From 7e70ae9988cb96756d0c8a90423bf99fdb6216bf Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 00:18:52 +0000 Subject: [PATCH 01/37] Ask for Touch ID without holding the send settings lock Admin used to hold the settings lock across the owner's Touch ID dialog, so sends waited for it. Admin now works out the change from a snapshot, asks with no lock held, then takes the lock, reloads, and applies the change only if the settings still match what the dialog showed; otherwise it answers overloaded and the owner reruns the command. A send reads and checks its settings under the same lock admin saves under. Turning sending off, removing a key and lowering a limit always save, so a failed write reaches the caller. The CLI's wait for key and limit changes is the Touch ID wait plus a minute. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- .../Sources/HelperCore/SendService.swift | 136 ++++++++++-------- .../helper/Sources/HelperCore/SendState.swift | 4 +- .../Sources/gbrain-apple-helper/main.swift | 4 +- .../Tests/HelperCoreTests/SendTests.swift | 134 +++++++++++++++-- changelog.d/gbra597-send-admin-lock.md | 8 ++ 6 files changed, 216 insertions(+), 72 deletions(-) create mode 100644 changelog.d/gbra597-send-admin-lock.md diff --git a/apple/helper/README.md b/apple/helper/README.md index a6e0f297b2f..bf26978b26b 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -100,7 +100,7 @@ Sending is off until the owner turns it on at the Mac. The owner's agent then se 3. On the agent's computer, make an Ed25519 key pair (`generateSendKeyPair` in `src/core/apple/send-sign.ts`) and keep the private key there. At the Mac, `gbrain-apple-helper send-key add --name --public-key-file -` with the public key on stdin asks for Touch ID once. 4. Full Disk Access (System Settings > Privacy & Security > Full Disk Access) must be on: the helper reads the Messages database to confirm each send. -With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. +With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done. ### Request diff --git a/apple/helper/Sources/HelperCore/SendService.swift b/apple/helper/Sources/HelperCore/SendService.swift index ec682f88f3d..9e96ec2bea4 100644 --- a/apple/helper/Sources/HelperCore/SendService.swift +++ b/apple/helper/Sources/HelperCore/SendService.swift @@ -51,13 +51,15 @@ public final class SendService { let nonces = NonceCache() let queue = DispatchQueue(label: "io.gbrain.apple-helper.send") let lock = NSLock() - let stateLock = NSRecursiveLock() + let stateLock: NSRecursiveLock var inflight = Set() var lastRetention: Date? public init(store: SendStateStore, switchedOn: @escaping () -> Bool, audit: SendAudit, messages: MessagesPort, ledger: DeliveryLedger, - banner: Banner, presence: OwnerPresence, clock: SendClock = SendClock(), confirmWindow: TimeInterval = 30, pollInterval: TimeInterval = 0.5) { + banner: Banner, presence: OwnerPresence, clock: SendClock = SendClock(), confirmWindow: TimeInterval = 30, pollInterval: TimeInterval = 0.5, + stateLock: NSRecursiveLock = NSRecursiveLock()) { self.store = store + self.stateLock = stateLock self.switchedOn = switchedOn self.audit = audit self.messages = messages @@ -139,6 +141,8 @@ public final class SendService { func serially(_ send: SendRequest, key: String, signer: SendKey, peer: UInt32) -> SendReply { let limits: SendLimits do { + stateLock.lock() + defer { stateLock.unlock() } var state = try store.load() ?? SendState() observeKill(&state) guard state.enabled, switchedOn() else { return fail(.sendDisabled) } @@ -342,62 +346,32 @@ public final class SendService { guard let fields = StrictJSON.flatObject(request.body), let action = fields["action"] else { return .problem(.badParam("the body must be a JSON object with an action")) } - stateLock.lock() - defer { stateLock.unlock() } + var automation: String? + var banners: Bool? + if action == "setup" { + switch messages.prepare(askPermission: true) { + case .ready: automation = "allowed" + case .automationDenied: automation = "denied" + case .signedOut: automation = "allowed_signed_out" + case .unavailable: automation = "messages_unavailable" + case .failed(let number): automation = "error_\(number)" + } + banners = banner.requestAuthorization() + } do { - var state = try store.load() ?? SendState() - observeKill(&state) - var automation: String? - var banners: Bool? - switch action { - case "status": - break - case "setup": - switch messages.prepare(askPermission: true) { - case .ready: automation = "allowed" - case .automationDenied: automation = "denied" - case .signedOut: automation = "allowed_signed_out" - case .unavailable: automation = "messages_unavailable" - case .failed(let number): automation = "error_\(number)" - } - banners = banner.requestAuthorization() - if !state.enabled { - try confirm("turn on sending iMessages for your agent") - state.enabled = true - try store.save(state) - } - case "off": - state.enabled = false - try store.save(state) - case "add_key": - guard let name = fields["name"], !name.isEmpty, name.count <= 64, - name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "._-".contains($0)) }), - let encoded = fields["public_key"] else { - throw Problem.badParam("add_key needs name (letters, digits, dot, underscore, hyphen) and public_key") - } - let key = SendKey(name: name, publicKey: Base64URL.encode(Self.publicKeyBytes(encoded) ?? [])) - guard key.rawKey != nil else { throw Problem.badParam("public_key must be a 32-byte Ed25519 public key in base64 or base64url") } - try confirm("add the send key \(name) (\(key.fingerprint)) so it can send iMessages as you") - state.keys.removeAll { $0.name == name } - state.keys.append(key) - try store.save(state) - case "remove_key": - guard let name = fields["name"], state.keys.contains(where: { $0.name == name }) else { throw Problem.notFound } - state.keys.removeAll { $0.name == name } - try store.save(state) - case "set_limits": - var raised = false - for (name, text) in fields where name != "action" { - guard let current = state.limits.value(name), let value = Int(text), (0...1000).contains(value) else { - throw Problem.badParam("unknown limit or bad value: \(name)") - } - raised = raised || value > current - state.limits.set(name, value) - } - if raised { try confirm("raise the limits on iMessages your agent can send") } - try store.save(state) - default: - throw Problem.badParam("unknown action \(action)") + let seen = try locked { () throws -> SendState in + var state = try store.load() ?? SendState() + observeKill(&state) + return state + } + let change = try Self.change(action, fields, seen) + if let reason = change.reason { try confirm(reason) } + let state = try locked { () throws -> SendState in + var current = try store.load() ?? SendState() + observeKill(¤t) + guard current == seen else { throw Problem.overloaded } + if change.save { try store.save(change.state) } + return change.state } let status = SendStatus(send: state.enabled && switchedOn() ? "on" : "off", keys: state.keys.map(\.name).sorted(), limits: state.limits, automation: automation, banners: banners) @@ -407,6 +381,54 @@ public final class SendService { } } + func locked(_ body: () throws -> T) rethrows -> T { + stateLock.lock() + defer { stateLock.unlock() } + return try body() + } + + static func change(_ action: String, _ fields: [String: String], _ state: SendState) throws -> (state: SendState, reason: String?, save: Bool) { + var next = state + switch action { + case "status": + return (next, nil, false) + case "setup": + guard !state.enabled else { return (next, nil, false) } + next.enabled = true + return (next, "turn on sending iMessages for your agent", true) + case "off": + next.enabled = false + return (next, nil, true) + case "add_key": + guard let name = fields["name"], !name.isEmpty, name.count <= 64, + name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "._-".contains($0)) }), + let encoded = fields["public_key"] else { + throw Problem.badParam("add_key needs name (letters, digits, dot, underscore, hyphen) and public_key") + } + let key = SendKey(name: name, publicKey: Base64URL.encode(publicKeyBytes(encoded) ?? [])) + guard key.rawKey != nil else { throw Problem.badParam("public_key must be a 32-byte Ed25519 public key in base64 or base64url") } + next.keys.removeAll { $0.name == name } + next.keys.append(key) + return (next, "add the send key \(name) (\(key.fingerprint)) so it can send iMessages as you", true) + case "remove_key": + guard let name = fields["name"], state.keys.contains(where: { $0.name == name }) else { throw Problem.notFound } + next.keys.removeAll { $0.name == name } + return (next, nil, true) + case "set_limits": + var raised = false + for (name, text) in fields where name != "action" { + guard let current = state.limits.value(name), let value = Int(text), (0...1000).contains(value) else { + throw Problem.badParam("unknown limit or bad value: \(name)") + } + raised = raised || value > current + next.limits.set(name, value) + } + return (next, raised ? "raise the limits on iMessages your agent can send" : nil, true) + default: + throw Problem.badParam("unknown action \(action)") + } + } + func confirm(_ reason: String) throws { guard presence.confirm(reason: reason) == .confirmed else { throw Problem.ownerPresenceUnavailable } } diff --git a/apple/helper/Sources/HelperCore/SendState.swift b/apple/helper/Sources/HelperCore/SendState.swift index b798d387223..b5defbb4e1d 100644 --- a/apple/helper/Sources/HelperCore/SendState.swift +++ b/apple/helper/Sources/HelperCore/SendState.swift @@ -189,6 +189,8 @@ public protocol OwnerPresence { } public final class LocalOwnerPresence: OwnerPresence { + public static let wait: TimeInterval = 120 + public init() {} public func confirm(reason: String) -> Presence { @@ -201,7 +203,7 @@ public final class LocalOwnerPresence: OwnerPresence { result = ok ? .confirmed : .unavailable done.signal() } - guard done.wait(timeout: .now() + 120) == .success else { + guard done.wait(timeout: .now() + Self.wait) == .success else { context.invalidate() return .unavailable } diff --git a/apple/helper/Sources/gbrain-apple-helper/main.swift b/apple/helper/Sources/gbrain-apple-helper/main.swift index 4382a42b27b..d960b9d10cc 100644 --- a/apple/helper/Sources/gbrain-apple-helper/main.swift +++ b/apple/helper/Sources/gbrain-apple-helper/main.swift @@ -139,7 +139,7 @@ case "send-key": guard let source = value("--public-key-file") else { fail("send-key add needs --public-key-file ", code: 64) } let data = source == "-" ? FileHandle.standardInput.readDataToEndOfFile() : FileManager.default.contents(atPath: source) guard let data, let key = String(data: data, encoding: .utf8) else { fail("could not read the public key", code: 66) } - admin(["action": "add_key", "name": keyName, "public_key": key.trimmingCharacters(in: .whitespacesAndNewlines)], timeout: 180) + admin(["action": "add_key", "name": keyName, "public_key": key.trimmingCharacters(in: .whitespacesAndNewlines)], timeout: LocalOwnerPresence.wait + 60) case "remove": admin(["action": "remove_key", "name": keyName]) default: @@ -157,7 +157,7 @@ case "send-limits": fields[parts[0]] = parts[1] } guard fields.count > 1 else { fail(usage, code: 64) } - admin(fields, timeout: 180) + admin(fields, timeout: LocalOwnerPresence.wait + 60) case "send-audit": guard arguments.dropFirst().first == "show", arguments.contains("--redacted") else { diff --git a/apple/helper/Tests/HelperCoreTests/SendTests.swift b/apple/helper/Tests/HelperCoreTests/SendTests.swift index 453763c4e02..d5328c84cba 100644 --- a/apple/helper/Tests/HelperCoreTests/SendTests.swift +++ b/apple/helper/Tests/HelperCoreTests/SendTests.swift @@ -9,18 +9,47 @@ let boxPublic = Base64URL.encode(Array(boxKey.publicKey.rawRepresentation)) let sendPeer = IPv4.parse("100.102.0.7")! final class MemoryStore: SendStateStore { + let lock = NSLock() var state: SendState? var saves = 0 var failure: Problem? + var saveFailure: Problem? + var saving: DispatchSemaphore? + var saveGate: DispatchSemaphore? init(_ state: SendState?) { self.state = state } func load() throws -> SendState? { + lock.lock() + defer { lock.unlock() } if let failure { throw failure } return state } func save(_ state: SendState) throws { + saving?.signal() + lock.lock() + let gate = saveGate + lock.unlock() + gate?.wait() + lock.lock() + defer { lock.unlock() } + if let saveFailure { throw saveFailure } self.state = state saves += 1 } + func release() { + lock.lock() + let gate = saveGate + saveGate = nil + lock.unlock() + gate?.signal() + } +} + +final class WatchedLock: NSRecursiveLock { + var waiting: DispatchSemaphore? + override func lock() { + waiting?.signal() + super.lock() + } } final class FakeMessages: MessagesPort { @@ -88,8 +117,10 @@ final class FakePresence: OwnerPresence { var answer = Presence.confirmed var reasons: [String] = [] var gate: DispatchSemaphore? + var entered: DispatchSemaphore? func confirm(reason: String) -> Presence { reasons.append(reason) + entered?.signal() gate?.wait() return answer } @@ -110,8 +141,9 @@ final class Harness { let clock = Clock() var switchedOn = true lazy var audit = SendAudit(directory: directory) + let lock = WatchedLock() lazy var service = SendService(store: store, switchedOn: { self.switchedOn }, audit: audit, messages: messages, ledger: ledger, banner: banner, - presence: presence, clock: clock.clock, confirmWindow: 30, pollInterval: 0.5) + presence: presence, clock: clock.clock, confirmWindow: 30, pollInterval: 0.5, stateLock: lock) init(limits: SendLimits = SendLimits(), enabled: Bool = true) { store = MemoryStore(SendState(enabled: enabled, keys: [SendKey(name: "box", publicKey: boxPublic)], limits: limits)) @@ -584,31 +616,111 @@ final class Harness { #expect(admin(h, ["action": "add_key", "name": "bad", "public_key": "abc"]).1["code"] as? String == "bad_param") } - @Test func aSendSeeingTheSwitchOffKeepsAKeyAddedMeanwhile() { + @Test func aSendSeeingTheSwitchOffDuringTouchIDMakesTheOwnerRerunTheChange() { let h = Harness() h.presence.gate = DispatchSemaphore(value: 0) + h.presence.entered = DispatchSemaphore(value: 0) let group = DispatchGroup() + var reply: (Int, [String: Any]) = (0, [:]) group.enter() DispatchQueue.global().async { - _ = self.admin(h, ["action": "add_key", "name": "second", "public_key": boxPublic]) + reply = self.admin(h, ["action": "add_key", "name": "second", "public_key": boxPublic]) group.leave() } - let deadline = Date().addingTimeInterval(10) - while h.presence.reasons.isEmpty && Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } + #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) h.switchedOn = false + #expect(h.send(h.request(h.body())).json["code"] as? String == "send_disabled") + h.presence.gate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(reply.1["code"] as? String == "overloaded") + #expect(h.store.state?.keys.map(\.name) == ["box"]) + #expect(h.store.state?.enabled == false) + #expect(h.messages.count == 0) + } + + @Test func aSendWaitingOnAKeyReplacementChecksTheNewKey() { + let h = Harness() + let other = Base64URL.encode(Array(Curve25519.Signing.PrivateKey().publicKey.rawRepresentation)) + h.store.saving = DispatchSemaphore(value: 0) + h.store.saveGate = DispatchSemaphore(value: 0) + let group = DispatchGroup() group.enter() DispatchQueue.global().async { - _ = h.send(h.request(h.body())) + _ = self.admin(h, ["action": "add_key", "name": "box", "public_key": other]) group.leave() } - Thread.sleep(forTimeInterval: 0.3) - h.presence.gate?.signal() - group.wait() - #expect(h.store.state?.keys.map(\.name).sorted() == ["box", "second"]) - #expect(h.store.state?.enabled == false) + #expect(h.store.saving?.wait(timeout: .now() + 10) == .success) + h.lock.waiting = DispatchSemaphore(value: 0) + var code: String? + group.enter() + DispatchQueue.global().async { + code = h.send(h.request(h.body())).json["code"] as? String + group.leave() + } + #expect(h.lock.waiting?.wait(timeout: .now() + 10) == .success) + h.store.release() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(h.store.state?.keys == [SendKey(name: "box", publicKey: other)]) + #expect(code == "unknown_send_key") #expect(h.messages.count == 0) } + @Test func aSendDuringAPendingTouchIDDoesNotWaitForIt() { + let h = Harness() + let other = Base64URL.encode(Array(Curve25519.Signing.PrivateKey().publicKey.rawRepresentation)) + h.presence.gate = DispatchSemaphore(value: 0) + h.presence.entered = DispatchSemaphore(value: 0) + let group = DispatchGroup() + group.enter() + DispatchQueue.global().async { + _ = self.admin(h, ["action": "add_key", "name": "box", "public_key": other]) + group.leave() + } + #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) + #expect(h.send(h.request(h.body())).status == 200) + #expect(h.messages.count == 1) + h.presence.gate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(h.store.state?.keys == [SendKey(name: "box", publicKey: other)]) + } + + @Test func anAdminChangeLandingDuringTouchIDIsRefused() { + let h = Harness() + let other = Base64URL.encode(Array(Curve25519.Signing.PrivateKey().publicKey.rawRepresentation)) + h.presence.gate = DispatchSemaphore(value: 0) + h.presence.entered = DispatchSemaphore(value: 0) + let group = DispatchGroup() + var reply: (Int, [String: Any]) = (0, [:]) + group.enter() + DispatchQueue.global().async { + reply = self.admin(h, ["action": "add_key", "name": "second", "public_key": other]) + group.leave() + } + #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) + #expect(admin(h, ["action": "remove_key", "name": "box"]).0 == 200) + h.presence.gate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(reply.1["code"] as? String == "overloaded") + #expect(h.presence.reasons.count == 1) + #expect(h.store.state?.keys.isEmpty == true) + } + + @Test(arguments: [["action": "off"], ["action": "remove_key", "name": "box"], ["action": "set_limits", "max_per_day": "50"]]) + func aChangeThatCannotBeSavedIsReported(fields: [String: String]) { + let h = Harness() + h.store.saveFailure = .sendKeysUnreadable + #expect(admin(h, fields).1["code"] as? String == "send_keys_unreadable") + #expect(h.presence.reasons.isEmpty) + } + + @Test func offIsSavedEvenWhenTheSwitchAlreadyLooksOff() { + let h = Harness() + h.switchedOn = false + h.store.saveFailure = .sendKeysUnreadable + #expect(admin(h, ["action": "off"]).1["code"] as? String == "send_keys_unreadable") + #expect(h.store.state?.enabled == true) + } + @Test func turningSendingBackOnAfterTheConfigSwitchNeedsTheOwner() { let h = Harness() h.switchedOn = false diff --git a/changelog.d/gbra597-send-admin-lock.md b/changelog.d/gbra597-send-admin-lock.md new file mode 100644 index 00000000000..5a97e03f3b4 --- /dev/null +++ b/changelog.d/gbra597-send-admin-lock.md @@ -0,0 +1,8 @@ +**Changing GBrain Helper's send settings at the Mac no longer holds up sends, and a Touch ID approval applies only to the settings it was shown for.** + +### Fixed +- Turning sending on, adding a send key and raising a limit ask for Touch ID. The helper used to hold its settings lock for the whole dialog, which can take up to two minutes, so any send arriving then waited. It now asks with no lock held, and sends keep working while the dialog is open. +- After the owner approves, the helper takes the lock, reads the settings again and applies the change only if they still match what the dialog was built from. If another change landed in the meantime it applies nothing and answers `overloaded`, and the owner runs the command again. +- A send now reads its settings, checks the kill switch and its key, and takes the limits under the same lock admin uses to save. A send that arrives while a key is being replaced is checked against the new key. +- `send-setup --off`, `send-key remove` and lowering a limit always write the keychain item, so a failed write is reported as an error rather than taken as done. +- `send-key add` and `send-limits set` wait for the helper's Touch ID wait plus a minute. From 080de7242b4baa8fa8ac4c7a5588c180a9b3483f Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 00:32:10 +0000 Subject: [PATCH 02/37] Run the send concurrency tests on their own threads The shared dispatch queue can hold new work behind blocked test work on a small CI runner, so the background steps never started. Each step now gets its own thread, and the lock test double restates its Sendable conformance. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../Tests/HelperCoreTests/SendTests.swift | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/apple/helper/Tests/HelperCoreTests/SendTests.swift b/apple/helper/Tests/HelperCoreTests/SendTests.swift index d5328c84cba..c5e619de323 100644 --- a/apple/helper/Tests/HelperCoreTests/SendTests.swift +++ b/apple/helper/Tests/HelperCoreTests/SendTests.swift @@ -44,7 +44,7 @@ final class MemoryStore: SendStateStore { } } -final class WatchedLock: NSRecursiveLock { +final class WatchedLock: NSRecursiveLock, @unchecked Sendable { var waiting: DispatchSemaphore? override func lock() { waiting?.signal() @@ -623,10 +623,10 @@ final class Harness { let group = DispatchGroup() var reply: (Int, [String: Any]) = (0, [:]) group.enter() - DispatchQueue.global().async { + Thread { reply = self.admin(h, ["action": "add_key", "name": "second", "public_key": boxPublic]) group.leave() - } + }.start() #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) h.switchedOn = false #expect(h.send(h.request(h.body())).json["code"] as? String == "send_disabled") @@ -645,18 +645,18 @@ final class Harness { h.store.saveGate = DispatchSemaphore(value: 0) let group = DispatchGroup() group.enter() - DispatchQueue.global().async { + Thread { _ = self.admin(h, ["action": "add_key", "name": "box", "public_key": other]) group.leave() - } + }.start() #expect(h.store.saving?.wait(timeout: .now() + 10) == .success) h.lock.waiting = DispatchSemaphore(value: 0) var code: String? group.enter() - DispatchQueue.global().async { + Thread { code = h.send(h.request(h.body())).json["code"] as? String group.leave() - } + }.start() #expect(h.lock.waiting?.wait(timeout: .now() + 10) == .success) h.store.release() #expect(group.wait(timeout: .now() + 10) == .success) @@ -672,10 +672,10 @@ final class Harness { h.presence.entered = DispatchSemaphore(value: 0) let group = DispatchGroup() group.enter() - DispatchQueue.global().async { + Thread { _ = self.admin(h, ["action": "add_key", "name": "box", "public_key": other]) group.leave() - } + }.start() #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) #expect(h.send(h.request(h.body())).status == 200) #expect(h.messages.count == 1) @@ -692,10 +692,10 @@ final class Harness { let group = DispatchGroup() var reply: (Int, [String: Any]) = (0, [:]) group.enter() - DispatchQueue.global().async { + Thread { reply = self.admin(h, ["action": "add_key", "name": "second", "public_key": other]) group.leave() - } + }.start() #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) #expect(admin(h, ["action": "remove_key", "name": "box"]).0 == 200) h.presence.gate?.signal() From dc44dbf0dd50233c2346d93161ad2c4d28355be6 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 00:54:16 +0000 Subject: [PATCH 03/37] Keep send-setup --off from being undone by an open Touch ID approval Changes that need no Touch ID (off, removing a key, lowering a limit) now read, change and save under one lock, and each such save counts. An approval that was open while one landed is refused with overloaded even when the saved value looks the same. send-setup --off exits with an error when the helper answers but cannot save. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- .../Sources/HelperCore/SendService.swift | 33 ++++++++++++------- .../Sources/gbrain-apple-helper/main.swift | 9 +++-- .../Tests/HelperCoreTests/SendTests.swift | 20 +++++++++++ changelog.d/gbra597-send-admin-lock.md | 2 +- 5 files changed, 50 insertions(+), 16 deletions(-) diff --git a/apple/helper/README.md b/apple/helper/README.md index bf26978b26b..93a56f08439 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -100,7 +100,7 @@ Sending is off until the owner turns it on at the Mac. The owner's agent then se 3. On the agent's computer, make an Ed25519 key pair (`generateSendKeyPair` in `src/core/apple/send-sign.ts`) and keep the private key there. At the Mac, `gbrain-apple-helper send-key add --name --public-key-file -` with the public key on stdin asks for Touch ID once. 4. Full Disk Access (System Settings > Privacy & Security > Full Disk Access) must be on: the helper reads the Messages database to confirm each send. -With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done. +With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. ### Request diff --git a/apple/helper/Sources/HelperCore/SendService.swift b/apple/helper/Sources/HelperCore/SendService.swift index 9e96ec2bea4..e263ff622af 100644 --- a/apple/helper/Sources/HelperCore/SendService.swift +++ b/apple/helper/Sources/HelperCore/SendService.swift @@ -52,6 +52,7 @@ public final class SendService { let queue = DispatchQueue(label: "io.gbrain.apple-helper.send") let lock = NSLock() let stateLock: NSRecursiveLock + var adminSaves = 0 var inflight = Set() var lastRetention: Date? @@ -359,19 +360,29 @@ public final class SendService { banners = banner.requestAuthorization() } do { - let seen = try locked { () throws -> SendState in - var state = try store.load() ?? SendState() - observeKill(&state) - return state - } - let change = try Self.change(action, fields, seen) - if let reason = change.reason { try confirm(reason) } - let state = try locked { () throws -> SendState in + let first = try locked { () throws -> (change: (state: SendState, reason: String?, save: Bool), seen: SendState, saves: Int) in var current = try store.load() ?? SendState() observeKill(¤t) - guard current == seen else { throw Problem.overloaded } - if change.save { try store.save(change.state) } - return change.state + let change = try Self.change(action, fields, current) + if change.reason == nil, change.save { + try store.save(change.state) + adminSaves += 1 + } + return (change, current, adminSaves) + } + var state = first.change.state + if let reason = first.change.reason { + try confirm(reason) + state = try locked { () throws -> SendState in + var current = try store.load() ?? SendState() + observeKill(¤t) + guard current == first.seen, adminSaves == first.saves else { throw Problem.overloaded } + if first.change.save { + try store.save(first.change.state) + adminSaves += 1 + } + return first.change.state + } } let status = SendStatus(send: state.enabled && switchedOn() ? "on" : "off", keys: state.keys.map(\.name).sorted(), limits: state.limits, automation: automation, banners: banners) diff --git a/apple/helper/Sources/gbrain-apple-helper/main.swift b/apple/helper/Sources/gbrain-apple-helper/main.swift index d960b9d10cc..4e08e30796b 100644 --- a/apple/helper/Sources/gbrain-apple-helper/main.swift +++ b/apple/helper/Sources/gbrain-apple-helper/main.swift @@ -123,11 +123,14 @@ case "send-setup": if off { print("sending is off in \(configPath)") let port = config.port - if let (status, _) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 10), status == 200 { - print("GBrain Helper confirmed sending is off") - } else { + guard let (status, body) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 10) else { print("GBrain Helper didn't answer; the config switch already stops every send") + exit(0) } + guard status == 200 else { + fail("GBrain Helper couldn't save sending off in its keychain item: \(String(decoding: body, as: UTF8.self)). The config switch already stops every send.", code: 1) + } + print("GBrain Helper confirmed sending is off") exit(0) } admin(["action": "setup"], timeout: 300) diff --git a/apple/helper/Tests/HelperCoreTests/SendTests.swift b/apple/helper/Tests/HelperCoreTests/SendTests.swift index c5e619de323..5ecd8574ced 100644 --- a/apple/helper/Tests/HelperCoreTests/SendTests.swift +++ b/apple/helper/Tests/HelperCoreTests/SendTests.swift @@ -705,6 +705,26 @@ final class Harness { #expect(h.store.state?.keys.isEmpty == true) } + @Test func anOffDuringAPendingSetupIsNotUndoneByTheSetup() { + let h = Harness() + #expect(admin(h, ["action": "off"]).0 == 200) + h.presence.gate = DispatchSemaphore(value: 0) + h.presence.entered = DispatchSemaphore(value: 0) + let group = DispatchGroup() + var reply: (Int, [String: Any]) = (0, [:]) + group.enter() + Thread { + reply = self.admin(h, ["action": "setup"]) + group.leave() + }.start() + #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) + #expect(admin(h, ["action": "off"]).0 == 200) + h.presence.gate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(reply.1["code"] as? String == "overloaded") + #expect(h.store.state?.enabled == false) + } + @Test(arguments: [["action": "off"], ["action": "remove_key", "name": "box"], ["action": "set_limits", "max_per_day": "50"]]) func aChangeThatCannotBeSavedIsReported(fields: [String: String]) { let h = Harness() diff --git a/changelog.d/gbra597-send-admin-lock.md b/changelog.d/gbra597-send-admin-lock.md index 5a97e03f3b4..9f8104f6575 100644 --- a/changelog.d/gbra597-send-admin-lock.md +++ b/changelog.d/gbra597-send-admin-lock.md @@ -4,5 +4,5 @@ - Turning sending on, adding a send key and raising a limit ask for Touch ID. The helper used to hold its settings lock for the whole dialog, which can take up to two minutes, so any send arriving then waited. It now asks with no lock held, and sends keep working while the dialog is open. - After the owner approves, the helper takes the lock, reads the settings again and applies the change only if they still match what the dialog was built from. If another change landed in the meantime it applies nothing and answers `overloaded`, and the owner runs the command again. - A send now reads its settings, checks the kill switch and its key, and takes the limits under the same lock admin uses to save. A send that arrives while a key is being replaced is checked against the new key. -- `send-setup --off`, `send-key remove` and lowering a limit always write the keychain item, so a failed write is reported as an error rather than taken as done. +- `send-setup --off`, `send-key remove` and lowering a limit always write the keychain item in one step, so a failed write is reported as an error rather than taken as done, and a Touch ID approval still open from an earlier command is refused instead of undoing them. `send-setup --off` exits with an error when the helper answers but can't save. - `send-key add` and `send-limits set` wait for the helper's Touch ID wait plus a minute. From 94dee66565e17d901c9a4812093508a54a4666c4 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 01:05:16 +0000 Subject: [PATCH 04/37] Say in the helper README what overloaded means from the send settings route Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apple/helper/README.md b/apple/helper/README.md index 93a56f08439..2518559f769 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -197,7 +197,7 @@ The request was over 8 KB, or a send's body over 32 KB. ### overloaded -Four requests were already running. Retry after the `Retry-After` seconds. +Four requests were already running. Retry after the `Retry-After` seconds. From `POST /v1/admin/send`, it can also mean another settings change landed while a Touch ID dialog was open, so nothing was applied; run the command again. ### no_access From 392a1acf35fc5220fdaecd6fb4bfa5b214df5599 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 01:22:23 +0000 Subject: [PATCH 05/37] Make turning iMessage sending off win over a text in progress and an open Touch ID dialog Each send checks the kill switch and its key again under the settings lock right before it hands the text to Messages. send-setup --off releases the config lock before an earlier setup's Touch ID wait can hold it, and an approval given after the switch went off is refused. --off now says what answered when the helper refuses. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- .../Sources/HelperCore/SendService.swift | 30 +++++++++---- .../Sources/gbrain-apple-helper/main.swift | 19 +++++--- .../Tests/HelperCoreTests/SendTests.swift | 44 +++++++++++++++++++ changelog.d/gbra597-send-stop-wins.md | 6 +++ 5 files changed, 87 insertions(+), 14 deletions(-) create mode 100644 changelog.d/gbra597-send-stop-wins.md diff --git a/apple/helper/README.md b/apple/helper/README.md index 2518559f769..37ee585a9de 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -100,7 +100,7 @@ Sending is off until the owner turns it on at the Mac. The owner's agent then se 3. On the agent's computer, make an Ed25519 key pair (`generateSendKeyPair` in `src/core/apple/send-sign.ts`) and keep the private key there. At the Mac, `gbrain-apple-helper send-key add --name --public-key-file -` with the public key on stdin asks for Touch ID once. 4. Full Disk Access (System Settings > Privacy & Security > Full Disk Access) must be on: the helper reads the Messages database to confirm each send. -With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. +With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. Each send checks the switch and its key once more right before it hands the text to Messages, so once `send-setup --off` or `send-key remove` has returned, no further text goes out; a text already being handed over (up to 20 seconds) finishes first. `send-setup --off` doesn't wait for a `send-setup` that is still at its Touch ID dialog, and approving that dialog afterwards answers `send_disabled`. When the helper answers `send-setup --off` with an error, the command says what answered, such as the helper being busy. ### Request diff --git a/apple/helper/Sources/HelperCore/SendService.swift b/apple/helper/Sources/HelperCore/SendService.swift index e263ff622af..dabb3a6c129 100644 --- a/apple/helper/Sources/HelperCore/SendService.swift +++ b/apple/helper/Sources/HelperCore/SendService.swift @@ -142,13 +142,7 @@ public final class SendService { func serially(_ send: SendRequest, key: String, signer: SendKey, peer: UInt32) -> SendReply { let limits: SendLimits do { - stateLock.lock() - defer { stateLock.unlock() } - var state = try store.load() ?? SendState() - observeKill(&state) - guard state.enabled, switchedOn() else { return fail(.sendDisabled) } - guard state.keys.contains(signer) else { return fail(.unknownSendKey) } - limits = state.limits + limits = try locked { try allowed(signer) }.limits } catch { return fail((error as? Problem) ?? .sendKeysUnreadable) } @@ -194,7 +188,18 @@ public final class SendService { let dispatch: DispatchResult switch messages.prepare(askPermission: false) { case .ready: - dispatch = messages.send(text: send.text, to: send.to) + let handed = locked { () -> Result in + do { + _ = try allowed(signer) + } catch { + return .failure((error as? Problem) ?? .sendKeysUnreadable) + } + return .success(messages.send(text: send.text, to: send.to)) + } + switch handed { + case .success(let result): dispatch = result + case .failure(let stopped): return refuse(stopped, error: nil, pending: pending) + } case .automationDenied: return refuse(.automationDenied, error: -1743, pending: pending) case .signedOut: @@ -224,6 +229,14 @@ public final class SendService { return record(.from(delivery), pending: pending) } + func allowed(_ signer: SendKey) throws -> SendState { + var state = try store.load() ?? SendState() + observeKill(&state) + guard state.enabled, switchedOn() else { throw Problem.sendDisabled } + guard state.keys.contains(signer) else { throw Problem.unknownSendKey } + return state + } + func rateProblem(_ recipient: String, firstContact: Bool, limits: SendLimits, now: Date) -> Problem? { let day = audit.attempts(since: now.addingTimeInterval(-86400)) func check(_ window: TimeInterval, _ cap: Int, _ what: String, _ filter: (AuditRecord) -> Bool) -> Problem? { @@ -377,6 +390,7 @@ public final class SendService { var current = try store.load() ?? SendState() observeKill(¤t) guard current == first.seen, adminSaves == first.saves else { throw Problem.overloaded } + guard current.enabled || !first.change.state.enabled || switchedOn() else { throw Problem.sendDisabled } if first.change.save { try store.save(first.change.state) adminSaves += 1 diff --git a/apple/helper/Sources/gbrain-apple-helper/main.swift b/apple/helper/Sources/gbrain-apple-helper/main.swift index 4e08e30796b..c294e7d0b34 100644 --- a/apple/helper/Sources/gbrain-apple-helper/main.swift +++ b/apple/helper/Sources/gbrain-apple-helper/main.swift @@ -41,11 +41,16 @@ func save(_ config: Config) { } } -func lockedConfig() -> Config { +func lockConfigFile() -> Int32 { _ = loadConfig() let lockPath = configPath + ".lock" let lockFile = Darwin.open(lockPath, O_CREAT | O_RDWR, 0o600) guard lockFile >= 0, flock(lockFile, LOCK_EX) == 0 else { fail("could not lock \(lockPath)", code: 75) } + return lockFile +} + +func lockedConfig() -> Config { + _ = lockConfigFile() return loadConfig().0 } @@ -113,22 +118,26 @@ case "token": } case "send-setup": - var config = lockedConfig() + let configLock = lockConfigFile() + var config = loadConfig().0 let off = arguments.contains("--off") - if !off, config.send?.enabled != true, AdminClient.post(port: UInt16(config.port), fields: ["action": "off"], timeout: 10)?.0 != 200 { + if !off, config.send?.enabled != true, AdminClient.post(port: UInt16(config.port), fields: ["action": "off"], timeout: 40)?.0 != 200 { fail("GBrain Helper isn't answering on 127.0.0.1:\(config.port). Start it, then run send-setup again.", code: 69) } config.send = SendSetting(enabled: !off) save(config) + Darwin.close(configLock) if off { print("sending is off in \(configPath)") let port = config.port - guard let (status, body) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 10) else { + guard let (status, body) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 40) else { print("GBrain Helper didn't answer; the config switch already stops every send") exit(0) } guard status == 200 else { - fail("GBrain Helper couldn't save sending off in its keychain item: \(String(decoding: body, as: UTF8.self)). The config switch already stops every send.", code: 1) + let code = ((try? JSONSerialization.jsonObject(with: Data(body))) as? [String: Any])?["code"] as? String ?? "HTTP \(status)" + let answer = code == "overloaded" ? "GBrain Helper was busy (overloaded)" : "GBrain Helper answered \(code)" + fail("\(answer) and didn't record sending off in its keychain item. The config switch already stops every send.", code: 1) } print("GBrain Helper confirmed sending is off") exit(0) diff --git a/apple/helper/Tests/HelperCoreTests/SendTests.swift b/apple/helper/Tests/HelperCoreTests/SendTests.swift index 5ecd8574ced..b53b7038948 100644 --- a/apple/helper/Tests/HelperCoreTests/SendTests.swift +++ b/apple/helper/Tests/HelperCoreTests/SendTests.swift @@ -60,9 +60,13 @@ final class FakeMessages: MessagesPort { var askedPermission = false var gate: DispatchSemaphore? var onSend: ((String, String) -> Void)? + var preparing: DispatchSemaphore? + var prepareGate: DispatchSemaphore? func prepare(askPermission: Bool) -> PrepareResult { if askPermission { askedPermission = true } + preparing?.signal() + prepareGate?.wait() return prepareResult } @@ -725,6 +729,46 @@ final class Harness { #expect(h.store.state?.enabled == false) } + @Test(arguments: [["action": "off"], ["action": "remove_key", "name": "box"]]) + func aSendHeldBeforeMessagesIsStoppedByAChangeThatAlreadyReturned(fields: [String: String]) { + let h = Harness() + h.messages.preparing = DispatchSemaphore(value: 0) + h.messages.prepareGate = DispatchSemaphore(value: 0) + let group = DispatchGroup() + var reply: (status: Int, json: [String: Any]) = (0, [:]) + group.enter() + Thread { + reply = h.send(h.request(h.body())) + group.leave() + }.start() + #expect(h.messages.preparing?.wait(timeout: .now() + 10) == .success) + #expect(admin(h, fields).0 == 200) + h.messages.prepareGate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(reply.json["code"] as? String == (fields["action"] == "off" ? "send_disabled" : "unknown_send_key")) + #expect(h.messages.count == 0) + } + + @Test func aSetupApprovedAfterTheConfigSwitchWentOffIsRefused() { + let h = Harness() + #expect(admin(h, ["action": "off"]).0 == 200) + h.presence.gate = DispatchSemaphore(value: 0) + h.presence.entered = DispatchSemaphore(value: 0) + let group = DispatchGroup() + var reply: (Int, [String: Any]) = (0, [:]) + group.enter() + Thread { + reply = self.admin(h, ["action": "setup"]) + group.leave() + }.start() + #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) + h.switchedOn = false + h.presence.gate?.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(reply.1["code"] as? String == "send_disabled") + #expect(h.store.state?.enabled == false) + } + @Test(arguments: [["action": "off"], ["action": "remove_key", "name": "box"], ["action": "set_limits", "max_per_day": "50"]]) func aChangeThatCannotBeSavedIsReported(fields: [String: String]) { let h = Harness() diff --git a/changelog.d/gbra597-send-stop-wins.md b/changelog.d/gbra597-send-stop-wins.md new file mode 100644 index 00000000000..1357a0f4df9 --- /dev/null +++ b/changelog.d/gbra597-send-stop-wins.md @@ -0,0 +1,6 @@ +**Turning GBrain Helper's sending off now wins over a text already in progress and over a Touch ID dialog still open.** + +### Fixed +- Each send checks the kill switch and its key again right before it hands the text to Messages, under the lock the settings are saved under. A text that had passed its first check while `send-setup --off` or `send-key remove` ran is now refused instead of sent. +- `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. +- When the helper answers `send-setup --off` with an error, the command now says what answered (for example that the helper was busy) instead of blaming the keychain. From d36497ab6e533ab097b266b64d4d118cefeef58c Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 01:31:13 +0000 Subject: [PATCH 06/37] Report an unconfirmed send-setup --off as an error, and answer send_disabled for a setup approved after it A text already being handed to Messages can outlast the CLI's wait, so --off now exits nonzero when the helper doesn't confirm. A Touch ID approval that would turn sending on after the switch went off answers send_disabled before the overloaded check, and send-key remove waits as long as --off. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- apple/helper/Sources/HelperCore/SendService.swift | 2 +- apple/helper/Sources/gbrain-apple-helper/main.swift | 5 ++--- apple/helper/Tests/HelperCoreTests/SendTests.swift | 8 +++++--- changelog.d/gbra597-send-stop-wins.md | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/apple/helper/README.md b/apple/helper/README.md index 37ee585a9de..8bdb1cadbba 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -100,7 +100,7 @@ Sending is off until the owner turns it on at the Mac. The owner's agent then se 3. On the agent's computer, make an Ed25519 key pair (`generateSendKeyPair` in `src/core/apple/send-sign.ts`) and keep the private key there. At the Mac, `gbrain-apple-helper send-key add --name --public-key-file -` with the public key on stdin asks for Touch ID once. 4. Full Disk Access (System Settings > Privacy & Security > Full Disk Access) must be on: the helper reads the Messages database to confirm each send. -With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. Each send checks the switch and its key once more right before it hands the text to Messages, so once `send-setup --off` or `send-key remove` has returned, no further text goes out; a text already being handed over (up to 20 seconds) finishes first. `send-setup --off` doesn't wait for a `send-setup` that is still at its Touch ID dialog, and approving that dialog afterwards answers `send_disabled`. When the helper answers `send-setup --off` with an error, the command says what answered, such as the helper being busy. +With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. Each send checks the switch and its key once more right before it hands the text to Messages, so once `send-setup --off` or `send-key remove` has returned, no further text goes out; a text already being handed over finishes first, which can take up to about 30 seconds. If the helper doesn't confirm within 40 seconds, `send-setup --off` exits with an error, because such a text may still go out. `send-setup --off` doesn't wait for a `send-setup` that is still at its Touch ID dialog, and approving that dialog afterwards answers `send_disabled`. When the helper answers `send-setup --off` with an error, the command says what answered, such as the helper being busy. ### Request diff --git a/apple/helper/Sources/HelperCore/SendService.swift b/apple/helper/Sources/HelperCore/SendService.swift index dabb3a6c129..695cd688de3 100644 --- a/apple/helper/Sources/HelperCore/SendService.swift +++ b/apple/helper/Sources/HelperCore/SendService.swift @@ -389,8 +389,8 @@ public final class SendService { state = try locked { () throws -> SendState in var current = try store.load() ?? SendState() observeKill(¤t) - guard current == first.seen, adminSaves == first.saves else { throw Problem.overloaded } guard current.enabled || !first.change.state.enabled || switchedOn() else { throw Problem.sendDisabled } + guard current == first.seen, adminSaves == first.saves else { throw Problem.overloaded } if first.change.save { try store.save(first.change.state) adminSaves += 1 diff --git a/apple/helper/Sources/gbrain-apple-helper/main.swift b/apple/helper/Sources/gbrain-apple-helper/main.swift index c294e7d0b34..5e2dd2fce7c 100644 --- a/apple/helper/Sources/gbrain-apple-helper/main.swift +++ b/apple/helper/Sources/gbrain-apple-helper/main.swift @@ -131,8 +131,7 @@ case "send-setup": print("sending is off in \(configPath)") let port = config.port guard let (status, body) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 40) else { - print("GBrain Helper didn't answer; the config switch already stops every send") - exit(0) + fail("GBrain Helper didn't confirm within 40 seconds. The config switch stops every new send, but a text it was already handing to Messages may still go out.", code: 69) } guard status == 200 else { let code = ((try? JSONSerialization.jsonObject(with: Data(body))) as? [String: Any])?["code"] as? String ?? "HTTP \(status)" @@ -153,7 +152,7 @@ case "send-key": guard let data, let key = String(data: data, encoding: .utf8) else { fail("could not read the public key", code: 66) } admin(["action": "add_key", "name": keyName, "public_key": key.trimmingCharacters(in: .whitespacesAndNewlines)], timeout: LocalOwnerPresence.wait + 60) case "remove": - admin(["action": "remove_key", "name": keyName]) + admin(["action": "remove_key", "name": keyName], timeout: 40) default: fail(usage, code: 64) } diff --git a/apple/helper/Tests/HelperCoreTests/SendTests.swift b/apple/helper/Tests/HelperCoreTests/SendTests.swift index b53b7038948..5ef49bda8f0 100644 --- a/apple/helper/Tests/HelperCoreTests/SendTests.swift +++ b/apple/helper/Tests/HelperCoreTests/SendTests.swift @@ -620,7 +620,7 @@ final class Harness { #expect(admin(h, ["action": "add_key", "name": "bad", "public_key": "abc"]).1["code"] as? String == "bad_param") } - @Test func aSendSeeingTheSwitchOffDuringTouchIDMakesTheOwnerRerunTheChange() { + @Test func aSendSeeingTheSwitchOffDuringTouchIDRefusesTheChange() { let h = Harness() h.presence.gate = DispatchSemaphore(value: 0) h.presence.entered = DispatchSemaphore(value: 0) @@ -636,7 +636,7 @@ final class Harness { #expect(h.send(h.request(h.body())).json["code"] as? String == "send_disabled") h.presence.gate?.signal() #expect(group.wait(timeout: .now() + 10) == .success) - #expect(reply.1["code"] as? String == "overloaded") + #expect(reply.1["code"] as? String == "send_disabled") #expect(h.store.state?.keys.map(\.name) == ["box"]) #expect(h.store.state?.enabled == false) #expect(h.messages.count == 0) @@ -749,7 +749,8 @@ final class Harness { #expect(h.messages.count == 0) } - @Test func aSetupApprovedAfterTheConfigSwitchWentOffIsRefused() { + @Test(arguments: [true, false]) + func aSetupApprovedAfterTheConfigSwitchWentOffIsRefused(helperHeardOff: Bool) { let h = Harness() #expect(admin(h, ["action": "off"]).0 == 200) h.presence.gate = DispatchSemaphore(value: 0) @@ -763,6 +764,7 @@ final class Harness { }.start() #expect(h.presence.entered?.wait(timeout: .now() + 10) == .success) h.switchedOn = false + if helperHeardOff { #expect(admin(h, ["action": "off"]).0 == 200) } h.presence.gate?.signal() #expect(group.wait(timeout: .now() + 10) == .success) #expect(reply.1["code"] as? String == "send_disabled") diff --git a/changelog.d/gbra597-send-stop-wins.md b/changelog.d/gbra597-send-stop-wins.md index 1357a0f4df9..775b6d39c42 100644 --- a/changelog.d/gbra597-send-stop-wins.md +++ b/changelog.d/gbra597-send-stop-wins.md @@ -3,4 +3,4 @@ ### Fixed - Each send checks the kill switch and its key again right before it hands the text to Messages, under the lock the settings are saved under. A text that had passed its first check while `send-setup --off` or `send-key remove` ran is now refused instead of sent. - `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. -- When the helper answers `send-setup --off` with an error, the command now says what answered (for example that the helper was busy) instead of blaming the keychain. +- When the helper answers `send-setup --off` with an error, the command now says what answered (for example that the helper was busy) instead of blaming the keychain. When the helper doesn't confirm within 40 seconds, the command exits with an error instead of reporting success, because a text already being handed to Messages may still go out. From b6464d0895933292858294940cf6ed5da7bf9526 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 01:43:21 +0000 Subject: [PATCH 07/37] Keep sending off when send-setup --off races a setup, and say what --off actually did send-setup --off now holds the config file lock until the helper has answered, so a send-setup started meanwhile waits for it. A refused connection means the helper isn't running: --off says so and exits 0, because the config switch alone stops every send; 69 stays for a helper that doesn't answer in time. The success text for --off and send-key remove says no new text is handed to Messages, and that a text Messages has already accepted may still be delivered. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apple/helper/README.md | 2 +- .../Sources/HelperCore/AdminClient.swift | 18 ++- .../helper/Sources/HelperCore/SendSetup.swift | 74 +++++++++ .../Sources/gbrain-apple-helper/main.swift | 41 ++--- .../HelperCoreTests/SendSetupTests.swift | 146 ++++++++++++++++++ changelog.d/gbra597-send-stop-wins.md | 8 +- 6 files changed, 250 insertions(+), 39 deletions(-) create mode 100644 apple/helper/Sources/HelperCore/SendSetup.swift create mode 100644 apple/helper/Tests/HelperCoreTests/SendSetupTests.swift diff --git a/apple/helper/README.md b/apple/helper/README.md index 8bdb1cadbba..2a085287908 100644 --- a/apple/helper/README.md +++ b/apple/helper/README.md @@ -100,7 +100,7 @@ Sending is off until the owner turns it on at the Mac. The owner's agent then se 3. On the agent's computer, make an Ed25519 key pair (`generateSendKeyPair` in `src/core/apple/send-sign.ts`) and keep the private key there. At the Mac, `gbrain-apple-helper send-key add --name --public-key-file -` with the public key on stdin asks for Touch ID once. 4. Full Disk Access (System Settings > Privacy & Security > Full Disk Access) must be on: the helper reads the Messages database to confirm each send. -With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. Each send checks the switch and its key once more right before it hands the text to Messages, so once `send-setup --off` or `send-key remove` has returned, no further text goes out; a text already being handed over finishes first, which can take up to about 30 seconds. If the helper doesn't confirm within 40 seconds, `send-setup --off` exits with an error, because such a text may still go out. `send-setup --off` doesn't wait for a `send-setup` that is still at its Touch ID dialog, and approving that dialog afterwards answers `send_disabled`. When the helper answers `send-setup --off` with an error, the command says what answered, such as the helper being busy. +With nobody logged in at the Mac, the Touch ID steps fail with `owner_presence_unavailable`. Removing a key, lowering a limit and `send-setup --off` need no prompt. Sends keep working while a Touch ID dialog is open. If another settings change lands while the dialog is open, the helper applies nothing and answers `overloaded`; run the command again to see the dialog for the settings as they are now. `send-setup --off`, `send-key remove` and a lowered limit always write the keychain item, so a failed write is reported instead of being taken as done, and a Touch ID approval still open from an earlier command can't undo them. Each send checks the switch and its key once more right before it hands the text to Messages. So once `send-setup --off` or `send-key remove` has returned, no new text is handed to Messages. A text Messages has already accepted may still be delivered, and one already being handed over finishes first, which can take up to about 30 seconds. `send-setup --off` holds the config file lock until the helper has answered, so a `send-setup` started meanwhile waits for it. It doesn't wait for a `send-setup` that is still at its Touch ID dialog, and approving that dialog afterwards answers `send_disabled`. If the helper isn't running, `--off` says so and exits 0, because the config switch alone stops every send; if the helper doesn't confirm within 40 seconds, it exits 69, because a text being handed over may still go out. When the helper answers with an error, the command says what answered, such as the helper being busy. ### Request diff --git a/apple/helper/Sources/HelperCore/AdminClient.swift b/apple/helper/Sources/HelperCore/AdminClient.swift index 9e94e61b9e9..eedab6106ac 100644 --- a/apple/helper/Sources/HelperCore/AdminClient.swift +++ b/apple/helper/Sources/HelperCore/AdminClient.swift @@ -1,22 +1,26 @@ import Foundation public enum AdminClient { - public static func post(port: UInt16, fields: [String: String], timeout: TimeInterval) -> (status: Int, body: Data)? { - guard let url = URL(string: "http://127.0.0.1:\(port)\(SendService.adminRoute)") else { return nil } + public static func post(port: UInt16, fields: [String: String], timeout: TimeInterval) -> AdminReply { + guard let url = URL(string: "http://127.0.0.1:\(port)\(SendService.adminRoute)") else { return .noReply } var request = URLRequest(url: url, timeoutInterval: timeout) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body = "{" + fields.sorted { $0.key < $1.key }.map { "\(StrictJSON.quote($0.key)):\(StrictJSON.quote($0.value))" }.joined(separator: ",") + "}" request.httpBody = Data(body.utf8) let done = DispatchSemaphore(value: 0) - var result: (Int, Data)? + var reply = AdminReply.noReply let configuration = URLSessionConfiguration.ephemeral configuration.connectionProxyDictionary = [:] - URLSession(configuration: configuration).dataTask(with: request) { data, response, _ in - if let http = response as? HTTPURLResponse { result = (http.statusCode, data ?? Data()) } + URLSession(configuration: configuration).dataTask(with: request) { data, response, error in + if let http = response as? HTTPURLResponse { + reply = .answered(status: http.statusCode, body: data ?? Data()) + } else if (error as? URLError)?.code == .cannotConnectToHost { + reply = .notRunning + } done.signal() }.resume() - _ = done.wait(timeout: .now() + timeout + 5) - return result + guard done.wait(timeout: .now() + timeout + 5) == .success else { return .noReply } + return reply } } diff --git a/apple/helper/Sources/HelperCore/SendSetup.swift b/apple/helper/Sources/HelperCore/SendSetup.swift new file mode 100644 index 00000000000..3201f42af05 --- /dev/null +++ b/apple/helper/Sources/HelperCore/SendSetup.swift @@ -0,0 +1,74 @@ +import Foundation + +public enum AdminReply: Equatable { + case answered(status: Int, body: Data) + case notRunning + case noReply +} + +public struct SendSetupResult: Equatable { + public var out: [String] + public var err: String? + public var code: Int32 +} + +public struct SendSetup { + public static let offWait: TimeInterval = 40 + public static let setupWait: TimeInterval = 300 + public static let afterStop = "No new text will be handed to Messages. A text Messages has already accepted may still be delivered." + + let configPath: String + let lockConfig: () -> () -> Void + let loadConfig: () -> Config + let saveConfig: (Config) -> Void + let post: ([String: String], TimeInterval) -> AdminReply + + public init(configPath: String, lockConfig: @escaping () -> () -> Void, loadConfig: @escaping () -> Config, + saveConfig: @escaping (Config) -> Void, post: @escaping ([String: String], TimeInterval) -> AdminReply) { + self.configPath = configPath + self.lockConfig = lockConfig + self.loadConfig = loadConfig + self.saveConfig = saveConfig + self.post = post + } + + public func off() -> SendSetupResult { + let unlock = lockConfig() + defer { unlock() } + var config = loadConfig() + config.send = SendSetting(enabled: false) + saveConfig(config) + let saved = "sending is off in \(configPath)" + switch post(["action": "off"], Self.offWait) { + case .notRunning: + return SendSetupResult(out: [saved, "GBrain Helper isn't running, and the config switch stops every send."], err: nil, code: 0) + case .noReply: + return SendSetupResult(out: [saved], err: "GBrain Helper didn't confirm within \(Int(Self.offWait)) seconds. The config switch stops any new text being handed to Messages, but a text it was already handing over may still go out.", code: 69) + case .answered(200, _): + return SendSetupResult(out: [saved, "GBrain Helper confirmed sending is off. " + Self.afterStop], err: nil, code: 0) + case .answered(let status, let body): + let code = ((try? JSONSerialization.jsonObject(with: body)) as? [String: Any])?["code"] as? String ?? "HTTP \(status)" + let answer = code == "overloaded" ? "GBrain Helper was busy (overloaded)" : "GBrain Helper answered \(code)" + return SendSetupResult(out: [saved], err: "\(answer) and didn't record sending off in its keychain item. The config switch still stops any new text being handed to Messages.", code: 1) + } + } + + public func on() -> SendSetupResult { + let unlock = lockConfig() + var config = loadConfig() + let notAnswering = "GBrain Helper isn't answering on 127.0.0.1:\(config.port). Start it, then run send-setup again." + if config.send?.enabled != true { + guard case .answered(200, _) = post(["action": "off"], Self.offWait) else { + unlock() + return SendSetupResult(out: [], err: notAnswering, code: 69) + } + } + config.send = SendSetting(enabled: true) + saveConfig(config) + unlock() + guard case .answered(let status, let body) = post(["action": "setup"], Self.setupWait) else { + return SendSetupResult(out: [], err: notAnswering, code: 69) + } + return SendSetupResult(out: [String(decoding: body, as: UTF8.self)], err: nil, code: status == 200 ? 0 : 1) + } +} diff --git a/apple/helper/Sources/gbrain-apple-helper/main.swift b/apple/helper/Sources/gbrain-apple-helper/main.swift index 5e2dd2fce7c..a860708f7b9 100644 --- a/apple/helper/Sources/gbrain-apple-helper/main.swift +++ b/apple/helper/Sources/gbrain-apple-helper/main.swift @@ -61,12 +61,13 @@ func printJSON(_ value: T) { if let data = try? encoder.encode(value) { print(String(decoding: data, as: UTF8.self)) } } -func admin(_ fields: [String: String], timeout: TimeInterval = 30) -> Never { +func admin(_ fields: [String: String], timeout: TimeInterval = 30, success: String? = nil) -> Never { let port = loadConfig().1.port - guard let (status, body) = AdminClient.post(port: port, fields: fields, timeout: timeout) else { + guard case .answered(let status, let body) = AdminClient.post(port: port, fields: fields, timeout: timeout) else { fail("GBrain Helper isn't answering on 127.0.0.1:\(port). Check it is running: launchctl print gui/\(getuid())/\(HelperIdentity.bundleId)", code: 69) } print(String(decoding: body, as: UTF8.self)) + if status == 200, let success { print(success) } exit(status == 200 ? 0 : 1) } @@ -118,30 +119,15 @@ case "token": } case "send-setup": - let configLock = lockConfigFile() - var config = loadConfig().0 - let off = arguments.contains("--off") - if !off, config.send?.enabled != true, AdminClient.post(port: UInt16(config.port), fields: ["action": "off"], timeout: 40)?.0 != 200 { - fail("GBrain Helper isn't answering on 127.0.0.1:\(config.port). Start it, then run send-setup again.", code: 69) - } - config.send = SendSetting(enabled: !off) - save(config) - Darwin.close(configLock) - if off { - print("sending is off in \(configPath)") - let port = config.port - guard let (status, body) = AdminClient.post(port: UInt16(port), fields: ["action": "off"], timeout: 40) else { - fail("GBrain Helper didn't confirm within 40 seconds. The config switch stops every new send, but a text it was already handing to Messages may still go out.", code: 69) - } - guard status == 200 else { - let code = ((try? JSONSerialization.jsonObject(with: Data(body))) as? [String: Any])?["code"] as? String ?? "HTTP \(status)" - let answer = code == "overloaded" ? "GBrain Helper was busy (overloaded)" : "GBrain Helper answered \(code)" - fail("\(answer) and didn't record sending off in its keychain item. The config switch already stops every send.", code: 1) - } - print("GBrain Helper confirmed sending is off") - exit(0) - } - admin(["action": "setup"], timeout: 300) + let setup = SendSetup(configPath: configPath, + lockConfig: { let lockFile = lockConfigFile(); return { Darwin.close(lockFile) } }, + loadConfig: { loadConfig().0 }, + saveConfig: save, + post: { fields, timeout in AdminClient.post(port: loadConfig().1.port, fields: fields, timeout: timeout) }) + let result = arguments.contains("--off") ? setup.off() : setup.on() + result.out.forEach { print($0) } + if let err = result.err { FileHandle.standardError.write(Data("\(name): \(err)\n".utf8)) } + exit(result.code) case "send-key": guard let keyName = value("--name") else { fail(usage, code: 64) } @@ -152,7 +138,8 @@ case "send-key": guard let data, let key = String(data: data, encoding: .utf8) else { fail("could not read the public key", code: 66) } admin(["action": "add_key", "name": keyName, "public_key": key.trimmingCharacters(in: .whitespacesAndNewlines)], timeout: LocalOwnerPresence.wait + 60) case "remove": - admin(["action": "remove_key", "name": keyName], timeout: 40) + admin(["action": "remove_key", "name": keyName], timeout: 40, + success: "No new text signed with the key \(keyName) will be handed to Messages. A text Messages has already accepted may still be delivered.") default: fail(usage, code: 64) } diff --git a/apple/helper/Tests/HelperCoreTests/SendSetupTests.swift b/apple/helper/Tests/HelperCoreTests/SendSetupTests.swift new file mode 100644 index 00000000000..5df0eb3fb53 --- /dev/null +++ b/apple/helper/Tests/HelperCoreTests/SendSetupTests.swift @@ -0,0 +1,146 @@ +import Darwin +import Foundation +import Testing +@testable import HelperCore + +final class SetupWorld: @unchecked Sendable { + let lock = WatchedLock() + let logLock = NSLock() + var log: [String] = [] + var config = Config(port: 8792) + var replies: [String: AdminReply] = [:] + var holds: [String: (entered: DispatchSemaphore, gate: DispatchSemaphore)] = [:] + + func note(_ event: String) { + logLock.lock() + log.append(event) + logLock.unlock() + } + + var events: [String] { + logLock.lock() + defer { logLock.unlock() } + return log + } + + func hold(_ event: String) { + holds[event] = (DispatchSemaphore(value: 0), DispatchSemaphore(value: 0)) + } + + var setup: SendSetup { + SendSetup(configPath: "/tmp/config.json", + lockConfig: { self.lock.lock(); return { self.lock.unlock() } }, + loadConfig: { self.config }, + saveConfig: { self.config = $0; self.note("config \($0.send?.enabled == true ? "on" : "off")") }, + post: { fields, _ in + let event = "post \(fields["action"] ?? "")" + self.note(event) + if let hold = self.holds.removeValue(forKey: event) { + hold.entered.signal() + hold.gate.wait() + } + return self.replies[fields["action"] ?? ""] ?? .answered(status: 200, body: Data("{}".utf8)) + }) + } +} + +func loopbackSocket() -> (fd: Int32, port: UInt16) { + let fd = socket(AF_INET, SOCK_STREAM, 0) + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + address.sin_addr.s_addr = inet_addr("127.0.0.1") + var length = socklen_t(MemoryLayout.size) + _ = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, length) } } + _ = listen(fd, 4) + _ = withUnsafeMutablePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &length) } } + return (fd, UInt16(bigEndian: address.sin_port)) +} + +@Suite struct SendSetupTests { + @Test func offTakesEffectWhileASetupWaitsAtItsTouchIDDialog() { + let world = SetupWorld() + world.hold("post setup") + world.replies["setup"] = .answered(status: 503, body: Data(#"{"code":"send_disabled"}"#.utf8)) + let group = DispatchGroup() + var setupResult = SendSetupResult(out: [], err: nil, code: -1) + let hold = world.holds["post setup"] + group.enter() + Thread { + setupResult = world.setup.on() + group.leave() + }.start() + #expect(hold?.entered.wait(timeout: .now() + 10) == .success) + let offResult = world.setup.off() + #expect(offResult.code == 0) + #expect(offResult.out.last == "GBrain Helper confirmed sending is off. " + SendSetup.afterStop) + hold?.gate.signal() + #expect(group.wait(timeout: .now() + 10) == .success) + #expect(setupResult.code != 0) + #expect(world.config.send?.enabled == false) + #expect(world.events == ["post off", "config on", "post setup", "config off", "post off"]) + } + + @Test func aSetupStartedWhileOffIsInFlightWaitsForOffToFinish() { + let world = SetupWorld() + world.config.send = SendSetting(enabled: true) + world.hold("post off") + let hold = world.holds["post off"] + let offGroup = DispatchGroup() + var offResult = SendSetupResult(out: [], err: nil, code: -1) + offGroup.enter() + Thread { + offResult = world.setup.off() + offGroup.leave() + }.start() + #expect(hold?.entered.wait(timeout: .now() + 10) == .success) + world.lock.waiting = DispatchSemaphore(value: 0) + let setupGroup = DispatchGroup() + setupGroup.enter() + Thread { + _ = world.setup.on() + setupGroup.leave() + }.start() + #expect(world.lock.waiting?.wait(timeout: .now() + 10) == .success) + #expect(world.events == ["config off", "post off"]) + hold?.gate.signal() + #expect(offGroup.wait(timeout: .now() + 10) == .success) + #expect(offResult.code == 0) + #expect(setupGroup.wait(timeout: .now() + 10) == .success) + #expect(world.events == ["config off", "post off", "post off", "config on", "post setup"]) + } + + @Test(arguments: [(AdminReply.notRunning, Int32(0)), (AdminReply.noReply, Int32(69))]) + func offWithoutAConfirmationSaysWhatHappened(reply: AdminReply, code: Int32) { + let world = SetupWorld() + world.config.send = SendSetting(enabled: true) + world.replies["off"] = reply + let result = world.setup.off() + #expect(result.code == code) + #expect(world.config.send?.enabled == false) + if reply == .notRunning { + #expect(result.out.last == "GBrain Helper isn't running, and the config switch stops every send.") + #expect(result.err == nil) + } else { + #expect(result.err?.contains("didn't confirm within 40 seconds") == true) + } + } + + @Test func offReportsABusyHelperAsBusy() { + let world = SetupWorld() + world.replies["off"] = .answered(status: 503, body: Data(#"{"code":"overloaded"}"#.utf8)) + #expect(world.setup.off().err?.hasPrefix("GBrain Helper was busy (overloaded)") == true) + } + + @Test func aRefusedConnectionReadsAsNotRunning() { + let (fd, port) = loopbackSocket() + Darwin.close(fd) + #expect(AdminClient.post(port: port, fields: ["action": "off"], timeout: 5) == .notRunning) + } + + @Test func aListenerThatNeverAnswersReadsAsNoReply() { + let (fd, port) = loopbackSocket() + defer { Darwin.close(fd) } + #expect(AdminClient.post(port: port, fields: ["action": "off"], timeout: 1) == .noReply) + } +} diff --git a/changelog.d/gbra597-send-stop-wins.md b/changelog.d/gbra597-send-stop-wins.md index 775b6d39c42..3c228bde3f3 100644 --- a/changelog.d/gbra597-send-stop-wins.md +++ b/changelog.d/gbra597-send-stop-wins.md @@ -1,6 +1,6 @@ -**Turning GBrain Helper's sending off now wins over a text already in progress and over a Touch ID dialog still open.** +**Turning GBrain Helper's sending off now wins over a text in progress and over a Touch ID dialog still open.** ### Fixed -- Each send checks the kill switch and its key again right before it hands the text to Messages, under the lock the settings are saved under. A text that had passed its first check while `send-setup --off` or `send-key remove` ran is now refused instead of sent. -- `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. -- When the helper answers `send-setup --off` with an error, the command now says what answered (for example that the helper was busy) instead of blaming the keychain. When the helper doesn't confirm within 40 seconds, the command exits with an error instead of reporting success, because a text already being handed to Messages may still go out. +- Each send checks the kill switch and its key again right before it hands the text to Messages, under the lock the settings are saved under. Once `send-setup --off` or `send-key remove` has returned, no new text is handed to Messages; a text Messages has already accepted may still be delivered. Both commands now say so when they succeed. +- `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. `--off` keeps the config file locked until the helper has answered, so the config file and the helper always record the same last command. +- `send-setup --off` says what happened when the helper doesn't confirm: if the helper isn't running it says so and exits 0, because the config switch alone stops every send; if it doesn't answer within 40 seconds it exits 69; and if it answers with an error, it names the error (for example that the helper was busy) instead of blaming the keychain. From 20883385106f3a011d5ebc26d1df480c445bfbb4 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 01:56:49 +0000 Subject: [PATCH 08/37] Say what --off's config lock actually guarantees in the changelog Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/gbra597-send-stop-wins.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/gbra597-send-stop-wins.md b/changelog.d/gbra597-send-stop-wins.md index 3c228bde3f3..c7eda985673 100644 --- a/changelog.d/gbra597-send-stop-wins.md +++ b/changelog.d/gbra597-send-stop-wins.md @@ -2,5 +2,5 @@ ### Fixed - Each send checks the kill switch and its key again right before it hands the text to Messages, under the lock the settings are saved under. Once `send-setup --off` or `send-key remove` has returned, no new text is handed to Messages; a text Messages has already accepted may still be delivered. Both commands now say so when they succeed. -- `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. `--off` keeps the config file locked until the helper has answered, so the config file and the helper always record the same last command. +- `send-setup --off` no longer waits for an earlier `send-setup` that is still showing its Touch ID dialog, and an approval given after the switch went off answers `send_disabled` instead of turning sending back on. `--off` keeps the config file locked until the helper has answered, so a `send-setup` started meanwhile waits for it instead of writing sending back on in between. - `send-setup --off` says what happened when the helper doesn't confirm: if the helper isn't running it says so and exits 0, because the config switch alone stops every send; if it doesn't answer within 40 seconds it exits 69; and if it answers with an error, it names the error (for example that the helper was busy) instead of blaming the keychain. From dcaa3c119ce17ed3f997d471d53297049e965947 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 05:54:57 +0000 Subject: [PATCH 09/37] Rebuild a concept an input purge hid as a fresh page from its current members (#9653) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- scripts/core-world-reads-baseline.tsv | 1 + scripts/engine-raw-sql-baseline.tsv | 1 + src/commands/maintain.ts | 6 +- src/commands/pages.ts | 8 +- src/core/cli-flag-registry.generated.ts | 4 +- src/core/cycle.ts | 7 +- src/core/cycle/concept-publication.ts | 20 +- src/core/cycle/concept-writes.ts | 13 +- src/core/cycle/synthesize-concepts.ts | 56 +++- src/core/engine-sql/pages.ts | 9 +- src/core/engine.ts | 6 +- src/core/persistence/concept-rebuild.ts | 226 +++++++++++++ src/core/persistence/page-prepare.ts | 7 +- src/core/persistence/purge-deleted.ts | 26 +- src/core/pglite-engine.ts | 2 +- src/core/postgres-engine.ts | 2 +- test/concept-purge-rebuild-9653.test.ts | 406 ++++++++++++++++++++++++ test/postgres-unit-arms.txt | 1 + 18 files changed, 762 insertions(+), 39 deletions(-) create mode 100644 src/core/persistence/concept-rebuild.ts create mode 100644 test/concept-purge-rebuild-9653.test.ts diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv index 45bb4c092f8..9b7dd2ba19b 100644 --- a/scripts/core-world-reads-baseline.tsv +++ b/scripts/core-world-reads-baseline.tsv @@ -740,6 +740,7 @@ src/core/persistence/protocol.ts module_collection 1 W6: per-engine state, or ma src/core/persistence/publication-deadline.ts als_store 1 W2: engine scope (decision E) replaces ad hoc async context src/core/persistence/publication-deadline.ts module_collection 1 W6: per-engine state, or mark as a constant table src/core/persistence/publication-timing.ts process_env 1 W6: settings plane out of the core +src/core/persistence/concept-rebuild.ts load_config 1 #9653: the rebuild's retention purge goes through the coordinator with the same config as purge-deleted.ts src/core/persistence/purge-deleted.ts load_config 1 W6: settings plane out of the core src/core/persistence/put-page-screen.ts load_config 1 W6: settings plane out of the core src/core/persistence/reconcile-audit.ts fs_import 1 W5: repo-less persistence for hosts diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv index 0b5a39e1241..920cba93e8a 100644 --- a/scripts/engine-raw-sql-baseline.tsv +++ b/scripts/engine-raw-sql-baseline.tsv @@ -735,6 +735,7 @@ src/core/persistence/capacity-view.ts execute_raw 1 src/core/persistence/change-reason.ts execute_raw 4 src/core/persistence/checkpoint-validation.ts execute_raw 5 src/core/persistence/compaction-pass.ts execute_raw 2 +src/core/persistence/concept-rebuild.ts execute_raw 12 #9653: the held-concept rebuild's hold, member and stated-row checks run in its purge transaction, next to the engine purge it calls src/core/persistence/config-snapshot.ts execute_raw 2 src/core/persistence/connector-account-mismatch.ts execute_raw 2 src/core/persistence/connector-checkpoint-migration.ts execute_raw 13 diff --git a/src/commands/maintain.ts b/src/commands/maintain.ts index 78095823835..c9322b0b4e6 100644 --- a/src/commands/maintain.ts +++ b/src/commands/maintain.ts @@ -369,22 +369,24 @@ export function purgePreviewHash(retentionHours: number, pages: ReadonlyArray<{ } async function runPurgeCli(engine: BrainEngine, opts: MaintainOptions): Promise { - const [{ selectPurgeCandidates, purgeDeletedPagesCoordinated }, { readPurgeRetentionHours }] = await Promise.all([ + const [{ selectPurgeCandidates, purgeDeletedPagesCoordinated, rebuildNote }, { readPurgeRetentionHours }] = await Promise.all([ import('../core/persistence/purge-deleted.ts'), import('../core/sync-reconcile.ts')]); const retention = await readPurgeRetentionHours(engine); - const selection = await selectPurgeCandidates(engine, retention, { automatic: true }); + const selection = await selectPurgeCandidates(engine, retention, { automatic: true, model: (await import('../core/ai/gateway.ts')).isAvailable('chat') }); const pages: Array<{ source_id: string; slug: string }> = (selection.managed ? selection.candidates : selection.pages ?? []) .map((p) => ({ source_id: p.source_id, slug: p.slug })); const hash = purgePreviewHash(retention, pages); const apply = ['gbrain', 'maintain', '--purge', '--yes', '--expect', hash]; if (!opts.yes) { const preview = { mode: 'preview', retention_hours: retention, count: pages.length, pages: pages.slice(0, 50), blocked: selection.blocked.length, hash, + ...(selection.rebuild.held.length ? { rebuild: selection.rebuild, rebuild_note: rebuildNote(selection.rebuild) } : {}), ...(pages.length ? { apply: renderAction({ argv: apply, consent: ['destructive'], actor: 'agent', requires_exclusive: false, why: `Permanently deletes the ${pages.length} page(s) listed (soft-deleted more than ${retention}h ago); gbrain restore cannot bring them back.` }, cliRenderContext()) } : {}) }; if (opts.json) { console.log(JSON.stringify(preview, null, 2)); return; } console.log(`${pages.length} soft-deleted page(s) are past the ${retention}h recovery window.`); for (const p of pages.slice(0, 50)) console.log(` ${p.source_id}/${p.slug}`); if (pages.length > 50) console.log(` ...and ${pages.length - 50} more`); + if (selection.rebuild.held.length) console.log(rebuildNote(selection.rebuild)); if (pages.length) console.log(`Nothing was deleted. To purge exactly these, run: ${apply.join(' ')}`); return; } diff --git a/src/commands/pages.ts b/src/commands/pages.ts index 59a9e904023..12645daac4b 100644 --- a/src/commands/pages.ts +++ b/src/commands/pages.ts @@ -10,7 +10,7 @@ * page_links, chunk_relations via existing FKs. */ import type { BrainEngine } from '../core/engine.ts'; -import { notHeld, purgeConsentRequest, purgeDeletedPagesCoordinated, selectPurgeCandidates } from '../core/persistence/purge-deleted.ts'; +import { notHeld, purgeConsentRequest, purgeDeletedPagesCoordinated, rebuildNote, selectPurgeCandidates } from '../core/persistence/purge-deleted.ts'; import { PURGE_PARK_LIMIT } from '../core/persistence/purge-parks.ts'; import { setCliExitVerdict } from '../core/cli-force-exit.ts'; import { consentGate } from '../core/consent-cli.ts'; @@ -50,10 +50,11 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise park.retried).length; const notes = { ...(selection.parked.length ? { parked: selection.parked, retry_parked: retryParked } : {}), ...(selection.blocked.length ? { blocked: selection.blocked } : {}), - ...(selection.released_origins.length ? { released_origins: selection.released_origins } : {}) }; + ...(selection.released_origins.length ? { released_origins: selection.released_origins } : {}), + ...(selection.rebuild.held.length ? { rebuild: selection.rebuild, rebuild_note: rebuildNote(selection.rebuild, true) } : {}) }; if (dryRun) { // Read-only: the same predicate and DB now() clock as the real purge; only the verb differs. @@ -68,6 +69,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise !park.retried)) console.log(` parked: ${p.source_id}/${p.slug} after ${p.failures} failures (${p.code ?? 'error'}); skipped unless --retry-parked`); for (const b of selection.blocked.filter(entry => entry.code === 'writer_not_active')) console.log(` waiting: ${b.source_id}/${b.slug}: ${b.reason}`); + if (selection.rebuild.held.length) console.log(rebuildNote(selection.rebuild, true).split('\n').map(line => ` ${line}`).join('\n')); for (const o of selection.released_origins) console.log(` released: ${o.source_id}/${o.slug} is parked (gbrain doctor: derived_origin_parked); the run labels the pages derived from it private first and keeps it parked if that fails`); return; } diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts index b8b0a71459c..4ffcc8d34c3 100644 --- a/src/core/cli-flag-registry.generated.ts +++ b/src/core/cli-flag-registry.generated.ts @@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--room', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'], 'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'], 'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'], - 'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--contains', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from', '--from-meetings', '--full', '--get', '--grammar', '--grep', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--out', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--passphrase-stdin', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remotes', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'], + 'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--contains', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from', '--from-meetings', '--full', '--get', '--grammar', '--grep', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--out', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--passphrase-stdin', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remotes', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'], 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--attest-read', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--command', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--env', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'], 'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'], 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--concurrency', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--room', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'], @@ -97,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'notices': ['--brain', '--help', '--json', '--source'], 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--card', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--terms-url', '--to', '--token', '--updated-after', '--url', '--yes'], 'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--timeout', '--timings', '--wait'], - 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'], + 'pages': ['--brain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--status', '--verify', '--yes'], 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'], 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expect', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--prefix', '--quiet', '--readers', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--slugs-file', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'], 'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'], diff --git a/src/core/cycle.ts b/src/core/cycle.ts index 801399a0708..1696a95857b 100644 --- a/src/core/cycle.ts +++ b/src/core/cycle.ts @@ -1792,7 +1792,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise 0 ? ` (${purgeResult.blocked.length} blocked, see details)` : '') + `, ${purgedPages.count} page(s)${purgePhaseNote(purgedPages)}, ` + - `and ${purgedClones.count} orphan clone temp dir(s)`, + `and ${purgedClones.count} orphan clone temp dir(s)` + + (rebuild.held.length ? `; ${rebuild.held.length} concept(s) hidden by an input purge kept for the next concept synthesis${rebuild.kept.length ? ` (${rebuild.kept.length} of them stay hidden, reasons in details)` : ''}` : ''), details: { purged_sources_count: purgedSources.length, purged_sources_blocked: purgeResult.blocked, @@ -1821,6 +1823,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise 0 ? { purged_mcp_request_log_count: purgedMcpLog } : {}), }, }; diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts index 8965f0d15c5..6dafbebf36b 100644 --- a/src/core/cycle/concept-publication.ts +++ b/src/core/cycle/concept-publication.ts @@ -25,6 +25,7 @@ import { acquirePageLock } from '../page-lock.ts'; import { derivedFileTarget, writeDerivedPageThrough } from './derived-write-through.ts'; import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts'; import { declareDerivation, deriveTrust, lowerDerivedPage } from '../trust/taint.ts'; +import { finishConceptRebuild, purgeHeldConcept, type ConceptRebuild } from '../persistence/concept-rebuild.ts'; /** #5575 I2: the narrative carries the tier of the member atoms its prompt was built from (capped at agent_written). */ const conceptDerivation = (engine: BrainEngine, sourceId: string, members: readonly string[]) => @@ -262,13 +263,15 @@ export function stripFenceSections(body: string): string { */ export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string, synthesized: Record, narrative: string, baseline: string, - opts: { writeThrough: boolean; importPage: (markdown: string) => Promise; members?: readonly string[] }): Promise { + opts: { writeThrough: boolean; importPage: (markdown: string, tx?: BrainEngine) => Promise; members?: readonly string[]; rebuild?: ConceptRebuild }): Promise { const lock = await acquirePageLock(slug, { timeoutMs: 5_000 }); if (!lock) throw Object.assign(new Error('The concept page is locked by another writer.'), { code: 'revision_conflict' }); try { - const snapshot = await engine.readPageSnapshot(slug, { sourceId }); - const page = snapshot?.page ?? null; - if (stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline) + const { rebuild } = opts; + const snapshot = await engine.readPageSnapshot(slug, { sourceId, ...(rebuild ? { includeDeleted: true } : {}) }); + // #9653: a rebuild is composed from nothing in the tombstone; purgeHeldConcept confirms the hold under the lock. + const page = rebuild ? null : snapshot?.page ?? null; + if (rebuild ? snapshot?.page.deleted_at == null : stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline) || (page && !String(page.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts'))) { throw Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' }); } @@ -281,7 +284,14 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s const markdown = page ? composeConceptRepublication(page, snapshot!.tags, synthesized, narrative) : serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] }); - await opts.importPage(markdown); + if (rebuild) { + await engine.transaction(async tx => { + const before = await purgeHeldConcept(tx, sourceId, slug, rebuild); + if (typeof before === 'string') throw Object.assign(new Error(before), { code: 'revision_conflict' }); + await opts.importPage(markdown, tx); + await finishConceptRebuild(tx, sourceId, slug, before); + }); + } else await opts.importPage(markdown); // The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges. if (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug); if (file && (file.expectedFileBytes !== null || opts.writeThrough)) { diff --git a/src/core/cycle/concept-writes.ts b/src/core/cycle/concept-writes.ts index 6af9dc7b4bc..5ff9102d7d5 100644 --- a/src/core/cycle/concept-writes.ts +++ b/src/core/cycle/concept-writes.ts @@ -17,6 +17,7 @@ import { isAvailable } from '../ai/gateway.ts'; import { importFromContent } from '../import-file.ts'; import type { ConceptRetryBound } from './concept-retry-bound.ts'; import { publicationHold } from '../persistence/accepted-pending.ts'; +import type { ConceptRebuild } from '../persistence/concept-rebuild.ts'; import { conceptProvenanceCovers, replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcepts, } from './concept-publication.ts'; @@ -39,6 +40,10 @@ export interface ConceptWrite { revision: string | null; /** Unmanaged: the narrative the page held when synthesis started; a different narrative under the page lock defers the concept (D-N3). */ baseline: string; + /** #9653: a held concept's rebuild: unmanaged, the tombstone its transaction purges; managed, 'purged' (its purge committed). */ + rebuild?: ConceptRebuild | 'purged'; + /** #9653: set once the rebuilt page was written. */ + rebuilt?: boolean; } export interface ConceptWriterDeps { @@ -76,10 +81,13 @@ export function conceptWriter(deps: ConceptWriterDeps) { }; const publishClassic = async (write: ConceptWrite, pageVisibility: Visibility): Promise => { try { + // #9653: a rebuild imports inside its locked transaction, so its chunks wait for the embedding backlog instead. + const rebuild = write.rebuild && write.rebuild !== 'purged' ? write.rebuild : undefined; write.baseline = await publishClassicConcept(engine, write.conceptSlug, src, write.synthesized(pageVisibility), write.narrative, - write.baseline, { writeThrough: deps.writeThrough, members: write.atomSlugs, importPage: (markdown) => importFromContent(engine, write.conceptSlug, markdown, { - noEmbed: !isAvailable('embedding'), sourceId: deps.importSourceId, preserveGateMarkers: true, + write.baseline, { writeThrough: deps.writeThrough, members: write.atomSlugs, rebuild, importPage: (markdown, tx) => importFromContent(tx ?? engine, write.conceptSlug, markdown, { + noEmbed: !!rebuild || !isAvailable('embedding'), sourceId: deps.importSourceId, preserveGateMarkers: true, }) }); + if (write.rebuild) { write.rebuilt = true; write.rebuild = undefined; } return true; } catch (err) { return recorded(write, err); } }; @@ -131,6 +139,7 @@ export function conceptWriter(deps: ConceptWriterDeps) { const outcome = outcomes[i]!; if ('error' in outcome) return recorded(write, outcome.error); write.revision = outcome.revision; + if (write.rebuild) { write.rebuilt = true; write.rebuild = undefined; } return true; }); }; diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts index 4278a29b29b..f731a6d05e5 100644 --- a/src/core/cycle/synthesize-concepts.ts +++ b/src/core/cycle/synthesize-concepts.ts @@ -20,7 +20,7 @@ // For T3/T4: deterministic stub narrative. // 6. Write concept-typed pages with the synthesis mode made explicit. -import type { BrainEngine } from '../engine.ts'; +import type { BrainEngine, PageSnapshot } from '../engine.ts'; import { resolveModel } from '../model-config.ts'; import type { PhaseResult } from '../cycle.ts'; import type { ProgressReporter } from '../progress.ts'; @@ -41,6 +41,7 @@ import { derivedWriteThrough, reportDerivedWriteThrough } from './derived-write- import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts'; import { conceptProvenanceCovers, conceptPublicationHold, stripFenceSections } from './concept-publication.ts'; import { conceptWriter, type ConceptWrite } from './concept-writes.ts'; +import { heldConceptRebuild, keptReason, submitHeldConceptPurge, type ConceptRebuild, type RebuildKept } from '../persistence/concept-rebuild.ts'; import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts'; import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts'; import { ConceptDriftSkips } from '../persistence/drift-conflicts.ts'; @@ -138,7 +139,7 @@ export interface SynthesizeConceptsOpts { /** Test seam: alternative chat function. */ _chat?: typeof gatewayChat; /** Test seam: skip DB query; cluster these atoms directly. */ - _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string; visibility?: Visibility }>; + _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string; visibility?: Visibility; revision?: string }>; } interface AtomGroup { @@ -147,6 +148,8 @@ interface AtomGroup { atomSlugs: string[]; atomTitles: string[]; atomBodies: string[]; + /** #9653: each member's knowledge_revision when its body was read (a held concept's rebuild refuses if it moved). */ + atomRevisions: Array; /** #5525: strictest effective visibility of the member atoms. */ visibility: Visibility; tier: 'T1' | 'T2' | 'T3' | 'T4'; @@ -165,6 +168,14 @@ Output ONLY the summary paragraph (3-5 sentences). No headers, no JSON, no preamble. Write in plain English, present-tense voice. Synthesize what the atoms collectively SAY about the concept; don't enumerate the atoms.`; +/** #9653: the rebuild of a held concept tombstone, or null; a held concept kept hidden is added to `kept` with why. */ +async function conceptRebuildFor(engine: BrainEngine, sourceId: string, snapshot: PageSnapshot, group: AtomGroup, dryRun: boolean, + kept: RebuildKept[]): Promise { + const held = dryRun ? null : await heldConceptRebuild(engine, sourceId, snapshot, group.atomSlugs, group.atomRevisions, group.visibility); + if (held && 'kept' in held) kept.push(held.kept); + return held && 'rebuild' in held ? held.rebuild : null; +} + export async function runPhaseSynthesizeConcepts( engine: BrainEngine, opts: SynthesizeConceptsOpts = {}, @@ -179,13 +190,14 @@ export async function runPhaseSynthesizeConcepts( slug: string; title: string; compiled_truth: string; + revision: string; frontmatter: { concepts?: string[]; imported_from?: string }; private: boolean; }>( // Codex P2: scoped to the cycle source — the provenance edges below // are pinned to it, so a brain-global scan grouped same-slug atoms // from OTHER sources into this source's concepts. - `SELECT slug, title, compiled_truth, frontmatter, NOT (${privatePagesFilterFragment('pages')}) AS private + `SELECT slug, title, compiled_truth, knowledge_revision::text AS revision, frontmatter, NOT (${privatePagesFilterFragment('pages')}) AS private FROM pages WHERE type = 'atom' AND source_id = $1 @@ -199,6 +211,7 @@ export async function runPhaseSynthesizeConcepts( slug: r.slug, title: r.title, body: r.compiled_truth, + revision: r.revision, concept_refs: r.frontmatter!.concepts!, visibility: r.private ? 'private' as const : 'world' as const, })); @@ -219,13 +232,14 @@ export async function runPhaseSynthesizeConcepts( // 2. Group atoms by concept stem (#6161 human redirects, then #5965 spelling folds; see resolveAtomConceptStems); one atom counts once per concept. const { atomStems, foldedSpellings } = await resolveAtomConceptStems(engine, opts.sourceId ?? 'default', atoms); - const groups = new Map(); + const groups = new Map; visibilities: Visibility[] }>(); for (const [i, atom] of atoms.entries()) { for (const conceptSlug of atomStems[i]!) { - const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] }; + const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], revisions: [], visibilities: [] }; existing.slugs.push(atom.slug); existing.titles.push(atom.title); existing.bodies.push(atom.body); + existing.revisions.push(atom.revision); // An atom with no recorded visibility is private (derived pages fail closed). existing.visibilities.push(atom.visibility ?? 'private'); groups.set(conceptSlug, existing); @@ -244,6 +258,7 @@ export async function runPhaseSynthesizeConcepts( atomSlugs: data.slugs, atomTitles: data.titles, atomBodies: data.bodies, + atomRevisions: data.revisions, visibility: strictestVisibility(data.visibilities), tier, }); @@ -335,6 +350,9 @@ export async function runPhaseSynthesizeConcepts( const publicationPending: Array<{ concept: string; reason: string }> = []; const skippedHumanOwned: string[] = []; const skippedDeleted: string[] = []; + const rebuilds: ConceptWrite[] = []; + const rebuildDeferred: Array<{ concept: string; reason: string }> = []; + const rebuildKept: RebuildKept[] = []; const skippedUnchanged: string[] = []; const provenanceRestored: string[] = []; const rehashed: string[] = []; @@ -368,8 +386,11 @@ export async function runPhaseSynthesizeConcepts( // A concept page this phase did not write belongs to a human (or another // writer). Check before any spend; never replace its body. const existingSnapshot = await engine.readPageSnapshot(conceptSlug, { sourceId: opts.sourceId ?? 'default', includeDeleted: true }); - if (existingSnapshot?.page.deleted_at) { skippedDeleted.push(conceptSlug); continue; } // #6161: a deleted concept is never resurrected - const existing = existingSnapshot?.page ?? null; + // #6161: a deleted concept is never resurrected, except (#9653) one hidden only by an input purge and carrying nothing + // stated: after the model call its tombstone is purged and a fresh page written from the current members (concept-rebuild.ts). + const rebuild = existingSnapshot?.page.deleted_at ? await conceptRebuildFor(engine, src, existingSnapshot, group, !!opts.dryRun, rebuildKept) : null; + if (existingSnapshot?.page.deleted_at && !rebuild) { skippedDeleted.push(conceptSlug); continue; } + const existing = rebuild ? null : existingSnapshot?.page ?? null; if (existing && !String(existing.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts')) { skippedHumanOwned.push(conceptSlug); continue; @@ -405,7 +426,7 @@ export async function runPhaseSynthesizeConcepts( continue; } // #6643 (B1): a drifted concept would only add a conflict receipt per publication; checked live before any spend. - if (await driftSkips.skip(conceptSlug, existingSnapshot)) continue; + if (!rebuild && await driftSkips.skip(conceptSlug, existingSnapshot)) continue; const held = existing && conceptPublicationHold(existing); // checked before any spend if (held) { publicationHeld.push({ concept: group.conceptSlug, reason: held }); continue; } // A page hashed by the pre-D-N3 formula (full atom bodies) whose inputs are @@ -505,12 +526,17 @@ export async function runPhaseSynthesizeConcepts( keptExistingNarrative.push(conceptSlug); continue; } + // #9653: a failed synthesis never rebuilds a held concept; it stays hidden and held for the next cycle. + if (rebuild && synthesisMode !== 'llm' && synthesisMode !== 'deterministic_tier') { rebuildDeferred.push({ concept: conceptSlug, reason: 'the synthesis did not produce a narrative; retried next run' }); continue; } if (!grandfathered) synthesisModeCounts[synthesisMode]++; await stopIfAborted(); if (!opts.dryRun) { + // #9653: managed, the tombstone's retention purge commits before the fresh page is queued; otherwise nothing more is written. + const purged = rebuild && maintenance ? await submitHeldConceptPurge(engine, src, conceptSlug, rebuild) : true; + if (purged !== true) { rebuildDeferred.push({ concept: conceptSlug, reason: purged }); continue; } // #5525: tighten-only — a concept already private stays private. - const prior = await engine.getPage(conceptSlug, { sourceId: src }); + const prior = rebuild ? null : await engine.getPage(conceptSlug, { sourceId: src }); const visibility = strictestVisibility([group.visibility, prior?.frontmatter?.visibility === 'private' ? 'private' : 'world']); // #2163: serialize to markdown and import via the canonical pipeline so // the page is chunked (+ embedded when a provider is configured) — @@ -530,9 +556,10 @@ export async function runPhaseSynthesizeConcepts( // edge is durable, because a later private flip reaches it through them. // GBRA-60: one whose edges already cover every member publishes once, at // world, so a strict source never commits an intermediate private page. - const covered = visibility === 'world' && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs); + const covered = !rebuild && visibility === 'world' && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs); const write: ConceptWrite = { concept: group.conceptSlug, conceptSlug, atomSlugs: group.atomSlugs, visibility, covered, synthesisMode, synthesized, narrative, - revision: existingSnapshot?.revision ?? null, baseline: existing?.compiled_truth ?? '' }; + revision: rebuild ? null : existingSnapshot?.revision ?? null, baseline: existing?.compiled_truth ?? '', ...(rebuild ? { rebuild: maintenance ? 'purged' as const : rebuild } : {}) }; + if (rebuild) rebuilds.push(write); // GBRA-60: a managed run's concepts publish in batches (concept-writes.ts), each one publication group on Postgres. await stopIfAborted(); await (maintenance ? writer.queue(write) : writer.publish(write)); @@ -588,6 +615,7 @@ export async function runPhaseSynthesizeConcepts( }); } + const rebuilt = rebuilds.filter(write => write.rebuilt).map(write => write.conceptSlug); return reportDerivedWriteThrough({ phase: 'synthesize_concepts', status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || publicationPending.length > 0 @@ -599,6 +627,9 @@ export async function runPhaseSynthesizeConcepts( (failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : '') + (budgetCapped > 0 ? ` (${budgetCapped} over the $${budgetCap.toFixed(2)} budget → template fallback)` : '') + (linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') + + (rebuilt.length > 0 ? ` (${rebuilt.length} hidden by an input purge rebuilt)` : '') + + (rebuildDeferred.length > 0 ? ` (${rebuildDeferred.length} hidden by an input purge left hidden for the next run)` : '') + + (rebuildKept.length > 0 ? ` (${rebuildKept.length} hidden by an input purge kept hidden: ${rebuildKept.map(keptReason).join('; ')})` : '') + (skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') + (skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') + (rehashed.length > 0 ? ` (${rehashed.length} rehashed without synthesis)` : '') + @@ -619,6 +650,9 @@ export async function runPhaseSynthesizeConcepts( warnings, skipped_human_owned: skippedHumanOwned, skipped_deleted: skippedDeleted, + rebuilt, + rebuild_deferred: rebuildDeferred, + rebuild_kept: rebuildKept, skipped_unchanged: skippedUnchanged, provenance_restored: provenanceRestored, rehashed, diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts index 707a1ae3935..5408e4458aa 100644 --- a/src/core/engine-sql/pages.ts +++ b/src/core/engine-sql/pages.ts @@ -330,15 +330,18 @@ export async function restorePage(exec: SqlExecutor, slug: string, opts?: { sour export async function purgeDeletedPages( exec: SqlExecutor, olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { // Clamp to non-negative integer; runaway purge protection. The DELETE // cascades through content_chunks, page_links, chunk_relations via FKs. const hours = Math.max(0, Math.floor(olderThanHours)); // GBRA-130 A-49: tombstones the unmanaged belief-ledger expiry could not delete (or parked) stay for their own retry. + // #9653: `onlyIds` narrows the same statements to those pages (a concept rebuild's one tombstone). + const only = opts?.onlyIds ? sqlFragment` AND pages.id = ANY(${opts.onlyIds}::bigint[])` : sqlFragment``; + const onlyManifest = opts?.onlyIds ? sqlFragment` AND p.id = ANY(${opts.onlyIds}::bigint[])` : sqlFragment``; const excluded = opts?.excludeIds?.length ? sqlFragment` - AND NOT (pages.id = ANY(${opts.excludeIds}::bigint[]))` : sqlFragment``; - const excludedManifest = opts?.excludeIds?.length ? sqlFragment` AND NOT (p.id = ANY(${opts.excludeIds}::bigint[]))` : sqlFragment``; + AND NOT (pages.id = ANY(${opts.excludeIds}::bigint[]))${only}` : only; + const excludedManifest = opts?.excludeIds?.length ? sqlFragment` AND NOT (p.id = ANY(${opts.excludeIds}::bigint[]))${onlyManifest}` : onlyManifest; if (opts?.dryRun) { // SAME WHERE predicate as the DELETE below (same cutoff arithmetic, // same DB now() clock source) — only the verb differs, so preview and diff --git a/src/core/engine.ts b/src/core/engine.ts index 50fe860e503..ed2245d878a 100644 --- a/src/core/engine.ts +++ b/src/core/engine.ts @@ -1117,12 +1117,12 @@ export interface BrainEngine { * the cutoff (or is soft-deleted/restored) between the two statements. * Dry-run responses additionally carry `pages` (slug, source_id, deleted_at) for * display; the destructive path leaves `pages` undefined. - * `opts.excludeIds` keeps those page ids out of both (GBRA-130 A-49: the - * tombstones the unmanaged belief-ledger expiry failed or parked). + * `opts.excludeIds` keeps those page ids out of both (GBRA-130 A-49: tombstones the unmanaged belief-ledger + * expiry failed or parked); `opts.onlyIds` limits both to those ids under the same holds (#9653 concept rebuild). */ purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }>; /** * v0.26.5: by default `listPages` excludes soft-deleted rows. Set diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts new file mode 100644 index 00000000000..5ac706d136b --- /dev/null +++ b/src/core/persistence/concept-rebuild.ts @@ -0,0 +1,226 @@ +/** + * #9653: a concept the input purge hid is rebuilt as a new page. purge's hideDerivedRows soft-deletes a concept derived + * from a purged input and marks it needs_rederive with marked_at equal to the deleted_at it set; while that mark is open + * the automatic purge keeps the tombstone (purge-deleted.ts readRederiveHeldConcepts). The next synthesis, after its + * model call, hard-purges that one tombstone through the purge's own code and writes a fresh concept at the slug from + * the current members only. Unmanaged, both run in one transaction under the page lock; managed, the retention purge + * is submitted pinned to the tombstone's revision and the publish follows only once its receipt shows it committed. + * A purged slug is written again by any later synthesis, so a run that stops between the two leaves nothing a person + * must fix. A concept carrying anything a person or an agent stated, or whose fresh access would be wider than the + * tombstone's, is never rebuilt: it stays hidden and held. The rebuild's retention purge is no person's delete, so any + * later record of "a person deleted this concept" must stay outside it. Everything lives in the database, so a + * repo-less brain gets it unchanged. + */ +import { randomUUID } from 'node:crypto'; +import type { BrainEngine, LinkBatchInput, PageSnapshot } from '../engine.ts'; +import type { OperationContext } from '../ops/contract.ts'; +import { loadConfig } from '../config.ts'; +import { submitPageMutation } from './page-mutations.ts'; +import { maintenancePublishWaitMs } from './maintenance-wait.ts'; +import { pendingRequestId } from '../cycle/dream-write-deferral.ts'; +import { OWED_PURGE_OP } from './derived-origin-hold.ts'; +import { extractedFromPageSql } from '../facts/gone-page-facts.ts'; +import { PRIVACY_ALIASES, privacyPartSql, privatePagesFilterFragment } from '../search/private-visibility.ts'; + +type Sql = Pick; + +/** The tombstone a synthesis rebuilds: its row, delete instant and revision, and the members (at the revisions read). */ +export interface ConceptRebuild { page_id: number; deleted_us: string; revision: string; members: Array<{ slug: string; revision: string }> } + +/** Why a held concept is not rebuilt: something a person or an agent stated (with the kinds), no model, or wider access. */ +export type RebuildKept = { source_id: string; slug: string } & ({ reason: 'stated'; kinds: string[] } | { reason: 'no_model' } | { reason: 'access'; why: string }); + +/** Frontmatter keys only an owner or an agent sets on a concept (synthesis writes visibility alone): any of them is stated. */ +const STATED_LABEL_KEYS: readonly string[] = [...Object.keys(PRIVACY_ALIASES), 'readable_by', 'pinned_question', 'derived_from']; + +/** Link provenances a reconciler derives from page text; any other one (add_link's 'manual' or a caller's tag) is stated. */ +const DERIVED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved', 'concept-provenance']; + +/** + * Every store a hard purge of a page removes rows from, keyed as the purge receipt names them + * (test/concept-purge-rebuild-9653.test.ts fails on a receipt key missing here). `stated`: a row there was stated by a + * person or an agent, and a concept with one is never rebuilt (statedKinds checks each). `derived`: rows built from the + * page's own body or kept as telemetry, which the purge drops and the fresh page rebuilds as needed. + */ +export const REBUILD_STORES: Readonly> = { + facts: 'stated', takes: 'stated', timeline_entries: 'stated', page_aliases: 'stated', slug_aliases: 'stated', tags: 'stated', + files: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', + pages: 'derived', page_versions: 'derived', content_chunks: 'derived', query_cache: 'derived', take_proposals: 'derived', open_loops: 'derived', + slug_rename_history: 'derived', trust_proposals: 'derived', decide_proposals: 'derived', decide_review_queue: 'derived', + decide_review_proposals: 'derived', persistence_requests: 'derived', persistence_effects: 'derived', derived_generations: 'derived', + derived_generation_items: 'derived', retrieval_event_pages: 'derived', retrieval_event_links: 'derived', retrieval_feedback: 'derived', + retrieval_weights: 'derived', 'eval_candidates.retrieved_slugs': 'derived', mention_gazetteer_entries: 'derived', + context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', raw_data: 'derived', + page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', +}; + +const WIDER = 'its current members are all world-readable and the hidden concept was not'; + +const HELD_SQL = `p.deleted_at IS NOT NULL AND p.type = 'concept' AND coalesce(p.frontmatter->>'synthesized_by', '') LIKE 'synthesize_concepts%' + AND EXISTS (SELECT 1 FROM needs_rederive n WHERE n.derived_table = 'pages' AND n.derived_id = p.id::text AND n.marked_at = p.deleted_at) + AND NOT EXISTS (SELECT 1 FROM op_checkpoints o WHERE o.op = '${OWED_PURGE_OP}' AND o.fingerprint = p.id::text)`; +const DELETED_US = `floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text`; + +/** What a person or an agent stated on or about the concept row `$1` (source `$2`, slug `$3`), as REBUILD_STORES kinds. */ +const STATED_SQL = `SELECT array_remove(ARRAY[ + CASE WHEN EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $2 AND (f.entity_slug = $3 OR f.source_markdown_slug = $3) AND NOT ${extractedFromPageSql('f', '$3')}) THEN 'facts' END, + CASE WHEN EXISTS (SELECT 1 FROM takes t WHERE t.page_id = $1) THEN 'takes' END, + CASE WHEN EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = $1) THEN 'timeline_entries' END, + CASE WHEN EXISTS (SELECT 1 FROM links l WHERE (l.to_page_id = $1 OR l.from_page_id = $1) AND l.link_source IS NOT NULL + AND l.link_source <> ALL($4::text[])) THEN 'links' END, + CASE WHEN EXISTS (SELECT 1 FROM tags t WHERE t.page_id = $1) THEN 'tags' END, + CASE WHEN EXISTS (SELECT 1 FROM files x WHERE x.page_id = $1) THEN 'files' END, + CASE WHEN EXISTS (SELECT 1 FROM page_aliases a WHERE a.source_id = $2 AND a.slug = $3) THEN 'page_aliases' END, + CASE WHEN EXISTS (SELECT 1 FROM slug_aliases a WHERE a.source_id = $2 AND a.canonical_slug = $3) THEN 'slug_aliases' END, + CASE WHEN EXISTS (SELECT 1 FROM core_edit_notices c WHERE c.source_id = $2 AND c.slug = $3) THEN 'core_edit_notices' END, + CASE WHEN EXISTS (SELECT 1 FROM write_gate_holds h WHERE h.source_id = $2 AND h.slug = $3) THEN 'write_gate_holds' END, + CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 + AND p.frontmatter ?| $5::text[]) THEN 'labels' END +], NULL) AS kinds`; + +/** The kinds of stated rows the concept carries; empty when it carries none. */ +export async function statedKinds(engine: Sql, pageId: number, sourceId: string, slug: string): Promise { + const [row] = await engine.executeRaw<{ kinds: string[] | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS]); + return row?.kinds ?? []; +} + +/** Who may read a page, as the read predicate decides it: compared before and after a rebuild (rebuildWidens). */ +export interface RebuildAccess { open: boolean; public_part: boolean; readers: string[] | null; page_readers: string[] | null; folder_rule_ids: string[] | null } +const ACCESS_SQL = `SELECT ${privatePagesFilterFragment('p')} AS open, ${privacyPartSql('p')} AS public_part, gbrain_access_readers(p.frontmatter) AS readers, + p.page_readers, p.folder_rule_ids FROM pages p WHERE p.id = $1`; + +export async function readRebuildAccess(engine: Sql, pageId: number): Promise { + return (await engine.executeRaw(ACCESS_SQL, [pageId]))[0] ?? null; +} + +/** Why the fresh page would be readable by someone who could not read the tombstone, or null. Anything it cannot tell widens. */ +export function rebuildWidens(before: RebuildAccess | null | undefined, after: RebuildAccess | null | undefined): string | null { + if (!before || !after) return 'its access could not be read'; + const within = (inner: readonly string[] | null, outer: readonly string[] | null) => (inner ?? []).every(id => (outer ?? []).includes(id)); + if (!before.open && after.open) return 'it would be readable by any caller'; + if (!before.public_part && after.public_part) return 'it would no longer be private'; + if (before.readers && (!after.readers || !within(after.readers, before.readers))) return 'it would name readers the hidden concept did not'; + if (before.page_readers && (!after.page_readers || !within(after.page_readers, before.page_readers))) return 'its stored readers would widen'; + if (before.folder_rule_ids && (!after.folder_rule_ids || !within(before.folder_rule_ids, after.folder_rule_ids))) return 'a folder rule would stop covering it'; + return null; +} + +/** + * The rebuild a synthesis would run for `snapshot`, a tombstone. Null when the concept is not held (a person or a sync + * deleted it, or an owner purge is owed); `kept` when it is held but carries something stated, or when its fresh + * visibility (`visibility`, derived from the current members) would be wider than the tombstone's. Records each + * member at `read`, the revision its body was read at for the narrative, so the rebuild refuses when one moved. + */ +export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot: PageSnapshot, members: readonly string[], + read: ReadonlyArray, visibility: 'private' | 'world'): Promise<{ rebuild: ConceptRebuild } | { kept: RebuildKept } | null> { + const pageId = Number(snapshot.page.id); + const [held] = await engine.executeRaw<{ deleted_us: string }>(`SELECT ${DELETED_US} AS deleted_us FROM pages p WHERE p.id = $1 AND ${HELD_SQL}`, [pageId]); + if (!held) return null; + const slug = snapshot.page.slug; + const kinds = await statedKinds(engine, pageId, sourceId, slug); + if (kinds.length) return { kept: { source_id: sourceId, slug, reason: 'stated', kinds } }; + const access = await readRebuildAccess(engine, pageId); + if (!access || (visibility === 'world' && !access.public_part)) return { kept: { source_id: sourceId, slug, reason: 'access', why: WIDER } }; + const rows = await engine.executeRaw<{ slug: string; revision: string }>(`SELECT slug, knowledge_revision::text AS revision FROM pages + WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [sourceId, [...new Set(members)]]); + if (!rows.length || rows.length !== new Set(members).size) return null; + const readAt = new Map(members.flatMap((m, i) => read[i] === undefined ? [] : [[m, read[i]!] as const])); + return { rebuild: { page_id: pageId, deleted_us: held.deleted_us, revision: snapshot.revision, + members: rows.map(row => ({ slug: row.slug, revision: readAt.get(row.slug) ?? row.revision })) } }; +} + +/** + * Unmanaged, inside the rebuild's transaction and under the page lock: confirms the concept is still held at the same + * delete, carries nothing stated and every member is live at the revision the narrative read (locking them against a + * purge), then hard-purges the tombstone with the expiry's own statements (engine purgeDeletedPages, onlyIds). Returns + * why it purged nothing, or the tombstone's access and the incoming links the fresh page takes over. + */ +export async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { + const [held] = await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = $1 AND p.source_id = $2 AND p.slug = $3 + AND ${DELETED_US} = $4 AND ${HELD_SQL} FOR UPDATE OF p`, [rebuild.page_id, sourceId, slug, rebuild.deleted_us]); + if (!held) return 'The concept is no longer held for a rebuild (a person or sync deleted, restored or purged it), so the rebuild wrote nothing.'; + if ((await statedKinds(tx, rebuild.page_id, sourceId, slug)).length) return 'Something was stated on the concept during synthesis, so the rebuild wrote nothing and it stays held.'; + const live = await tx.executeRaw(`SELECT m.slug FROM pages m JOIN jsonb_to_recordset($2::text::jsonb) AS r(slug text, revision text) + ON m.slug = r.slug AND m.knowledge_revision::text = r.revision WHERE m.source_id = $1 AND m.deleted_at IS NULL FOR SHARE OF m`, [sourceId, JSON.stringify(rebuild.members)]); + if (!rebuild.members.length || live.length !== rebuild.members.length) return 'A member the rebuilt narrative was built from changed or was removed during synthesis, so the rebuild wrote nothing; the next run builds it again.'; + const access = await readRebuildAccess(tx, rebuild.page_id); + const incoming = await tx.executeRaw(`SELECT f.slug AS from_slug, $2::text AS to_slug, l.link_type, l.context, l.link_source, + o.slug AS origin_slug, l.origin_field, f.source_id AS from_source_id, $3::text AS to_source_id, o.source_id AS origin_source_id + FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id + WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL`, [rebuild.page_id, slug, sourceId]); + const purged = await tx.purgeDeletedPages(0, { onlyIds: [rebuild.page_id] }); + if (purged.count !== 1 || !access) return 'The tombstone is held by another purge rule, so the rebuild wrote nothing and it stays held.'; + return { access, incoming }; +} + +/** Unmanaged, after the fresh write in the same transaction: points the incoming links at it and confirms it reads no wider. */ +export async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: LinkBatchInput[] }): Promise { + const [fresh] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]); + if (!fresh) throw Object.assign(new Error('The rebuilt concept was not written (the import refused it), so the rebuild wrote nothing and the concept stays held.'), { code: 'revision_conflict' }); + if (before.incoming.length) await tx.addLinksBatch(before.incoming); + const widened = rebuildWidens(before.access, await readRebuildAccess(tx, Number(fresh.id))); + if (widened) { + const error: Error & { code?: string } = new Error(`The rebuilt concept would be readable more widely than the hidden one (${widened}), so the rebuild wrote nothing and the concept stays held.`); + error.code = 'revision_conflict'; + throw error; + } +} + +/** + * Managed: submits the retention purge of the tombstone, pinned to the revision the synthesis read, so a person's edit, + * restore or delete in between refuses it. True only when its receipt shows the purge committed; a pending, failed or + * refused purge returns why, and the next synthesis handles whatever it finds. + */ +export async function submitHeldConceptPurge(engine: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { + const live = await engine.executeRaw(`SELECT m.slug FROM pages m JOIN jsonb_to_recordset($2::text::jsonb) AS r(slug text, revision text) + ON m.slug = r.slug AND m.knowledge_revision::text = r.revision WHERE m.source_id = $1 AND m.deleted_at IS NULL`, [sourceId, JSON.stringify(rebuild.members)]); + if (live.length !== rebuild.members.length) return 'a member the rebuilt narrative was built from changed or was removed during synthesis'; + const [held] = await engine.executeRaw(`SELECT 1 FROM pages p WHERE p.id = $1 AND ${DELETED_US} = $2 AND ${HELD_SQL}`, [rebuild.page_id, rebuild.deleted_us]); + if (!held) return 'the concept is no longer held for a rebuild (a person or sync deleted, restored or purged it)'; + if ((await statedKinds(engine, rebuild.page_id, sourceId, slug)).length) return 'something was stated on the concept during synthesis'; + const ctx: OperationContext = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, sourceId, dryRun: false, + logger: { info() {}, warn() {}, error() {} } }; + try { + const purged = await submitPageMutation(ctx, { operation: 'delete_page', waitMs: maintenancePublishWaitMs(), params: { slug, source_id: sourceId, + purge: true, retention: true, expected_revision: rebuild.revision, request_id: randomUUID() } }); + return purged.status === 'purged' ? true : `the purge of the hidden concept did not commit (${String(purged.status ?? 'no status')})`; + } catch (error) { + const pending = pendingRequestId(error); + if (pending) return `the purge of the hidden concept is accepted and still pending (request_id ${pending})`; + return `the purge of the hidden concept was refused: ${error instanceof Error ? error.message : String(error)}`; + } +} + +/** + * Every held concept and, for those the next synthesis will not rebuild, why (the purge previews name them). `model`: + * whether a synthesis model is configured; without one a concept built from many atoms is not rebuilt. + */ +export async function readHeldConcepts(engine: Sql, model: boolean): Promise<{ held: Array<{ source_id: string; slug: string }>; kept: RebuildKept[] }> { + const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; private: boolean; members_private: boolean }>(`SELECT p.id, p.source_id, p.slug, + NOT ${privacyPartSql('p')} AS private, + EXISTS (SELECT 1 FROM derivation_inputs d JOIN pages m ON m.id::text = d.input_id AND d.input_table = 'pages' + WHERE d.derived_table = 'pages' AND d.derived_id = p.id::text AND m.deleted_at IS NULL AND NOT (${privatePagesFilterFragment('m')})) AS members_private + FROM pages p WHERE ${HELD_SQL} ORDER BY p.source_id, p.slug`); + const kept: RebuildKept[] = []; + for (const row of rows) { + const kinds = await statedKinds(engine, Number(row.id), row.source_id, row.slug); + if (kinds.length) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'stated', kinds }); + else if (row.private && !row.members_private) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'access', why: WIDER }); + else if (!model) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'no_model' }); + } + return { held: rows.map(({ source_id, slug }) => ({ source_id, slug })), kept }; +} + +/** When a tombstone's recovery window ends: its own delete plus `hours` (UTC, to the second), and whether that has passed. */ +export async function tombstoneWindow(tx: Sql, pageId: number, hours: number): Promise<{ until: string; past: boolean } | null> { + const [window] = await tx.executeRaw<{ until: string; past: boolean }>(`SELECT to_char((deleted_at + ($2 || ' hours')::interval) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS until, + deleted_at + ($2 || ' hours')::interval <= now() AS past FROM pages WHERE id = $1 AND deleted_at IS NOT NULL`, [pageId, String(hours)]); + return window ?? null; +} + +/** One preview line per kept concept, naming its reason. */ +export function keptReason(kept: RebuildKept): string { + if (kept.reason === 'stated') return `${kept.source_id}/${kept.slug}: stays hidden, it carries what a person or an agent stated (${kept.kinds.join(', ')})`; + if (kept.reason === 'access') return `${kept.source_id}/${kept.slug}: stays hidden, a rebuild would be readable more widely (${kept.why})`; + return `${kept.source_id}/${kept.slug}: stays hidden, no synthesis model is configured to rebuild it`; +} diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts index 02dec813093..3637f69d7d5 100644 --- a/src/core/persistence/page-prepare.ts +++ b/src/core/persistence/page-prepare.ts @@ -44,6 +44,7 @@ import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from ' import { digest, sha256 } from './digest.ts'; import { replaceableFile } from '../facts/file-body-guard.ts'; import { releaseHiddenMoment } from '../facts/derivation-inputs.ts'; +import { tombstoneWindow } from './concept-rebuild.ts'; import { getWorktreeBinding } from './ownership.ts'; import type { PreparedContentImport } from './prepared-import.ts'; import type { PreparedMutation } from './coordinator.ts'; @@ -755,6 +756,7 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest, const observedRevision = snapshot.revision; const purge = p.purge === true; const noop = !purge && snapshot.page.deleted_at != null; + const retentionHours = purge ? 0 : await (await import('../sync-reconcile.ts')).readPurgeRetentionHours(engine); // Always-loaded core pages: a remote caller cannot delete one (owner-only). if (!noop) { enterClaimStep(clock, 'core_guard', undefined, 'db'); await prepareCoreGuard(engine, { row, snapshot, incoming: null }); } enterClaimStep(clock, 'file_target', undefined, 'fs'); @@ -826,8 +828,11 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest, // GST-2518: a soft delete authors no content, so the tombstone keeps its tier (and a write over it the page's label guard). if (!noop) { await tx.createVersion(row.slug, source); await withTrustKeep(tx, ['pages'], () => tx.softDeletePage(row.slug, source)); } else await releaseHiddenMoment(tx, Number(snapshot.page.id)); + // #9653: a page already deleted keeps its tombstone's date, so its window runs from that date (a released hold included). + const window = noop ? await tombstoneWindow(tx, Number(snapshot.page.id), retentionHours) : null; + const until = !window ? `now + ${retentionHours}h` : window.past ? `the next purge (its ${retentionHours}h window ended ${window.until})` : window.until; return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop, - recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete --purge, local CLI only)' }; + recoverable_until: `${until} via restore_page (remove immediately instead: gbrain delete --purge, local CLI only)` }; } }; return prepared; } diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts index f28039e9181..3d418ec4ac3 100644 --- a/src/core/persistence/purge-deleted.ts +++ b/src/core/persistence/purge-deleted.ts @@ -33,7 +33,24 @@ async function readRederiveHeldConcepts(engine: Pick) AND EXISTS (SELECT 1 FROM needs_rederive n WHERE n.derived_table = 'pages' AND n.derived_id = p.id::text AND n.marked_at = p.deleted_at)`); return rows.map(row => Number(row.id)); } + +/** + * #9653: the preview lines for the concepts an input purge hid: how many the next concept synthesis rebuilds, and one + * line per concept it keeps hidden with the reason (concept-rebuild.ts). `removes` (an explicit purge) says it purges + * the expired ones instead. + */ +export function rebuildNote(rebuild: PurgeSelection['rebuild'], removes = false): string { + if (!rebuild.held.length) return ''; + const kept = new Set(rebuild.kept.map(k => `${k.source_id}/${k.slug}`)); + const next = rebuild.held.filter(c => !kept.has(`${c.source_id}/${c.slug}`)); + return [`${rebuild.held.length} concept(s) hidden by an input purge are kept out of the automatic purge.`, + ...(next.length ? [`${next.length} of them are rebuilt by the next concept synthesis from their current members: ${next.slice(0, 20).map(c => `${c.source_id}/${c.slug}`).join(', ')}${next.length > 20 ? ` and ${next.length - 20} more` : ''}.`] : []), + ...rebuild.kept.slice(0, 20).map(keptReason), ...(rebuild.kept.length > 20 ? [`...and ${rebuild.kept.length - 20} more kept hidden`] : []), + ...(removes ? ['This purge removes any of them listed above instead.'] : [])].join('\n'); +} + import { scrubPurgedSlugs } from '../feedback/store.ts'; +import { keptReason, readHeldConcepts, type RebuildKept } from './concept-rebuild.ts'; import { scrubPurgedNameStores } from './purge-name-stores.ts'; import { scrubPurgedSlugHolds, scrubPurgedSlugStores } from './purge-slug-stores.ts'; import { expireGonePageFacts } from '../facts/gone-page-facts.ts'; @@ -247,6 +264,8 @@ export interface PurgeSelection { writers: Record; /** GST-2689: the candidates that are parked origins the run's carry releases first (`forecast.release`). */ released_origins: Array<{ source_id: string; slug: string }>; + /** #9653: the concepts an input purge hid, which an automatic purge keeps, and those the next synthesis will not rebuild, with why. */ + rebuild: { held: Array<{ source_id: string; slug: string }>; kept: RebuildKept[] }; } /** @@ -264,7 +283,7 @@ export function purgeHoldsSql(page: string, source: string, released?: string): * selection the run makes once its carry has run, so it counts the parked origins the carry releases and leaves out the * origins it parks; the run itself reads the parks as they are. */ -export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; forecast?: CarryForecast } = {}): Promise { +export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; forecast?: CarryForecast; model?: boolean } = {}): Promise { const release = (opts.forecast?.release ?? []).map(origin => origin.id), hold = (opts.forecast?.hold ?? []).map(origin => origin.id); if (!await managedPersistenceEnabled(engine)) { const parked = (await recordedTombstones(engine, String(Math.max(0, Math.floor(olderThanHours))), release)) @@ -286,7 +305,7 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: blocked: [...(opts.retryParked ? [] : parked.map(row => ({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(row.park) }))), ...held.map(row => syncDeleteHeld(row, olderThanHours))], parked: parked.map(row => ({ source_id: row.source_id, slug: row.slug, failures: row.park.failures, code: row.park.code, retried: opts.retryParked === true })), - inactive: 0, held: held.length, sync_unreviewed: opts.automatic ? 0 : unreviewed.filter(row => row.expired).length, writers: {} }; + inactive: 0, held: held.length, sync_unreviewed: opts.automatic ? 0 : unreviewed.filter(row => row.expired).length, writers: {}, rebuild: await readHeldConcepts(engine, opts.model ?? true) }; } const hours = Math.max(0, Math.floor(olderThanHours)); const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; cutoff: string; deleted_us: string }>( @@ -299,7 +318,8 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: const parks = rows.length ? await readPurgeParks(engine) : new Map(); const unreviewed = new Set(rows.length ? (await readUnreviewedSyncTombstones(engine, hours)).map(row => row.id) : []); const rederive = new Set(rows.length && opts.automatic ? await readRederiveHeldConcepts(engine) : []); - const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, held: 0, sync_unreviewed: 0, writers: {}, released_origins: [] }; + const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, held: 0, sync_unreviewed: 0, writers: {}, released_origins: [], + rebuild: await readHeldConcepts(engine, opts.model ?? true) }; for (const { id, ...row } of rows) { const writer = states.get(row.source_id); const active = writer?.state !== 'recovery_required'; diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts index 60f0178f258..635a0187938 100644 --- a/src/core/pglite-engine.ts +++ b/src/core/pglite-engine.ts @@ -1337,7 +1337,7 @@ export class PGLiteEngine implements BrainEngine { async purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { return pagesImpl.purgeDeletedPages(this.engineSql, olderThanHours, opts); } diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts index 4f1a6fed012..ed1b31bb6d5 100644 --- a/src/core/postgres-engine.ts +++ b/src/core/postgres-engine.ts @@ -980,7 +980,7 @@ export class PostgresEngine implements BrainEngine { async purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { return pagesImpl.purgeDeletedPages(this.engineSql, olderThanHours, opts); } diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts new file mode 100644 index 00000000000..d1b4c356e54 --- /dev/null +++ b/test/concept-purge-rebuild-9653.test.ts @@ -0,0 +1,406 @@ +import { afterEach, describe, expect, spyOn, test } from 'bun:test'; +import { randomUUID } from 'node:crypto'; +import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts'; +import { __setChatTransportForTests } from '../src/core/ai/gateway.ts'; +import type { BrainEngine } from '../src/core/engine.ts'; +import type { OperationContext, AuthInfo } from '../src/core/ops/contract.ts'; +import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts'; +import { submitPageMutation } from '../src/core/persistence/page-mutations.ts'; +import { purgeDeletedPagesCoordinated, rebuildNote, selectPurgeCandidates } from '../src/core/persistence/purge-deleted.ts'; +import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts'; +import type { WriteRequest } from '../src/core/persistence/model.ts'; +import { REBUILD_STORES } from '../src/core/persistence/concept-rebuild.ts'; +import { installFaultHook } from '../src/core/persistence/fault-points.ts'; +import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts'; +import { proposeRevision } from '../src/core/access/policy.ts'; +import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts'; +import { sqlQueryForEngine } from '../src/core/sql-query.ts'; +import { mintLegacyToken } from '../src/core/token-mint.ts'; +import { dispatchToolCall } from '../src/mcp/dispatch.ts'; +import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts'; +import { setOwner } from '../src/core/access/owner.ts'; +import { bindCredential } from '../src/core/access/members.ts'; +import { runPages } from '../src/commands/pages.ts'; +import { runMaintain } from '../src/commands/maintain.ts'; +import { runCycle } from '../src/core/cycle.ts'; +import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts'; +import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts'; + +// #9653: a concept hidden by an input purge is rebuilt by purging its tombstone and writing a fresh page at the slug from +// its current members. Synthetic data only. +const MODEL = 'anthropic:claude-sonnet-4-6'; +const CONCEPT = 'concepts/storage-example'; +const OLD = 'A narrative built from atoms'; +const NEW = 'Rebuilt narrative canaryrebuilt.'; +const atom = (i: number) => `atoms/storage-${i}`; +const members = (ids: number[]) => ids.map(i => ({ slug: atom(i), concept_refs: [CONCEPT], body: `Atom ${i} about storage.`, title: `storage atom ${i}`, visibility: 'world' as const })); +const reply = (text: string): ChatResult => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end', + usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'anthropic' }); + +afterEach(() => { installFaultHook(undefined); __setChatTransportForTests(null); }); + +async function put(ctx: OperationContext, slug: string, body: string, type = 'atom'): Promise { + await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: `---\ntitle: ${slug}\ntype: ${type}\nvisibility: world\n---\n${body}` } }); +} +async function deletePage(engine: BrainEngine, ctx: OperationContext, slug: string): Promise> { + const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }); + return await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, expected_revision: snapshot!.revision, request_id: randomUUID() } }) as Record; +} +async function unmanagedWhile(engine: BrainEngine, on: boolean, fn: () => Promise): Promise { + await disposePersistenceConsumer(engine); + if (on) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); + try { return await fn(); } finally { + if (on) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); + await disposePersistenceConsumer(engine); + } +} +/** Moves a tombstone (and its rederive mark, which time moves with it) `hours` into the past. */ +async function age(engine: BrainEngine, slug: string, hours = 100): Promise { + await unmanagedWhile(engine, true, async () => { + await engine.executeRaw(`UPDATE needs_rederive n SET marked_at = n.marked_at - ($2 || ' hours')::interval FROM pages p + WHERE n.derived_table='pages' AND n.derived_id=p.id::text AND p.source_id='default' AND p.slug=$1`, [slug, String(hours)]); + await engine.executeRaw(`UPDATE pages SET deleted_at=deleted_at - ($2 || ' hours')::interval WHERE source_id='default' AND slug=$1`, [slug, String(hours)]); + }); +} +async function raw(engine: BrainEngine, sql: string, params: unknown[] = []): Promise { + await unmanagedWhile(engine, true, async () => { await engine.executeRaw(sql, params); }); +} +/** What a member who is neither the owner nor a reader gets from get_page over the remote path. */ +async function remoteRead(engine: BrainEngine): Promise { + const minted = await unmanagedWhile(engine, true, async () => { + await engine.executeRaw("INSERT INTO access_members (id) VALUES ('bob-example') ON CONFLICT DO NOTHING"); + await engine.executeRaw("INSERT INTO access_members (id) VALUES ('owner-example') ON CONFLICT DO NOTHING"); + await setOwner(engine, 'owner-example'); + const token = await mintLegacyToken(engine, { name: `bob-${randomUUID().slice(0, 8)}`, scopes: ['read'], takesHolders: ['world'], sourceGrant: ['default'] }); + await bindCredential(engine, { kind: 'token', id: token.id }, { member: 'bob-example' }); + await engine.executeRaw(`UPDATE access_tokens SET private_pages = 'granted_sources' WHERE id = $1`, [token.id]); + return token.token; + }); + __resetPrivateVisibilityCacheForTests(); + const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) }); + const auth = await provider.verifyAccessToken(minted) as unknown as AuthInfo; + const out = await dispatchToolCall(engine, 'get_page', { slug: CONCEPT }, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] }); + return out.content.map(c => c.text).join('\n'); +} +async function printedJson(run: () => Promise): Promise> { + const lines: string[] = []; + const log = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { lines.push(parts.join(' ')); }); + try { await run(); } finally { log.mockRestore(); } + return JSON.parse(lines.join('\n')); +} +async function purge(engine: BrainEngine, automatic: boolean): Promise { + return unmanagedWhile(engine, false, async () => (await purgeDeletedPagesCoordinated(engine, 72, { automatic })).slugs); +} +async function synthesize(engine: BrainEngine, root: string, ids: number[], opts: { text?: string; unmanaged?: boolean; during?: () => Promise; + read?: Record; requests?: ChatOpts[]; settle?: boolean } = {}) { + const chat = async (request: ChatOpts): Promise => { opts.requests?.push(request); await opts.during?.(); return reply(opts.text ?? `${OLD} ${ids.join(', ')}.`); }; + const result = await unmanagedWhile(engine, !!opts.unmanaged, () => runPhaseSynthesizeConcepts(engine, { sourceId: 'default', brainDir: root, + _atoms: members(ids).map(m => ({ ...m, revision: opts.read?.[m.slug] })), _chat: chat as never })); + if (opts.settle !== false) await settleManagedGitEffects(engine); + return result.details as Record; +} +async function state(engine: BrainEngine) { + const [row] = await engine.executeRaw<{ id: number | null; live: boolean | null; links_in: number; marks: number; versions: number; old_versions: number; old_chunks: number; old_journal: number; body: string | null }>(`SELECT + (SELECT id FROM pages WHERE source_id='default' AND slug=$1) AS id, + (SELECT deleted_at IS NULL FROM pages WHERE source_id='default' AND slug=$1) AS live, + (SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1) AS body, + (SELECT count(*)::int FROM links l JOIN pages n ON n.id=l.from_page_id JOIN pages c ON c.id=l.to_page_id WHERE c.slug=$1 AND n.slug='notes/storage-ref') AS links_in, + (SELECT count(*)::int FROM needs_rederive n JOIN pages c ON n.derived_id=c.id::text WHERE n.derived_table='pages' AND c.slug=$1) AS marks, + (SELECT count(*)::int FROM page_versions v JOIN pages c ON c.id=v.page_id WHERE c.slug=$1) AS versions, + (SELECT count(*)::int FROM page_versions WHERE compiled_truth LIKE '%' || $2 || '%') AS old_versions, + (SELECT count(*)::int FROM content_chunks WHERE chunk_text LIKE '%' || $2 || '%') AS old_chunks, + (SELECT count(*)::int FROM persistence_requests WHERE intent::text LIKE '%' || $2 || '%') AS old_journal`, [CONCEPT, OLD]); + return row!; +} +/** A concept built from atoms 0 to 4 and rebuilt from 1 to 5; a note links to it; atom 0's purge hides it. */ +async function heldConcept(engine: BrainEngine, ctx: OperationContext, root: string, live?: () => Promise): Promise { + await engine.setConfig('models.dream.synthesize', MODEL); + for (const i of [0, 1, 2, 3, 4, 5]) await put(ctx, atom(i), `Atom ${i} about storage.`); + await synthesize(engine, root, [0, 1, 2, 3, 4]); + await put(ctx, 'notes/storage-ref', 'See [[concepts/storage-example]] for the overview.', 'note'); + await deletePage(engine, ctx, atom(0)); + await age(engine, atom(0)); + await synthesize(engine, root, [1, 2, 3, 4, 5]); + await live?.(); + expect(await purge(engine, true)).toEqual([atom(0)]); + const held = await state(engine); + expect(held).toMatchObject({ live: false, marks: 1, links_in: 1 }); + expect(held.versions).toBeGreaterThan(0); + return Number(held.id); +} +const stillHeld = async (engine: BrainEngine, id: number, links = 1) => { + const now = await state(engine); + expect(now).toMatchObject({ id, live: false, marks: 1, links_in: links }); + expect(now.versions).toBeGreaterThan(0); +}; + +for (const backend of testBackends()) { + const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined; + describe(`a concept hidden by an input purge is rebuilt as a fresh page (${backend})`, () => { + for (const unmanaged of [false, true]) { + const mode = unmanaged ? 'unmanaged' : 'managed'; + test(`${mode}: the tombstone is purged and a fresh page written; nothing of the old body reaches the model or stays`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const requests: ChatOpts[] = []; + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, requests }); + expect(details.rebuilt).toEqual([CONCEPT]); + expect(requests).toHaveLength(1); + expect(JSON.stringify(requests[0]!.messages)).not.toContain(OLD); + expect(JSON.stringify(requests[0]!.messages)).toContain('Atom 5 about storage.'); + const rebuilt = await state(engine); + expect(rebuilt).toMatchObject({ live: true, marks: 0, old_versions: 0, old_chunks: 0 }); + expect(rebuilt.id).not.toBe(id); + expect(rebuilt.body).toContain('canaryrebuilt'); + if (!unmanaged) expect(rebuilt.old_journal).toBe(0); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND deleted_at IS NOT NULL', [CONCEPT])).toHaveLength(0); + expect(await engine.executeRaw('SELECT 1 FROM page_purges WHERE slug=$1', [CONCEPT])).toHaveLength(0); + // the incoming link: unmanaged in the rebuild's transaction; managed at the extract phase of the same cycle + expect(rebuilt.links_in).toBe(unmanaged ? 1 : 0); + if (!unmanaged) { + await runCycle(engine, { brainDir: root, phases: ['extract'], sourceId: 'default' }); + expect((await state(engine)).links_in).toBe(1); + } + }, { databaseUrl }); + }, 300_000); + + test(`${mode}: a failed synthesis leaves it hidden and held`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: '', unmanaged }); + expect(details.rebuild_deferred.map((d: { concept: string }) => d.concept)).toEqual([CONCEPT]); + await stillHeld(engine, id); + }, { databaseUrl }); + }, 300_000); + + test(`${mode}: during the model call, a person's delete, a released hold or a second input purge writes nothing`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, during: async () => { await deletePage(engine, ctx, CONCEPT); } }); + expect(details.rebuilt).toEqual([]); + expect(await state(engine)).toMatchObject({ live: false }); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND compiled_truth LIKE $2', [CONCEPT, '%canaryrebuilt%'])).toHaveLength(0); + }, { databaseUrl }); + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + await age(engine, CONCEPT); + await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, during: async () => { expect(await purge(engine, false)).toEqual([CONCEPT]); } }); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND compiled_truth LIKE $2', [CONCEPT, '%canaryrebuilt%'])).toHaveLength(0); + }, { databaseUrl }); + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, during: async () => { + await deletePage(engine, ctx, atom(1)); + await age(engine, atom(1)); + expect(await purge(engine, true)).toEqual([atom(1)]); + } }); + expect(details.rebuilt).toEqual([]); + expect(await state(engine)).toMatchObject({ id, live: false, marks: 1 }); + expect((await synthesize(engine, root, [2, 3, 4, 5], { text: NEW, unmanaged })).rebuilt).toEqual([CONCEPT]); + }, { databaseUrl }); + }, 900_000); + + test(`${mode}: a folder rule still covers the fresh page and a remote non-owner reads nothing`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root, () => unmanagedWhile(engine, true, async () => { + const rule = await proposeRevision(engine, 'default', [{ id: 'concepts', prefix: 'concepts/', readable_by: ['member:alice-example'] }], { origin: 'cli', store: 'database' }); + expect(rule.state).toBe('applied'); + })); + const [before] = await engine.executeRaw<{ rules: string[] | null }>('SELECT folder_rule_ids AS rules FROM pages WHERE slug=$1', [CONCEPT]); + expect(before!.rules).not.toBeNull(); + expect((await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged })).rebuilt).toEqual([CONCEPT]); + const [after] = await engine.executeRaw<{ rules: string[] | null }>('SELECT folder_rule_ids AS rules FROM pages WHERE slug=$1', [CONCEPT]); + expect(after!.rules).toEqual(before!.rules); + expect(await remoteRead(engine)).not.toContain('canaryrebuilt'); + }, { databaseUrl }); + }, 600_000); + + test(`${mode}: what a person stated keeps it hidden and held, and the purge deletes none of it`, async () => { + const stated: Array<[string, (engine: BrainEngine, ctx: OperationContext, id: number) => Promise]> = [ + ['labels', async engine => raw(engine, 'UPDATE pages SET frontmatter = frontmatter || $2::text::jsonb WHERE source_id = $3 AND slug = $1', [CONCEPT, JSON.stringify({ readable_by: ['alice-example'] }), 'default'])], + ['links', async (engine, _ctx, id) => raw(engine, "INSERT INTO links (from_page_id, to_page_id, link_type, link_source, context) SELECT n.id, $1, 'mentions', 'manual', 'added by hand' FROM pages n WHERE n.slug = 'notes/storage-ref'", [id])], + ['facts', async engine => raw(engine, "INSERT INTO facts (source_id, fact, source, entity_slug) VALUES ('default', 'A stated fact about storage.', 'mcp:remember', $1)", [CONCEPT])], + ['tags', async (engine, _ctx, id) => raw(engine, "INSERT INTO tags (page_id, tag) VALUES ($1, 'hand-tag')", [id])], + ['timeline_entries', async (engine, _ctx, id) => raw(engine, "INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', 'a stated event')", [id])], + ]; + for (const [kind, add] of stated) await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + await add(engine, ctx, id); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged }); + expect(details.rebuilt).toEqual([]); + expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'stated', kinds: [kind] }]); + await stillHeld(engine, id, kind === 'links' ? 2 : 1); + }, { databaseUrl }); + }, 1_500_000); + } + + test('access: a hidden concept no caller could read stays hidden when its current members are all world-readable', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + await raw(engine, "UPDATE pages SET frontmatter = frontmatter || '{\"visibility\":\"private\"}'::jsonb WHERE id = $1", [id]); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW }); + expect(details.rebuild_kept).toMatchObject([{ slug: CONCEPT, reason: 'access' }]); + await stillHeld(engine, id); + }, { databaseUrl }); + }, 300_000); + + test('managed: the publish waits on the purge receipt; a pending purge writes nothing more this cycle and the next one recovers', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + let release!: () => void; + const stalled = new Promise(resolve => { release = resolve; }); + installFaultHook(async (point, detail) => { if (point === 'consumer:prepared' && (detail as { operation?: string }).operation === 'delete_page') await stalled; }); + const restore = __setMaintenanceWriteWaitForTests(300); + try { + const details = (await runPhaseSynthesizeConcepts(engine, { sourceId: 'default', brainDir: root, _atoms: members([1, 2, 3, 4, 5]), _chat: (async () => reply(NEW)) as never })).details as Record; + expect(details.rebuilt).toEqual([]); + expect(details.rebuild_deferred).toMatchObject([{ concept: CONCEPT }]); + expect(details.rebuild_deferred[0].reason).toContain('still pending'); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND deleted_at IS NULL', [CONCEPT])).toHaveLength(0); + } finally { release(); restore(); installFaultHook(undefined); } + const open = await engine.executeRaw("SELECT * FROM persistence_requests WHERE source_id='default' AND state NOT IN ('committed','failed','cancelled')"); + for (const row of open) await waitForWrite(engine, row, { engine: engine.kind }, 20_000); + await settleManagedGitEffects(engine); + await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW }); + const recovered = await state(engine); + expect(recovered).toMatchObject({ live: true, old_versions: 0, old_chunks: 0 }); + expect(recovered.body).toContain('canaryrebuilt'); + }, { databaseUrl }); + }, 600_000); + + test('managed: a person who restores, edits or deletes the tombstone before the purge is submitted refuses it', async () => { + const moves: Array<(engine: BrainEngine, ctx: OperationContext) => Promise> = [ + async (_engine, ctx) => { await submitPageMutation(ctx, { operation: 'restore_page', params: { slug: CONCEPT, request_id: randomUUID() } }); }, + async (engine, ctx) => { + const at = await engine.readPageSnapshot(CONCEPT, { sourceId: 'default', includeDeleted: true }); + await submitPageMutation(ctx, { operation: 'put_page', params: { slug: CONCEPT, request_id: randomUUID(), expected_revision: at!.revision, + content: '---\ntitle: storage example\ntype: concept\n---\nWritten by a person.' } }); + }, + async (engine, ctx) => { await deletePage(engine, ctx, CONCEPT); }, + ]; + for (const move of moves) await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, during: () => move(engine, ctx) }); + expect(details.rebuilt).toEqual([]); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND compiled_truth LIKE $2', [CONCEPT, '%canaryrebuilt%'])).toHaveLength(0); + expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', [CONCEPT])).toHaveLength(1); + }, { databaseUrl }); + }, 900_000); + + test('the single-page purge deletes exactly what the cutoff purge deletes', async () => { + await managedBrain(async ({ engine, ctx }) => { + const slugs = ['notes/purge-a', 'notes/purge-b']; + for (const slug of slugs) { + await put(ctx, slug, `Body of ${slug} with [[notes/purge-other]].`, 'note'); + const at = await engine.readPageSnapshot(slug, { sourceId: 'default' }); + await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: at!.revision, + content: `---\ntitle: ${slug}\ntype: note\nvisibility: world\n---\nSecond body of ${slug} with [[notes/purge-other]].` } }); + } + await put(ctx, 'notes/purge-other', 'Links to [[notes/purge-a]] and [[notes/purge-b]].', 'note'); + await unmanagedWhile(engine, true, async () => { + for (const slug of slugs) { + const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]); + await engine.executeRaw("INSERT INTO tags (page_id, tag) VALUES ($1, 't')", [page!.id]); + await engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', 'e')", [page!.id]); + await engine.executeRaw("INSERT INTO facts (source_id, fact, source, source_markdown_slug) VALUES ('default', $2, 'test', $1)", [slug, `A fact on ${slug}.`]); + await engine.executeRaw("INSERT INTO page_aliases (source_id, slug, alias_norm) VALUES ('default', $1, $2)", [slug, `alias ${slug}`]); + await engine.executeRaw("INSERT INTO open_loops (source_id, page_slug, kind, summary) VALUES ('default', $1, 'promise', 'x')", [slug]).catch(() => undefined); + } + }); + await raw(engine, "UPDATE pages SET deleted_at = now() - interval '100 hours' WHERE source_id = 'default' AND slug = ANY($1::text[])", [slugs]); + const counts = async (slug: string) => (await engine.executeRaw>(`SELECT + (SELECT count(*)::int FROM pages WHERE slug=$1) AS pages, + (SELECT count(*)::int FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug=$1) AS chunks, + (SELECT count(*)::int FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug=$1) AS versions, + (SELECT count(*)::int FROM links l JOIN pages p ON p.id IN (l.from_page_id, l.to_page_id) WHERE p.slug=$1) AS links, + (SELECT count(*)::int FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL) AS live_facts, + (SELECT count(*)::int FROM page_aliases WHERE slug=$1) AS aliases, + (SELECT count(*)::int FROM open_loops WHERE page_slug=$1) AS loops`, [slug]))[0]!; + const before = [await counts(slugs[0]!), await counts(slugs[1]!)]; + expect(before[0]).toEqual(before[1]!); + expect(before[0]!.versions).toBeGreaterThan(0); + await unmanagedWhile(engine, true, async () => { + const [a] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug=$1", [slugs[0]]); + expect((await engine.purgeDeletedPages(0, { onlyIds: [Number(a!.id)] })).slugs).toEqual([slugs[0]!]); + expect(await counts(slugs[1]!)).toEqual(before[1]!); + expect((await engine.purgeDeletedPages(72)).slugs).toEqual([slugs[1]!]); + }); + expect(await counts(slugs[0]!)).toEqual(await counts(slugs[1]!)); + expect((await counts(slugs[0]!)).pages).toBe(0); + }, { databaseUrl }); + }, 300_000); + + test('every store a page purge removes rows from is classified stated or derived', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + const snapshot = await engine.readPageSnapshot(CONCEPT, { sourceId: 'default', includeDeleted: true }); + const receipt = await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: CONCEPT, purge: true, expected_revision: snapshot!.revision, request_id: randomUUID() } }) as { purge: { removed: Record } }; + for (const store of Object.keys(receipt.purge.removed)) expect([store, REBUILD_STORES[store]]).toEqual([store, expect.stringMatching(/^(stated|derived)$/)]); + }, { databaseUrl }); + }, 300_000); + + test('a concept a person deleted stays deleted, also after an input purge marks it', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await engine.setConfig('models.dream.synthesize', MODEL); + for (const i of [0, 1, 2, 3, 4]) await put(ctx, atom(i), `Atom ${i} about storage.`); + await synthesize(engine, root, [0, 1, 2, 3, 4]); + await deletePage(engine, ctx, CONCEPT); + await deletePage(engine, ctx, atom(0)); + await age(engine, atom(0)); + expect(await purge(engine, true)).toEqual([atom(0)]); + const details = await synthesize(engine, root, [1, 2, 3, 4], { text: NEW }); + expect(details.skipped_deleted).toEqual([CONCEPT]); + expect(await state(engine)).toMatchObject({ live: false }); + }, { databaseUrl }); + }, 300_000); + + test('a held concept a person then deletes stays deleted', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + await deletePage(engine, ctx, CONCEPT); + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW }); + expect(details.skipped_deleted).toEqual([CONCEPT]); + expect(await state(engine)).toMatchObject({ live: false }); + }, { databaseUrl }); + }, 300_000); + + test('the purge previews name each held concept and, for one kept hidden, why', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const held = [{ source_id: 'default', slug: CONCEPT }]; + expect((await selectPurgeCandidates(engine, 72, { automatic: true, model: false })).rebuild).toEqual({ held, kept: [{ ...held[0]!, reason: 'no_model' }] }); + __setChatTransportForTests(async () => reply(NEW)); + for (const automatic of [true, false]) expect((await selectPurgeCandidates(engine, 72, { automatic, model: true })).rebuild).toEqual({ held, kept: [] }); + const note = rebuildNote({ held, kept: [] }); + expect(note).toContain(`1 of them are rebuilt by the next concept synthesis from their current members: default/${CONCEPT}`); + const explicit = await printedJson(() => runPages(engine, ['purge-deleted', '--dry-run', '--json'])); + expect(explicit).toMatchObject({ rebuild: { held } }); + expect(explicit.rebuild_note).toEndWith('This purge removes any of them listed above instead.'); + const automatic = await printedJson(() => runMaintain(engine, ['--purge', '--json'])); + expect(automatic).toMatchObject({ mode: 'preview', rebuild: { held }, rebuild_note: note }); + await raw(engine, "INSERT INTO tags (page_id, tag) VALUES ($1, 'hand-tag')", [id]); + const kept = (await selectPurgeCandidates(engine, 72, { automatic: true, model: true })).rebuild; + expect(kept.kept).toEqual([{ ...held[0]!, reason: 'stated', kinds: ['tags'] }]); + expect(rebuildNote(kept)).toContain(`default/${CONCEPT}: stays hidden, it carries what a person or an agent stated (tags)`); + const phase = (await runCycle(engine, { brainDir: root, phases: ['purge'], sourceId: 'default' })).phases.find(p => p.phase === 'purge')!; + expect(phase.details).toMatchObject({ purged_pages_kept_for_rebuild: held, kept_hidden: kept.kept }); + expect(phase.summary).toContain('1 concept(s) hidden by an input purge kept for the next concept synthesis (1 of them stay hidden'); + expect(await state(engine)).toMatchObject({ live: false, marks: 1 }); + }, { databaseUrl }); + }, 300_000); + + for (const aged of [100, 10]) test(`deleting a held concept aged ${aged}h: the receipt states the true expiry and the tombstone keeps its date`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + await age(engine, CONCEPT, aged); + const [before] = await engine.executeRaw<{ at: string; until: string }>(`SELECT deleted_at::text AS at, + to_char((deleted_at + interval '72 hours') AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS until FROM pages WHERE slug=$1`, [CONCEPT]); + const receipt = await deletePage(engine, ctx, CONCEPT); + const [after] = await engine.executeRaw<{ at: string }>('SELECT deleted_at::text AS at FROM pages WHERE slug=$1', [CONCEPT]); + expect(after!.at).toBe(before!.at); + expect(String(receipt.recoverable_until)).toStartWith(aged > 72 ? `the next purge (its 72h window ended ${before!.until})` : `${before!.until} via restore_page`); + expect(await purge(engine, true)).toEqual(aged > 72 ? [CONCEPT] : []); + }, { databaseUrl }); + }, 300_000); + }); +} diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt index 26575bb8cfd..74837d8a46a 100644 --- a/test/postgres-unit-arms.txt +++ b/test/postgres-unit-arms.txt @@ -80,6 +80,7 @@ test/code-edges-parity.test.ts test/colon-slug-windows-5032.test.ts test/company-brain-policy.test.ts test/company-brain-runtime.test.ts +test/concept-purge-rebuild-9653.test.ts test/concept-rename-history-gst2687.test.ts test/consolidate-fenced-close-reimport.test.ts test/consolidate-same-instant-6023.test.ts From 3dbf0017ea2505430e1acbfdc3d6abf0347f6c1f Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 06:00:03 +0000 Subject: [PATCH 10/37] Update the type-surface golden for purgeDeletedPages onlyIds Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- test/fixtures/goldens/exports/types.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json index 5fbbce09564..9d4aa931ad1 100644 --- a/test/fixtures/goldens/exports/types.json +++ b/test/fixtures/goldens/exports/types.json @@ -208,7 +208,7 @@ "pageCollapseFacts: (ids: number[], bodyIds: number[]) => Promise", "pagesLinkingTo: (fromIds: number[], toIds: number[]) => Promise", "pruneFrontmatterTags: (slug: string, keep: readonly string[], opts?: { sourceId?: string; }) => Promise", - "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", + "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", "putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record; ttl_seconds?: number; }) => Promise", "putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise", "putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise", @@ -1330,7 +1330,7 @@ "private vectorScope", "private withScopedReadTransaction", "pruneFrontmatterTags: (slug: string, keep: readonly string[], opts?: { sourceId?: string; }) => Promise", - "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", + "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", "putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record; ttl_seconds?: number; }) => Promise", "putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise", "putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise", @@ -3890,7 +3890,7 @@ "pageCollapseFacts: (ids: number[], bodyIds: number[]) => Promise", "pagesLinkingTo: (fromIds: number[], toIds: number[]) => Promise", "pruneFrontmatterTags: (slug: string, keep: readonly string[], opts?: { sourceId?: string; }) => Promise", - "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", + "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", "putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record; ttl_seconds?: number; }) => Promise", "putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise", "putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise", @@ -7477,7 +7477,7 @@ "private vectorIterativeScan", "private vectorScope", "pruneFrontmatterTags: (slug: string, keep: readonly string[], opts?: { sourceId?: string; }) => Promise", - "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", + "purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[]; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date; }[]; }>", "putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record; ttl_seconds?: number; }) => Promise", "putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise", "putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise", From 5267e1b5a1d2bd1cabb93a87b416c9c8fe83b051 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 06:25:28 +0000 Subject: [PATCH 11/37] Rebuild runs in one belief batch (page.expired) and parks derived origins before the purge; census row; preview wording Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- docs/architecture/canonical-writers.tsv | 1 + src/core/cycle/concept-publication.ts | 11 +++------- src/core/persistence/concept-rebuild.ts | 29 +++++++++++++++++++++++-- src/core/persistence/purge-deleted.ts | 2 +- test/concept-purge-rebuild-9653.test.ts | 17 ++++++++++++++- 5 files changed, 48 insertions(+), 12 deletions(-) diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv index 5d4df181c75..202628511cd 100644 --- a/docs/architecture/canonical-writers.tsv +++ b/docs/architecture/canonical-writers.tsv @@ -314,3 +314,4 @@ src/core/access/attest-sources.ts 1 projection GST-1113: applyAttestSources sets src/core/storage-manifest/source.ts 1 contract markRole sets role and federated in the config of the storage source that addSource or hostRepo created in the same storage init or first repo-less register; it writes source configuration only, never page content. src/core/guests/sources.ts 1 projection GBRA-504 guest source setup (initGuestSource, the trusted local gbrain guests init): merges the guest, federated and trust_ceiling keys into sources.config in the transaction that writes the guest_sources row; a settings field, not page content, and canonical columns stay guarded by SQL triggers. src/core/git/redact-finish.ts 1 contract GST-2988 PR 2: finishRedactions moves sources.last_commit from a commit a publish redaction rebuilt to its rebuilt copy (compare-and-set on the old sha, from the redactions journal beside the checkout); it writes no page content, and the page side goes through repair/secret-spans.ts redactPageForPublish. +src/core/persistence/concept-rebuild.ts 1 engine_guard #9653: on an unmanaged brain, a concept an input purge hid is rebuilt in one transaction that hard-purges only that tombstone through the engine purge (purgeDeletedPages onlyIds, the expiry statements and holds), inside a belief batch (page.expired) like the recorded-tombstone expiry, then imports the fresh page; a managed brain submits delete_page purge through the coordinator instead. diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts index 6dafbebf36b..edfde7b3fa7 100644 --- a/src/core/cycle/concept-publication.ts +++ b/src/core/cycle/concept-publication.ts @@ -25,7 +25,7 @@ import { acquirePageLock } from '../page-lock.ts'; import { derivedFileTarget, writeDerivedPageThrough } from './derived-write-through.ts'; import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts'; import { declareDerivation, deriveTrust, lowerDerivedPage } from '../trust/taint.ts'; -import { finishConceptRebuild, purgeHeldConcept, type ConceptRebuild } from '../persistence/concept-rebuild.ts'; +import { rebuildHeldConcept, type ConceptRebuild } from '../persistence/concept-rebuild.ts'; /** #5575 I2: the narrative carries the tier of the member atoms its prompt was built from (capped at agent_written). */ const conceptDerivation = (engine: BrainEngine, sourceId: string, members: readonly string[]) => @@ -269,7 +269,7 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s try { const { rebuild } = opts; const snapshot = await engine.readPageSnapshot(slug, { sourceId, ...(rebuild ? { includeDeleted: true } : {}) }); - // #9653: a rebuild is composed from nothing in the tombstone; purgeHeldConcept confirms the hold under the lock. + // #9653: a rebuild is composed from nothing in the tombstone; rebuildHeldConcept confirms the hold under the lock. const page = rebuild ? null : snapshot?.page ?? null; if (rebuild ? snapshot?.page.deleted_at == null : stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline) || (page && !String(page.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts'))) { @@ -285,12 +285,7 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s ? composeConceptRepublication(page, snapshot!.tags, synthesized, narrative) : serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] }); if (rebuild) { - await engine.transaction(async tx => { - const before = await purgeHeldConcept(tx, sourceId, slug, rebuild); - if (typeof before === 'string') throw Object.assign(new Error(before), { code: 'revision_conflict' }); - await opts.importPage(markdown, tx); - await finishConceptRebuild(tx, sourceId, slug, before); - }); + await rebuildHeldConcept(engine, sourceId, slug, rebuild, tx => opts.importPage(markdown, tx)); } else await opts.importPage(markdown); // The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges. if (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug); diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index 5ac706d136b..e594e0bbe4c 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -16,6 +16,9 @@ import type { BrainEngine, LinkBatchInput, PageSnapshot } from '../engine.ts'; import type { OperationContext } from '../ops/contract.ts'; import { loadConfig } from '../config.ts'; import { submitPageMutation } from './page-mutations.ts'; +import { linkStreamSlugs } from './page-purge.ts'; +import { withBeliefBatch } from '../belief/ledger.ts'; +import { markBeliefCommits } from '../belief/append.ts'; import { maintenancePublishWaitMs } from './maintenance-wait.ts'; import { pendingRequestId } from '../cycle/dream-write-deferral.ts'; import { OWED_PURGE_OP } from './derived-origin-hold.ts'; @@ -135,7 +138,7 @@ export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot * purge), then hard-purges the tombstone with the expiry's own statements (engine purgeDeletedPages, onlyIds). Returns * why it purged nothing, or the tombstone's access and the incoming links the fresh page takes over. */ -export async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { +async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { const [held] = await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = $1 AND p.source_id = $2 AND p.slug = $3 AND ${DELETED_US} = $4 AND ${HELD_SQL} FOR UPDATE OF p`, [rebuild.page_id, sourceId, slug, rebuild.deleted_us]); if (!held) return 'The concept is no longer held for a rebuild (a person or sync deleted, restored or purged it), so the rebuild wrote nothing.'; @@ -148,13 +151,15 @@ export async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: o.slug AS origin_slug, l.origin_field, f.source_id AS from_source_id, $3::text AS to_source_id, o.source_id AS origin_source_id FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL`, [rebuild.page_id, slug, sourceId]); + const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts'); + await parkUncarriedInPurge(tx, [rebuild.page_id]); const purged = await tx.purgeDeletedPages(0, { onlyIds: [rebuild.page_id] }); if (purged.count !== 1 || !access) return 'The tombstone is held by another purge rule, so the rebuild wrote nothing and it stays held.'; return { access, incoming }; } /** Unmanaged, after the fresh write in the same transaction: points the incoming links at it and confirms it reads no wider. */ -export async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: LinkBatchInput[] }): Promise { +async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: LinkBatchInput[] }): Promise { const [fresh] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]); if (!fresh) throw Object.assign(new Error('The rebuilt concept was not written (the import refused it), so the rebuild wrote nothing and the concept stays held.'), { code: 'revision_conflict' }); if (before.incoming.length) await tx.addLinksBatch(before.incoming); @@ -166,6 +171,26 @@ export async function finishConceptRebuild(tx: BrainEngine, sourceId: string, sl } } +/** + * Unmanaged: one transaction purges the held tombstone, writes the fresh page through `write` and carries the incoming + * links over. Like the expiry of a recorded tombstone (purge-deleted.ts), it runs in one belief batch over the page and + * its link streams, so the ledger ends the old page's lifetime as `page.expired` and the fresh page starts a new one. + */ +export async function rebuildHeldConcept(engine: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild, write: (tx: BrainEngine) => Promise): Promise { + const publicationId = randomUUID(), report = { appended: 0 }; + await engine.transaction(async tx => { + const slugs = [...new Set([slug, ...await linkStreamSlugs(tx, sourceId, rebuild.page_id)])].sort(); + await tx.lockPageKeys(slugs.map(key => ({ sourceId, slug: key }))); + await withBeliefBatch(tx, { sourceId, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report }, async () => { + const before = await purgeHeldConcept(tx, sourceId, slug, rebuild); + if (typeof before === 'string') throw Object.assign(new Error(before), { code: 'revision_conflict' }); + await write(tx); + await finishConceptRebuild(tx, sourceId, slug, before); + }); + }); + if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined); +} + /** * Managed: submits the retention purge of the tombstone, pinned to the revision the synthesis read, so a person's edit, * restore or delete in between refuses it. True only when its receipt shows the purge committed; a pending, failed or diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts index 3d418ec4ac3..c246f9682d0 100644 --- a/src/core/persistence/purge-deleted.ts +++ b/src/core/persistence/purge-deleted.ts @@ -44,7 +44,7 @@ export function rebuildNote(rebuild: PurgeSelection['rebuild'], removes = false) const kept = new Set(rebuild.kept.map(k => `${k.source_id}/${k.slug}`)); const next = rebuild.held.filter(c => !kept.has(`${c.source_id}/${c.slug}`)); return [`${rebuild.held.length} concept(s) hidden by an input purge are kept out of the automatic purge.`, - ...(next.length ? [`${next.length} of them are rebuilt by the next concept synthesis from their current members: ${next.slice(0, 20).map(c => `${c.source_id}/${c.slug}`).join(', ')}${next.length > 20 ? ` and ${next.length - 20} more` : ''}.`] : []), + ...(next.length ? [`${next.length} of them are rebuilt by the next concept synthesis that still finds at least two members for them (one with fewer stays hidden until an explicit purge): ${next.slice(0, 20).map(c => `${c.source_id}/${c.slug}`).join(', ')}${next.length > 20 ? ` and ${next.length - 20} more` : ''}.`] : []), ...rebuild.kept.slice(0, 20).map(keptReason), ...(rebuild.kept.length > 20 ? [`...and ${rebuild.kept.length - 20} more kept hidden`] : []), ...(removes ? ['This purge removes any of them listed above instead.'] : [])].join('\n'); } diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index d1b4c356e54..20d623b6ddd 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -23,6 +23,8 @@ import { bindCredential } from '../src/core/access/members.ts'; import { runPages } from '../src/commands/pages.ts'; import { runMaintain } from '../src/commands/maintain.ts'; import { runCycle } from '../src/core/cycle.ts'; +import { enableBeliefLedger } from '../src/core/belief/coverage.ts'; +import { readEvents } from './helpers/belief-ledger.ts'; import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts'; import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts'; @@ -164,6 +166,19 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); + if (unmanaged) test('unmanaged, belief ledger on: the rebuild ends the old page as page.expired and the fresh page starts its own lifetime', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + await enableBeliefLedger(engine, 'default'); + const after = Math.max(0, ...(await readEvents(engine, 'default')).map(e => e.id)); + expect((await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged: true })).rebuilt).toEqual([CONCEPT]); + const events = (await readEvents(engine, 'default', after)).filter(e => e.slug === CONCEPT && e.subject_kind === 'page'); + const expired = events.find(e => e.event_type === 'page.expired'); + expect(expired?.purged).toBe(false); + expect(events.filter(e => e.page_lifetime !== expired!.page_lifetime).length).toBeGreaterThan(0); + }, { databaseUrl }); + }, 300_000); + test(`${mode}: a failed synthesis leaves it hidden and held`, async () => { await managedBrain(async ({ engine, ctx, root }) => { const id = await heldConcept(engine, ctx, root); @@ -372,7 +387,7 @@ for (const backend of testBackends()) { __setChatTransportForTests(async () => reply(NEW)); for (const automatic of [true, false]) expect((await selectPurgeCandidates(engine, 72, { automatic, model: true })).rebuild).toEqual({ held, kept: [] }); const note = rebuildNote({ held, kept: [] }); - expect(note).toContain(`1 of them are rebuilt by the next concept synthesis from their current members: default/${CONCEPT}`); + expect(note).toContain(`1 of them are rebuilt by the next concept synthesis that still finds at least two members for them (one with fewer stays hidden until an explicit purge): default/${CONCEPT}`); const explicit = await printedJson(() => runPages(engine, ['purge-deleted', '--dry-run', '--json'])); expect(explicit).toMatchObject({ rebuild: { held } }); expect(explicit.rebuild_note).toEndWith('This purge removes any of them listed above instead.'); From 812e66d5791095a9919a5b35a90549d049a13f48 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 06:26:59 +0000 Subject: [PATCH 12/37] fix: pre-landing review fixes Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/cycle.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/cycle.ts b/src/core/cycle.ts index 1696a95857b..9e69308bf78 100644 --- a/src/core/cycle.ts +++ b/src/core/cycle.ts @@ -1801,7 +1801,10 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise { // #9653: kept for the next concept synthesis + console.warn(`[cycle] held-concept report skipped: ${e instanceof Error ? e.message : String(e)}`); + return { held: [], kept: [] }; + }); // #6770: request-log rows past cycle.purge.mcp_request_log_retention_days, when set (logic in mcp-request-log-retention.ts). let purgedMcpLog = 0; try { purgedMcpLog = (await (await import('./mcp-request-log-retention.ts')).runMcpLogRetention(engine))?.deleted ?? 0; } catch (e) { console.warn(`[cycle] request-log retention skipped: ${e instanceof Error ? e.message : String(e)}`); } From f1dc3129544ac47049deb3077bdb5ce0d4a9ab5d Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 06:47:13 +0000 Subject: [PATCH 13/37] fix: leave provenance edges out of the rebuild carry; keep the park when the rebuild refuses Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p2/outside-voice#2 reader=outside-voice Review-Finding: p2/specialist-batched#1 reader=specialist-batched Review-Finding: p2/adversarial-native#1 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 11 ++++++--- test/concept-purge-rebuild-9653.test.ts | 31 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index e594e0bbe4c..4d16ca2e8c4 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -138,7 +138,7 @@ export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot * purge), then hard-purges the tombstone with the expiry's own statements (engine purgeDeletedPages, onlyIds). Returns * why it purged nothing, or the tombstone's access and the incoming links the fresh page takes over. */ -async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { +async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { const [held] = await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = $1 AND p.source_id = $2 AND p.slug = $3 AND ${DELETED_US} = $4 AND ${HELD_SQL} FOR UPDATE OF p`, [rebuild.page_id, sourceId, slug, rebuild.deleted_us]); if (!held) return 'The concept is no longer held for a rebuild (a person or sync deleted, restored or purged it), so the rebuild wrote nothing.'; @@ -150,9 +150,11 @@ async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, const incoming = await tx.executeRaw(`SELECT f.slug AS from_slug, $2::text AS to_slug, l.link_type, l.context, l.link_source, o.slug AS origin_slug, l.origin_field, f.source_id AS from_source_id, $3::text AS to_source_id, o.source_id AS origin_source_id FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id - WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL`, [rebuild.page_id, slug, sourceId]); + WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL AND l.link_source IS DISTINCT FROM 'concept-provenance'`, [rebuild.page_id, slug, sourceId]); const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts'); - await parkUncarriedInPurge(tx, [rebuild.page_id]); + if ((await parkUncarriedInPurge(tx, [rebuild.page_id])).length) { + return { parked: 'A page written since depends on the concept for its privacy, so the concept is parked until the next purge labels it and the rebuild wrote nothing.' }; + } const purged = await tx.purgeDeletedPages(0, { onlyIds: [rebuild.page_id] }); if (purged.count !== 1 || !access) return 'The tombstone is held by another purge rule, so the rebuild wrote nothing and it stays held.'; return { access, incoming }; @@ -178,17 +180,20 @@ async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: str */ export async function rebuildHeldConcept(engine: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild, write: (tx: BrainEngine) => Promise): Promise { const publicationId = randomUUID(), report = { appended: 0 }; + let parked: string | undefined; await engine.transaction(async tx => { const slugs = [...new Set([slug, ...await linkStreamSlugs(tx, sourceId, rebuild.page_id)])].sort(); await tx.lockPageKeys(slugs.map(key => ({ sourceId, slug: key }))); await withBeliefBatch(tx, { sourceId, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report }, async () => { const before = await purgeHeldConcept(tx, sourceId, slug, rebuild); if (typeof before === 'string') throw Object.assign(new Error(before), { code: 'revision_conflict' }); + if ('parked' in before) { parked = before.parked; return; } await write(tx); await finishConceptRebuild(tx, sourceId, slug, before); }); }); if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined); + if (parked) throw Object.assign(new Error(parked), { code: 'revision_conflict' }); } /** diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index 20d623b6ddd..b20b662deaa 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -25,6 +25,8 @@ import { runMaintain } from '../src/commands/maintain.ts'; import { runCycle } from '../src/core/cycle.ts'; import { enableBeliefLedger } from '../src/core/belief/coverage.ts'; import { readEvents } from './helpers/belief-ledger.ts'; +import * as originCarry from '../src/core/repair/origin-carry.ts'; +import { parkDerivedOrigin, readDerivedOriginParks } from '../src/core/persistence/derived-origin-hold.ts'; import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts'; import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts'; @@ -179,6 +181,35 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); + if (unmanaged) test('unmanaged, belief ledger on: a member that left gets its provenance edge retracted, never carried to the fresh page', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + await heldConcept(engine, ctx, root); + await enableBeliefLedger(engine, 'default'); + const after = Math.max(0, ...(await readEvents(engine, 'default')).map(e => e.id)); + expect((await synthesize(engine, root, [1, 2, 3, 4], { text: NEW, unmanaged: true })).rebuilt).toEqual([CONCEPT]); + const left = (await readEvents(engine, 'default', after)).filter(e => e.slug === atom(5) && e.subject_kind === 'link'); + expect(await engine.executeRaw(`SELECT 1 FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id + WHERE f.slug = $1 AND t.slug = $2 AND l.link_source = 'concept-provenance'`, [atom(5), CONCEPT])).toHaveLength(0); + expect(left.map(e => e.event_type)).toEqual(['link.retracted']); + }, { databaseUrl }); + }, 300_000); + + if (unmanaged) test('unmanaged: a park the rebuild writes for a dependent survives its refusal', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const spy = spyOn(originCarry, 'parkUncarriedInPurge').mockImplementation(async (tx, ids) => { + const park = { source_id: 'default', slug: CONCEPT, page_id: Number(ids[0]), blocking_slug: 'notes/storage-ref', code: 'dependent_written_mid_purge', reason: 'notes/storage-ref depends on it.' }; + await parkDerivedOrigin(tx, park); + return [{ ...park, parked_at: new Date().toISOString() }]; + }); + try { + expect((await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged: true })).rebuilt).toEqual([]); + } finally { spy.mockRestore(); } + await stillHeld(engine, id); + expect((await readDerivedOriginParks(engine)).map(p => p.page_id)).toEqual([id]); + }, { databaseUrl }); + }, 300_000); + test(`${mode}: a failed synthesis leaves it hidden and held`, async () => { await managedBrain(async ({ engine, ctx, root }) => { const id = await heldConcept(engine, ctx, root); From afe20468ee33e40b82f580324f3a5da1e5b12dd5 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 07:16:11 +0000 Subject: [PATCH 14/37] Hold concepts with curated Facets or Merged sections; managed brains keep held concepts hidden until the write owner re-checks them (GST-3179) Review-Finding: p3/outside-voice#2 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 24 +++++++++++--- test/concept-purge-rebuild-9653.test.ts | 44 +++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index 4d16ca2e8c4..12844c89f20 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -24,6 +24,10 @@ import { pendingRequestId } from '../cycle/dream-write-deferral.ts'; import { OWED_PURGE_OP } from './derived-origin-hold.ts'; import { extractedFromPageSql } from '../facts/gone-page-facts.ts'; import { PRIVACY_ALIASES, privacyPartSql, privatePagesFilterFragment } from '../search/private-visibility.ts'; +import { preservedConceptSections } from '../cycle/concept-sections.ts'; +import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts'; +import { BOUNDED_PREFIX_BYTES } from '../page-window/document.ts'; +import { managedPersistenceEnabled } from './ownership.ts'; type Sql = Pick; @@ -31,7 +35,12 @@ type Sql = Pick; export interface ConceptRebuild { page_id: number; deleted_us: string; revision: string; members: Array<{ slug: string; revision: string }> } /** Why a held concept is not rebuilt: something a person or an agent stated (with the kinds), no model, or wider access. */ -export type RebuildKept = { source_id: string; slug: string } & ({ reason: 'stated'; kinds: string[] } | { reason: 'no_model' } | { reason: 'access'; why: string }); +export type RebuildKept = { source_id: string; slug: string } & ({ reason: 'stated'; kinds: string[] } | { reason: 'no_model' } | { reason: 'managed' } | { reason: 'access'; why: string }); + +let managedRebuild = false; +/** GST-3179 re-checks the hold and the members inside the write owner's transaction; until then a managed brain keeps its held concepts hidden. */ +export function __setManagedConceptRebuildForTests(on: boolean): void { managedRebuild = on; } +const managedHeld = async (engine: Sql) => !managedRebuild && await managedPersistenceEnabled(engine); /** Frontmatter keys only an owner or an agent sets on a concept (synthesis writes visibility alone): any of them is stated. */ const STATED_LABEL_KEYS: readonly string[] = [...Object.keys(PRIVACY_ALIASES), 'readable_by', 'pinned_question', 'derived_from']; @@ -79,12 +88,15 @@ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM write_gate_holds h WHERE h.source_id = $2 AND h.slug = $3) THEN 'write_gate_holds' END, CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.frontmatter ?| $5::text[]) THEN 'labels' END -], NULL) AS kinds`; +], NULL) AS kinds, + (SELECT ${boundedBodyPrefixSql('p')} FROM pages p WHERE p.id = $1) AS lead, (SELECT p.body_storage = 'segmented' FROM pages p WHERE p.id = $1) AS segmented`; /** The kinds of stated rows the concept carries; empty when it carries none. */ export async function statedKinds(engine: Sql, pageId: number, sourceId: string, slug: string): Promise { - const [row] = await engine.executeRaw<{ kinds: string[] | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS]); - return row?.kinds ?? []; + const [row] = await engine.executeRaw<{ kinds: string[] | null; lead: string | null; segmented: boolean | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS]); + // A body past the bounded lead is not scanned, so it may hold curated sections and counts as if it did. + const unread = row?.segmented === true || (row?.lead ?? '').length >= BOUNDED_PREFIX_BYTES; + return [...row?.kinds ?? [], ...unread || preservedConceptSections(row?.lead ?? '').length ? ['curated_sections'] : []]; } /** Who may read a page, as the read predicate decides it: compared before and after a rebuild (rebuildWidens). */ @@ -122,6 +134,7 @@ export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot const slug = snapshot.page.slug; const kinds = await statedKinds(engine, pageId, sourceId, slug); if (kinds.length) return { kept: { source_id: sourceId, slug, reason: 'stated', kinds } }; + if (await managedHeld(engine)) return { kept: { source_id: sourceId, slug, reason: 'managed' } }; const access = await readRebuildAccess(engine, pageId); if (!access || (visibility === 'world' && !access.public_part)) return { kept: { source_id: sourceId, slug, reason: 'access', why: WIDER } }; const rows = await engine.executeRaw<{ slug: string; revision: string }>(`SELECT slug, knowledge_revision::text AS revision FROM pages @@ -232,9 +245,11 @@ export async function readHeldConcepts(engine: Sql, model: boolean): Promise<{ h WHERE d.derived_table = 'pages' AND d.derived_id = p.id::text AND m.deleted_at IS NULL AND NOT (${privatePagesFilterFragment('m')})) AS members_private FROM pages p WHERE ${HELD_SQL} ORDER BY p.source_id, p.slug`); const kept: RebuildKept[] = []; + const managed = rows.length > 0 && await managedHeld(engine); for (const row of rows) { const kinds = await statedKinds(engine, Number(row.id), row.source_id, row.slug); if (kinds.length) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'stated', kinds }); + else if (managed) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'managed' }); else if (row.private && !row.members_private) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'access', why: WIDER }); else if (!model) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'no_model' }); } @@ -252,5 +267,6 @@ export async function tombstoneWindow(tx: Sql, pageId: number, hours: number): P export function keptReason(kept: RebuildKept): string { if (kept.reason === 'stated') return `${kept.source_id}/${kept.slug}: stays hidden, it carries what a person or an agent stated (${kept.kinds.join(', ')})`; if (kept.reason === 'access') return `${kept.source_id}/${kept.slug}: stays hidden, a rebuild would be readable more widely (${kept.why})`; + if (kept.reason === 'managed') return `${kept.source_id}/${kept.slug}: stays hidden, its rebuild on a managed brain waits for a later release`; return `${kept.source_id}/${kept.slug}: stays hidden, no synthesis model is configured to rebuild it`; } diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index b20b662deaa..91e4f755b38 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -1,4 +1,6 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; +import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; +import { rmSync } from 'node:fs'; +import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts'; import { __setChatTransportForTests } from '../src/core/ai/gateway.ts'; @@ -9,7 +11,7 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts'; import { purgeDeletedPagesCoordinated, rebuildNote, selectPurgeCandidates } from '../src/core/persistence/purge-deleted.ts'; import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts'; import type { WriteRequest } from '../src/core/persistence/model.ts'; -import { REBUILD_STORES } from '../src/core/persistence/concept-rebuild.ts'; +import { REBUILD_STORES, __setManagedConceptRebuildForTests } from '../src/core/persistence/concept-rebuild.ts'; import { installFaultHook } from '../src/core/persistence/fault-points.ts'; import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts'; import { proposeRevision } from '../src/core/access/policy.ts'; @@ -141,6 +143,28 @@ const stillHeld = async (engine: BrainEngine, id: number, links = 1) => { for (const backend of testBackends()) { const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined; describe(`a concept hidden by an input purge is rebuilt as a fresh page (${backend})`, () => { + beforeAll(() => __setManagedConceptRebuildForTests(true)); + afterAll(() => __setManagedConceptRebuildForTests(false)); + test('managed, without the write owner re-check: synthesis leaves the hidden concept exactly as it was and says why', async () => { + __setManagedConceptRebuildForTests(false); + try { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const before = (await engine.readPageSnapshot(CONCEPT, { sourceId: 'default', includeDeleted: true }))!.revision; + const requests: ChatOpts[] = []; + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, requests }); + expect(details.rebuilt).toEqual([]); + expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'managed' }]); + expect(requests).toHaveLength(0); + await stillHeld(engine, id); + expect((await engine.readPageSnapshot(CONCEPT, { sourceId: 'default', includeDeleted: true }))!.revision).toBe(before); + const preview = (await selectPurgeCandidates(engine, 72, { automatic: true, model: true })).rebuild; + expect(preview.kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'managed' }]); + expect(rebuildNote(preview)).toContain(`default/${CONCEPT}: stays hidden, its rebuild on a managed brain waits for a later release`); + }, { databaseUrl }); + } finally { __setManagedConceptRebuildForTests(true); } + }, 300_000); + for (const unmanaged of [false, true]) { const mode = unmanaged ? 'unmanaged' : 'managed'; test(`${mode}: the tombstone is purged and a fresh page written; nothing of the old body reaches the model or stays`, async () => { @@ -210,6 +234,22 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); + test(`${mode}: a curated ## Facets section on the hidden concept keeps it hidden and held${unmanaged ? ' (no git repository)' : ''}`, async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + await raw(engine, "UPDATE pages SET compiled_truth = compiled_truth || E'\\n\\n## Facets\\n\\n- storage-alt-example: merged here.\\n' WHERE source_id='default' AND slug=$1", [CONCEPT]); + if (unmanaged) { + rmSync(join(root, '.git'), { recursive: true, force: true }); + await raw(engine, "UPDATE sources SET local_path=NULL WHERE id='default'"); + } + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, settle: !unmanaged }); + expect(details.rebuilt).toEqual([]); + expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'stated', kinds: ['curated_sections'] }]); + await stillHeld(engine, id); + expect((await state(engine)).body).toContain('storage-alt-example: merged here.'); + }, { databaseUrl }); + }, 300_000); + test(`${mode}: a failed synthesis leaves it hidden and held`, async () => { await managedBrain(async ({ engine, ctx, root }) => { const id = await heldConcept(engine, ctx, root); From cc6008b1be289a9096d3bbe006c6dc92442cae8c Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 07:57:40 +0000 Subject: [PATCH 15/37] fix: rebuild a hidden concept only when synthesis wrote everything on it, and keep every link column A hidden concept now stays hidden when its title is not the slug title, it has a frontmatter key synthesis does not write, a stored timeline, a file other than .md, or dated link transitions. Incoming links the fresh page takes over keep every column (link_kind, resolution_type, assertion_tense, created_at included), and a census test lists each links and pages column so a new one cannot be dropped silently. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- scripts/page-body-readers-baseline.tsv | 1 + src/core/persistence/concept-rebuild.ts | 54 +++++++++++++++++++------ test/concept-purge-rebuild-9653.test.ts | 54 ++++++++++++++++++++++++- 3 files changed, 95 insertions(+), 14 deletions(-) diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv index 553ce2f4667..7f630c1944a 100644 --- a/scripts/page-body-readers-baseline.tsv +++ b/scripts/page-body-readers-baseline.tsv @@ -725,3 +725,4 @@ src/commands/doctor/checks/atom-body-recheck.ts unchangedBodyAtoms sql INLINE do src/core/guests/promote.ts promoteGuestNote call:serializeMarkdown INLINE assertInlineBody refuses a guest note stored in segments (page_body_segmented) before its body is copied into the owner page src/core/guests/promote.ts promoteGuestNote field INLINE assertInlineBody before the body is read src/core/rust-engine/store-codec.ts guardNullBody field META reads only whether the Rust store sent compiled_truth/timeline as null (a segmented shell, PGLite pages_body_storage_chk), never the body text; a null body becomes the guarded segmented page of rowToPage +src/core/persistence/concept-rebuild.ts STATED_SQL sql INLINE reads only an inline page timeline for emptiness; a segmented page counts as unread and stays hidden diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index 12844c89f20..7c622f7dd1b 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -12,7 +12,7 @@ * repo-less brain gets it unchanged. */ import { randomUUID } from 'node:crypto'; -import type { BrainEngine, LinkBatchInput, PageSnapshot } from '../engine.ts'; +import type { BrainEngine, PageSnapshot } from '../engine.ts'; import type { OperationContext } from '../ops/contract.ts'; import { loadConfig } from '../config.ts'; import { submitPageMutation } from './page-mutations.ts'; @@ -66,6 +66,26 @@ export const REBUILD_STORES: Readonly> = { page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', }; +/** + * Every column of links (test/concept-purge-rebuild-9653.test.ts fails on one missing here). An incoming link the fresh + * page takes over keeps each carried column; to_page_id, and an origin_page_id naming the old row, point at the fresh row. + */ +export const REBUILD_LINK_COLUMNS: Readonly> = { + id: 'regenerated', from_page_id: 'carried', to_page_id: 'carried', link_type: 'carried', context: 'carried', link_source: 'carried', + link_kind: 'carried', origin_page_id: 'carried', origin_field: 'carried', resolution_type: 'carried', created_at: 'carried', assertion_tense: 'carried', +}; +const CARRIED_LINK_COLUMNS = Object.keys(REBUILD_LINK_COLUMNS).filter(column => REBUILD_LINK_COLUMNS[column] === 'carried'); +/** The fresh row at (`$1`, `$2`), with the incoming links `$3` (to_jsonb rows of the old row `$4`) carried onto it. */ +const CARRY_LINKS_SQL = `WITH fresh AS (SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL), + carried AS (INSERT INTO links (${CARRIED_LINK_COLUMNS.join(', ')}) SELECT ${CARRIED_LINK_COLUMNS.map(column => column === 'to_page_id' ? 'fresh.id' + : column === 'origin_page_id' ? 'CASE WHEN r.origin_page_id = $4::int THEN fresh.id ELSE r.origin_page_id END' : `r.${column}`).join(', ')} + FROM fresh, jsonb_populate_recordset(NULL::links, $3::text::jsonb) r ON CONFLICT DO NOTHING RETURNING 1) + SELECT id, (SELECT count(*)::int FROM carried) AS carried FROM fresh`; + +/** Frontmatter keys synthesis and its write path set on a concept (synthesize-concepts.ts, serializeMarkdown, the trust stamp); any other key keeps it hidden. */ +const SYNTHESIS_KEYS: readonly string[] = ['type', 'title', 'trust_tier', 'tier', 'mention_count', 'composite_score', 'synthesis_mode', 'member_hash', + 'synthesized_at', 'synthesized_by', 'visibility', 'unverified_claims']; + const WIDER = 'its current members are all world-readable and the hidden concept was not'; const HELD_SQL = `p.deleted_at IS NOT NULL AND p.type = 'concept' AND coalesce(p.frontmatter->>'synthesized_by', '') LIKE 'synthesize_concepts%' @@ -73,7 +93,11 @@ const HELD_SQL = `p.deleted_at IS NOT NULL AND p.type = 'concept' AND coalesce(p AND NOT EXISTS (SELECT 1 FROM op_checkpoints o WHERE o.op = '${OWED_PURGE_OP}' AND o.fingerprint = p.id::text)`; const DELETED_US = `floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text`; -/** What a person or an agent stated on or about the concept row `$1` (source `$2`, slug `$3`), as REBUILD_STORES kinds. */ +/** + * What on or about the concept row `$1` (source `$2`, slug `$3`) synthesis did not write: REBUILD_STORES kinds for rows a + * person or an agent stated, plus a title other than the slug's, a frontmatter key synthesis does not write, a stored + * timeline, a file other than `.md`, and dated link transitions. + */ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $2 AND (f.entity_slug = $3 OR f.source_markdown_slug = $3) AND NOT ${extractedFromPageSql('f', '$3')}) THEN 'facts' END, CASE WHEN EXISTS (SELECT 1 FROM takes t WHERE t.page_id = $1) THEN 'takes' END, @@ -86,14 +110,21 @@ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM slug_aliases a WHERE a.source_id = $2 AND a.canonical_slug = $3) THEN 'slug_aliases' END, CASE WHEN EXISTS (SELECT 1 FROM core_edit_notices c WHERE c.source_id = $2 AND c.slug = $3) THEN 'core_edit_notices' END, CASE WHEN EXISTS (SELECT 1 FROM write_gate_holds h WHERE h.source_id = $2 AND h.slug = $3) THEN 'write_gate_holds' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.title <> replace(regexp_replace(p.slug, '^.*/', ''), '-', ' ')) THEN 'title' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p, jsonb_each(p.frontmatter) e WHERE p.id = $1 AND e.key <> ALL($6::text[]) AND e.key <> ALL($5::text[]) + AND NOT (e.key = 'tags' AND e.value = '[]'::jsonb)) THEN 'frontmatter' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.body_storage IS DISTINCT FROM 'segmented' AND coalesce(p.timeline, '') <> '') THEN 'timeline' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND ((p.source_path IS NOT NULL AND p.source_path <> p.slug || '.md') + OR p.source_uri IS NOT NULL OR p.withheld_source_path IS NOT NULL)) THEN 'source_path' END, + CASE WHEN EXISTS (SELECT 1 FROM link_transitions t WHERE t.from_page_id = $1 OR t.to_page_id = $1 OR t.origin_page_id = $1) THEN 'link_transitions' END, CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.frontmatter ?| $5::text[]) THEN 'labels' END ], NULL) AS kinds, (SELECT ${boundedBodyPrefixSql('p')} FROM pages p WHERE p.id = $1) AS lead, (SELECT p.body_storage = 'segmented' FROM pages p WHERE p.id = $1) AS segmented`; -/** The kinds of stated rows the concept carries; empty when it carries none. */ +/** What the concept carries that synthesis did not write, as kinds; empty when it carries nothing else. */ export async function statedKinds(engine: Sql, pageId: number, sourceId: string, slug: string): Promise { - const [row] = await engine.executeRaw<{ kinds: string[] | null; lead: string | null; segmented: boolean | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS]); + const [row] = await engine.executeRaw<{ kinds: string[] | null; lead: string | null; segmented: boolean | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS, SYNTHESIS_KEYS]); // A body past the bounded lead is not scanned, so it may hold curated sections and counts as if it did. const unread = row?.segmented === true || (row?.lead ?? '').length >= BOUNDED_PREFIX_BYTES; return [...row?.kinds ?? [], ...unread || preservedConceptSections(row?.lead ?? '').length ? ['curated_sections'] : []]; @@ -151,7 +182,7 @@ export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot * purge), then hard-purges the tombstone with the expiry's own statements (engine purgeDeletedPages, onlyIds). Returns * why it purged nothing, or the tombstone's access and the incoming links the fresh page takes over. */ -async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { +async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { const [held] = await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = $1 AND p.source_id = $2 AND p.slug = $3 AND ${DELETED_US} = $4 AND ${HELD_SQL} FOR UPDATE OF p`, [rebuild.page_id, sourceId, slug, rebuild.deleted_us]); if (!held) return 'The concept is no longer held for a rebuild (a person or sync deleted, restored or purged it), so the rebuild wrote nothing.'; @@ -160,24 +191,21 @@ async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, ON m.slug = r.slug AND m.knowledge_revision::text = r.revision WHERE m.source_id = $1 AND m.deleted_at IS NULL FOR SHARE OF m`, [sourceId, JSON.stringify(rebuild.members)]); if (!rebuild.members.length || live.length !== rebuild.members.length) return 'A member the rebuilt narrative was built from changed or was removed during synthesis, so the rebuild wrote nothing; the next run builds it again.'; const access = await readRebuildAccess(tx, rebuild.page_id); - const incoming = await tx.executeRaw(`SELECT f.slug AS from_slug, $2::text AS to_slug, l.link_type, l.context, l.link_source, - o.slug AS origin_slug, l.origin_field, f.source_id AS from_source_id, $3::text AS to_source_id, o.source_id AS origin_source_id - FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id - WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL AND l.link_source IS DISTINCT FROM 'concept-provenance'`, [rebuild.page_id, slug, sourceId]); + const incoming = (await tx.executeRaw<{ link: unknown }>(`SELECT to_jsonb(l) AS link FROM links l JOIN pages f ON f.id = l.from_page_id + WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL AND l.link_source IS DISTINCT FROM 'concept-provenance'`, [rebuild.page_id])).map(row => row.link); const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts'); if ((await parkUncarriedInPurge(tx, [rebuild.page_id])).length) { return { parked: 'A page written since depends on the concept for its privacy, so the concept is parked until the next purge labels it and the rebuild wrote nothing.' }; } const purged = await tx.purgeDeletedPages(0, { onlyIds: [rebuild.page_id] }); if (purged.count !== 1 || !access) return 'The tombstone is held by another purge rule, so the rebuild wrote nothing and it stays held.'; - return { access, incoming }; + return { access, incoming, oldId: rebuild.page_id }; } /** Unmanaged, after the fresh write in the same transaction: points the incoming links at it and confirms it reads no wider. */ -async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: LinkBatchInput[] }): Promise { - const [fresh] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]); +async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: unknown[]; oldId: number }): Promise { + const [fresh] = await tx.executeRaw<{ id: number }>(CARRY_LINKS_SQL, [sourceId, slug, JSON.stringify(before.incoming), before.oldId]); if (!fresh) throw Object.assign(new Error('The rebuilt concept was not written (the import refused it), so the rebuild wrote nothing and the concept stays held.'), { code: 'revision_conflict' }); - if (before.incoming.length) await tx.addLinksBatch(before.incoming); const widened = rebuildWidens(before.access, await readRebuildAccess(tx, Number(fresh.id))); if (widened) { const error: Error & { code?: string } = new Error(`The rebuilt concept would be readable more widely than the hidden one (${widened}), so the rebuild wrote nothing and the concept stays held.`); diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index 91e4f755b38..442a30afa8f 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -11,7 +11,7 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts'; import { purgeDeletedPagesCoordinated, rebuildNote, selectPurgeCandidates } from '../src/core/persistence/purge-deleted.ts'; import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts'; import type { WriteRequest } from '../src/core/persistence/model.ts'; -import { REBUILD_STORES, __setManagedConceptRebuildForTests } from '../src/core/persistence/concept-rebuild.ts'; +import { REBUILD_LINK_COLUMNS, REBUILD_STORES, __setManagedConceptRebuildForTests } from '../src/core/persistence/concept-rebuild.ts'; import { installFaultHook } from '../src/core/persistence/fault-points.ts'; import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts'; import { proposeRevision } from '../src/core/access/policy.ts'; @@ -250,6 +250,39 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); + test(`${mode}: anything on the page synthesis did not write keeps it hidden and held${unmanaged ? ' (no git repository)' : ''}`, async () => { + const authored: Array<[string, string, unknown[]]> = [ + ['title', "UPDATE pages SET title = 'Storage, renamed by hand' WHERE source_id='default' AND slug=$1", [CONCEPT]], + ['frontmatter', "UPDATE pages SET frontmatter = frontmatter || '{\"aliases\":[\"storage-alt-example\"]}'::jsonb WHERE source_id='default' AND slug=$1", [CONCEPT]], + ['timeline', "UPDATE pages SET timeline = '- 2026-01-01: a curated event' WHERE source_id='default' AND slug=$1", [CONCEPT]], + ['source_path', "UPDATE pages SET source_path = 'concepts/storage-renamed.md' WHERE source_id='default' AND slug=$1", [CONCEPT]], + ]; + for (const [kind, sql, params] of authored) await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + await raw(engine, sql, params); + if (unmanaged) { + rmSync(join(root, '.git'), { recursive: true, force: true }); + await raw(engine, "UPDATE sources SET local_path=NULL WHERE id='default'"); + } + const details = await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged, settle: !unmanaged }); + expect(details.rebuilt).toEqual([]); + expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'stated', kinds: [kind] }]); + await stillHeld(engine, id); + }, { databaseUrl }); + }, 1_500_000); + + if (unmanaged) test('unmanaged: an incoming link keeps every column it had, pointed at the fresh page', async () => { + await managedBrain(async ({ engine, ctx, root }) => { + const id = await heldConcept(engine, ctx, root); + const pick = "SELECT l.link_type, l.context, l.link_source, l.link_kind, l.origin_field, l.resolution_type, l.assertion_tense, l.created_at::text AS created_at, o.slug AS origin FROM links l JOIN pages n ON n.id = l.from_page_id JOIN pages c ON c.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE n.slug = 'notes/storage-ref' AND c.slug = $1"; + await raw(engine, "UPDATE links SET link_kind = 'typed_ner', resolution_type = 'qualified', assertion_tense = 'past' WHERE to_page_id = $1", [id]); + const before = await engine.executeRaw(pick, [CONCEPT]); + expect(before).toHaveLength(1); + expect((await synthesize(engine, root, [1, 2, 3, 4, 5], { text: NEW, unmanaged: true })).rebuilt).toEqual([CONCEPT]); + expect(await engine.executeRaw(pick, [CONCEPT])).toEqual(before); + }, { databaseUrl }); + }, 300_000); + test(`${mode}: a failed synthesis leaves it hidden and held`, async () => { await managedBrain(async ({ engine, ctx, root }) => { const id = await heldConcept(engine, ctx, root); @@ -416,6 +449,25 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); + test('every column of links and of the rewritten page is carried, regenerated or held on by the rebuild', async () => { + const PAGE_COLUMNS: Record = Object.fromEntries([ + ...['title', 'compiled_truth', 'timeline', 'frontmatter', 'source_path', 'source_uri', 'withheld_source_path', 'page_readers', 'folder_rule_ids', + 'body_storage', 'truth_lead', 'timeline_lead'].map(c => [c, 'held'] as const), + ...['id', 'source_id', 'slug', 'type', 'page_kind', 'content_hash', 'emotional_weight', 'created_at', 'updated_at', 'deleted_at', 'effective_date', + 'effective_date_source', 'import_filename', 'salience_touched_at', 'last_retrieved_at', 'links_extracted_at', 'database_only_reason', + 'contextual_retrieval_mode', 'corpus_generation', 'generation', 'search_vector', 'knowledge_revision', 'text_projection_revision', + 'emotional_weight_recomputed_at', 'chunker_version', 'ingested_via', 'ingested_at', 'source_kind', 'embedding_signature', + 'links_attendance_blocked_revision', 'links_attendance_blocked_at', 'revision_write_request_id', 'revision_principal_kind', + 'revision_principal_id', 'trust_tier', 'write_origin', 'body_bytes', 'truth_bytes', 'body_lines', 'body_generation', 'segment_count', + 'segmenter_version', 'body_flags', 'links_extract_failure', 'version_history_gap_at'].map(c => [c, 'regenerated'] as const), + ]); + await managedBrain(async ({ engine }) => { + const columns = async (table: string) => (await engine.executeRaw<{ c: string }>("SELECT column_name AS c FROM information_schema.columns WHERE table_name = $1 AND table_schema = current_schema()", [table])).map(r => r.c).sort(); + expect(await columns('links')).toEqual(Object.keys(REBUILD_LINK_COLUMNS).sort()); + expect(await columns('pages')).toEqual(Object.keys(PAGE_COLUMNS).sort()); + }, { databaseUrl }); + }, 120_000); + test('every store a page purge removes rows from is classified stated or derived', async () => { await managedBrain(async ({ engine, ctx, root }) => { await heldConcept(engine, ctx, root); From 037bca9808fb05fcd0f770c43bd8557e84688b57 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:16:21 +0000 Subject: [PATCH 16/37] fix: keep a hidden concept hidden when it has an agent payload, a person's edge decision, an identity or a guest mark Attached raw_data, a rejected, undone or reverted edge proposal, an entity identity and a guest mark or promotion each keep the concept hidden instead of being deleted by its rebuild. The census test now also lists every table keyed to a page, so a new one has to be classified. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 13 ++++++++++--- test/concept-purge-rebuild-9653.test.ts | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index 7c622f7dd1b..e60e3eac076 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -56,13 +56,13 @@ const DERIVED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-r */ export const REBUILD_STORES: Readonly> = { facts: 'stated', takes: 'stated', timeline_entries: 'stated', page_aliases: 'stated', slug_aliases: 'stated', tags: 'stated', - files: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', + files: 'stated', raw_data: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', pages: 'derived', page_versions: 'derived', content_chunks: 'derived', query_cache: 'derived', take_proposals: 'derived', open_loops: 'derived', slug_rename_history: 'derived', trust_proposals: 'derived', decide_proposals: 'derived', decide_review_queue: 'derived', decide_review_proposals: 'derived', persistence_requests: 'derived', persistence_effects: 'derived', derived_generations: 'derived', derived_generation_items: 'derived', retrieval_event_pages: 'derived', retrieval_event_links: 'derived', retrieval_feedback: 'derived', retrieval_weights: 'derived', 'eval_candidates.retrieved_slugs': 'derived', mention_gazetteer_entries: 'derived', - context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', raw_data: 'derived', + context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', }; @@ -96,7 +96,8 @@ const DELETED_US = `floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::tex /** * What on or about the concept row `$1` (source `$2`, slug `$3`) synthesis did not write: REBUILD_STORES kinds for rows a * person or an agent stated, plus a title other than the slug's, a frontmatter key synthesis does not write, a stored - * timeline, a file other than `.md`, and dated link transitions. + * timeline, a file other than `.md`, dated link transitions, an attached raw_data payload, a person's decision on an + * edge proposal (rejected, undone or reverted), an entity identity, and a guest mark or promotion. */ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $2 AND (f.entity_slug = $3 OR f.source_markdown_slug = $3) AND NOT ${extractedFromPageSql('f', '$3')}) THEN 'facts' END, @@ -117,6 +118,12 @@ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND ((p.source_path IS NOT NULL AND p.source_path <> p.slug || '.md') OR p.source_uri IS NOT NULL OR p.withheld_source_path IS NOT NULL)) THEN 'source_path' END, CASE WHEN EXISTS (SELECT 1 FROM link_transitions t WHERE t.from_page_id = $1 OR t.to_page_id = $1 OR t.origin_page_id = $1) THEN 'link_transitions' END, + CASE WHEN EXISTS (SELECT 1 FROM raw_data r WHERE r.page_id = $1) THEN 'raw_data' END, + CASE WHEN EXISTS (SELECT 1 FROM link_edge_proposals e WHERE $1 IN (e.from_page_id, e.a_to_page_id, e.b_to_page_id, e.ending_to_page_id) + AND e.status IN ('rejected', 'undone', 'reverted_by_user')) THEN 'link_edge_proposals' END, + CASE WHEN EXISTS (SELECT 1 FROM entity_identities i WHERE i.page_id = $1) THEN 'entity_identities' END, + CASE WHEN EXISTS (SELECT 1 FROM guest_marks g WHERE g.page_id = $1) THEN 'guest_marks' END, + CASE WHEN EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = $1) THEN 'guest_promotions' END, CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.frontmatter ?| $5::text[]) THEN 'labels' END ], NULL) AS kinds, diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index 442a30afa8f..33c3e04e19a 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -341,6 +341,11 @@ for (const backend of testBackends()) { ['facts', async engine => raw(engine, "INSERT INTO facts (source_id, fact, source, entity_slug) VALUES ('default', 'A stated fact about storage.', 'mcp:remember', $1)", [CONCEPT])], ['tags', async (engine, _ctx, id) => raw(engine, "INSERT INTO tags (page_id, tag) VALUES ($1, 'hand-tag')", [id])], ['timeline_entries', async (engine, _ctx, id) => raw(engine, "INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', 'a stated event')", [id])], + ['raw_data', async (engine, _ctx, id) => raw(engine, "INSERT INTO raw_data (page_id, source, data) VALUES ($1, 'agent-example', '{\"note\": 1}'::jsonb)", [id])], + ['link_edge_proposals', async (engine, _ctx, id) => raw(engine, "INSERT INTO link_edge_proposals (source_id, from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash, status) SELECT 'default', n.id, $1, n.id, 'works_at', 'evidence-example', 'rejected' FROM pages n WHERE n.slug = 'notes/storage-ref'", [id])], + ['entity_identities', async (engine, _ctx, id) => raw(engine, "INSERT INTO entity_identities (entity_id, source_id, page_id) VALUES ('entity-example', 'default', $1)", [id])], + ['guest_marks', async (engine, _ctx, id) => raw(engine, "INSERT INTO guest_marks (page_id, source_id, slug_at_write, audience_member, group_slug, sender_label, saved_at, writer_kind, writer_id) VALUES ($1, 'default', $2, 'alice-example', 'group-example', 'Alice', now(), 'member', 'alice-example')", [id, CONCEPT])], + ['guest_promotions', async (engine, _ctx, id) => raw(engine, "INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id) VALUES ($1, 'default', 'notes/promoted-example', 'member', 'alice-example')", [id])], ]; for (const [kind, add] of stated) await managedBrain(async ({ engine, ctx, root }) => { const id = await heldConcept(engine, ctx, root); @@ -449,7 +454,7 @@ for (const backend of testBackends()) { }, { databaseUrl }); }, 300_000); - test('every column of links and of the rewritten page is carried, regenerated or held on by the rebuild', async () => { + test('every column of links and of the rewritten page, and every table keyed to a page, is carried, regenerated or held on by the rebuild', async () => { const PAGE_COLUMNS: Record = Object.fromEntries([ ...['title', 'compiled_truth', 'timeline', 'frontmatter', 'source_path', 'source_uri', 'withheld_source_path', 'page_readers', 'folder_rule_ids', 'body_storage', 'truth_lead', 'timeline_lead'].map(c => [c, 'held'] as const), @@ -461,10 +466,19 @@ for (const backend of testBackends()) { 'revision_principal_id', 'trust_tier', 'write_origin', 'body_bytes', 'truth_bytes', 'body_lines', 'body_generation', 'segment_count', 'segmenter_version', 'body_flags', 'links_extract_failure', 'version_history_gap_at'].map(c => [c, 'regenerated'] as const), ]); + const PAGE_TABLES: Record = Object.fromEntries([ + ...['files', 'link_edge_proposals', 'link_transitions', 'links', 'page_label_guards', 'raw_data', 'tags', 'takes', 'timeline_entries', + 'entity_identities', 'guest_marks', 'guest_promotions'].map(t => [t, 'held'] as const), + ...['chronicle_page_state', 'content_chunks', 'extract_atoms_page_state', 'link_relationships', 'page_body_manifest', 'page_body_stagings', + 'page_derivation_spend', 'page_embedding_budget', 'page_extraction_state', 'page_facts_reconcile', 'page_mention_state', + 'page_segment_derivations', 'page_versions', 'page_view_digests', 'secret_store_occurrence', 'synthesis_evidence', 'wanted_links'].map(t => [t, 'regenerated'] as const), + ]); await managedBrain(async ({ engine }) => { const columns = async (table: string) => (await engine.executeRaw<{ c: string }>("SELECT column_name AS c FROM information_schema.columns WHERE table_name = $1 AND table_schema = current_schema()", [table])).map(r => r.c).sort(); expect(await columns('links')).toEqual(Object.keys(REBUILD_LINK_COLUMNS).sort()); expect(await columns('pages')).toEqual(Object.keys(PAGE_COLUMNS).sort()); + const tables = (await engine.executeRaw<{ t: string }>("SELECT DISTINCT conrelid::regclass::text AS t FROM pg_constraint WHERE confrelid = 'pages'::regclass AND contype = 'f'")).map(r => r.t).sort(); + expect(tables).toEqual(Object.keys(PAGE_TABLES).sort()); }, { databaseUrl }); }, 120_000); From 0cca18ba1a93c8288bfe955667e5c78b19e564be Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:20:59 +0000 Subject: [PATCH 17/37] Index page titles of any length, so long-title brains upgrade and save (#9779) The exact-title lookup index was a btree on (source_id, lower(title)); a btree entry must fit in 2,704 bytes, so a longer title stopped the v240 upgrade and was refused on save. v240 and schema.sql now build a hash index on lower(title), and v326 builds it online on brains that have the btree, then drops the btree online. Transcript imports cap a new page's title at 200 characters. Reported by @mweber82. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../transcript_title_cap_9779.md | 4 + changelog.d/fix-long-title-index.md | 10 ++ src/core/pglite-schema.generated.ts | 2 +- src/core/schema-embedded.generated.ts | 5 +- .../schema-migrations/latest.generated.ts | 2 +- .../schema-migrations/registry.generated.ts | 2 + .../v240-pages-name-lookup-indexes.ts | 17 ++-- .../v326-pages-title-lower-hash-index.ts | 37 ++++++++ src/core/transcripts/ingest.ts | 2 +- src/core/transcripts/render.ts | 16 +++- src/schema.sql | 5 +- test/e2e/entity-names-parity-postgres.test.ts | 2 +- .../long-title-index-9779-postgres.test.ts | 25 +++++ test/e2e/whois-postgres.test.ts | 2 +- test/entity-names-parity.test.ts | 2 +- .../catalog/pglite-engine-init-default.json | 2 +- .../pglite-engine-init-fts-portuguese.json | 2 +- .../catalog/pglite-engine-init-high-dims.json | 2 +- .../catalog/pglite-schema-blob-default.json | 2 +- .../pglite-schema-blob-fts-portuguese.json | 2 +- .../catalog/pglite-schema-blob-high-dims.json | 2 +- .../catalog/postgres-db-initschema.json | 2 +- .../catalog/postgres-engine-init-default.json | 2 +- .../postgres-engine-init-fts-portuguese.json | 2 +- .../postgres-engine-init-high-dims.json | 2 +- test/fixtures/goldens/migrations/records.json | 43 ++++++++- .../catalog-after-boot.json | 2 +- test/helpers/long-title-index.ts | 95 +++++++++++++++++++ .../page-timeline-tsvector-bound.test.ts | 4 +- test/long-title-index-9779.test.ts | 57 +++++++++++ test/whois.test.ts | 2 +- 31 files changed, 320 insertions(+), 36 deletions(-) create mode 100644 behavior-changes.d/transcript_title_cap_9779.md create mode 100644 changelog.d/fix-long-title-index.md create mode 100644 src/core/schema-migrations/v326-pages-title-lower-hash-index.ts create mode 100644 test/e2e/long-title-index-9779-postgres.test.ts create mode 100644 test/helpers/long-title-index.ts create mode 100644 test/long-title-index-9779.test.ts diff --git a/behavior-changes.d/transcript_title_cap_9779.md b/behavior-changes.d/transcript_title_cap_9779.md new file mode 100644 index 00000000000..199b3dc01da --- /dev/null +++ b/behavior-changes.d/transcript_title_cap_9779.md @@ -0,0 +1,4 @@ +--- +kind: fix +--- +A transcript import now gives a new page a title of at most 200 characters, cut with an ellipsis, instead of the whole title the harness reported, which for some harnesses is the session's opening text and could run to over 100 KB. Sessions already imported keep their titles, and the full text stays in the page body. Separately, page titles of any length can now be saved and upgraded: the exact-title lookup index is a hash index, so a brain holding titles over about 2,700 bytes no longer stops its upgrade and no longer refuses those page saves (#9779). diff --git a/changelog.d/fix-long-title-index.md b/changelog.d/fix-long-title-index.md new file mode 100644 index 00000000000..d3f380cc404 --- /dev/null +++ b/changelog.d/fix-long-title-index.md @@ -0,0 +1,10 @@ +--- +important: data-loss +--- +**Brains with page titles longer than about 2,700 bytes upgrade again, and pages with long titles save instead of being refused (#9779).** + +### Fixed +- The index behind exact-title lookups (`entity`, `whois`, context cards, search's alias check) was a btree on the lowercased title, and a btree entry must fit in 2,704 bytes. Upgrading a brain that already held a longer title stopped with "index row requires N bytes, maximum size is 8191", and on an upgraded brain saving such a page failed with `storage_error` ("index row size N exceeds btree version 4 maximum 2704"). The index is now a hash index on the lowercased title, which indexes a title of any length; the lookups are unchanged and still use it. Brains that already built the old index get the new one built online, then the old one dropped online, on the next upgrade. Reported by @mweber82. +- Transcript imports cap the title of a new page at 200 characters, ending in an ellipsis when cut. Some harnesses report a session's opening text as its title, which ran to over 100 KB. Pages already imported keep their titles. + + diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts index 0f287eec363..f83e59f2166 100644 --- a/src/core/pglite-schema.generated.ts +++ b/src/core/pglite-schema.generated.ts @@ -142,7 +142,7 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); -CREATE INDEX IF NOT EXISTS idx_pages_source_title_lower ON pages (source_id, lower(title)); +CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id); CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idx diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts index 8f18b8e7fe5..0428d0f46d2 100644 --- a/src/core/schema-embedded.generated.ts +++ b/src/core/schema-embedded.generated.ts @@ -285,8 +285,9 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); --- v240: the entity name lookups (exact title, alias title check, slug suffix) as index scans. -CREATE INDEX IF NOT EXISTS idx_pages_source_title_lower ON pages (source_id, lower(title)); +-- v240/v326: the entity name lookups (exact title, alias title check, slug suffix) as index scans. Hash, not btree: +-- a btree entry must fit in 2,704 bytes, and a page title has no length limit (#9779). +CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); -- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first. CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC); diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts index 5c010bca72f..ef03a230259 100644 --- a/src/core/schema-migrations/latest.generated.ts +++ b/src/core/schema-migrations/latest.generated.ts @@ -4,4 +4,4 @@ // The highest schema migration version (migrate.ts LATEST_VERSION), importable without // loading the migrations themselves. -export const LATEST_SCHEMA_VERSION = 325; +export const LATEST_SCHEMA_VERSION = 326; diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts index abd20378136..d8e3fa15f5f 100644 --- a/src/core/schema-migrations/registry.generated.ts +++ b/src/core/schema-migrations/registry.generated.ts @@ -326,6 +326,7 @@ import { v322 } from './v322-owner-only-marks.ts'; import { v323 } from './v323-token-read-shared.ts'; import { v324 } from './v324-secret-store.ts'; import { v325 } from './v325-entity-identity-reviews.ts'; +import { v326 } from './v326-pages-title-lower-hash-index.ts'; // Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the // runner sorts by version before applying. @@ -650,4 +651,5 @@ export const MIGRATIONS: Migration[] = [ v323, v324, v325, + v326, ]; diff --git a/src/core/schema-migrations/v240-pages-name-lookup-indexes.ts b/src/core/schema-migrations/v240-pages-name-lookup-indexes.ts index d0ec92c9cb0..6316803eb8b 100644 --- a/src/core/schema-migrations/v240-pages-name-lookup-indexes.ts +++ b/src/core/schema-migrations/v240-pages-name-lookup-indexes.ts @@ -9,15 +9,20 @@ import { buildIndexOnline, migrationNotice } from './helpers.ts'; * the card's exact-title / exact-slug / slug-suffix arm * (`lower(title) = $2 OR slug = ANY($3) OR slug LIKE '%/'`, * verbs/entity-card.ts), about 50 ms each at 55,000 pages on PGLite. With - * `(source_id, lower(title))` and a trigram index on `slug` (pg_trgm already - * backs idx_pages_trgm) every arm is an index scan, combined by a BitmapOr, - * and both reads take about 1 ms. The predicates are unchanged, so the same - * rows come back. Postgres builds each index CONCURRENTLY, one statement per + * a hash index on `lower(title)` and a trigram index on `slug` (pg_trgm + * already backs idx_pages_trgm) every arm is an index scan, combined by a + * BitmapOr, and both reads take about 1 ms. The predicates are unchanged, so + * the same rows come back. The title index is a hash index (#9779): a btree + * entry must fit in 2,704 bytes, so a btree on `(source_id, lower(title))` + * refused every page with a longer title and stopped this migration on a + * brain that already held one; a hash index stores only the 4-byte hash, so + * a title of any length is indexed. v326 replaces the btree on brains that + * built it here before. Postgres builds each index CONCURRENTLY, one statement per * call, after dropping an INVALID leftover; PGLite builds them inline. */ export const PAGES_NAME_LOOKUP_INDEXES = [ - { name: 'idx_pages_source_title_lower', table: 'pages', - sql: 'CREATE INDEX IF NOT EXISTS idx_pages_source_title_lower ON pages (source_id, lower(title))' }, + { name: 'idx_pages_title_lower_hash', table: 'pages', + sql: 'CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title))' }, { name: 'idx_pages_slug_trgm', table: 'pages', sql: 'CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops)' }, ] as const; diff --git a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts new file mode 100644 index 00000000000..d839fa77c73 --- /dev/null +++ b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts @@ -0,0 +1,37 @@ +import type { Migration } from './types.ts'; +import { buildIndexOnline, migrationNotice, runMigrationStatement } from './helpers.ts'; +import { PAGES_NAME_LOOKUP_INDEXES } from './v240-pages-name-lookup-indexes.ts'; + +// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md +// ("Canonical schema sources") for when schema.sql or a TS fragment also changes. +// +// #9779: v240 first indexed the exact-title lookups with a btree on +// (source_id, lower(title)). A btree entry must fit in 2,704 bytes, so on a +// brain past v240 a page whose title is longer could not be saved, and the +// index could not be built on a brain that already held one. v240 and +// schema.sql now build a hash index on lower(title), which stores only the +// title's hash; the lookups compare lower(title) exactly as before, so they +// use it unchanged. This replaces the btree on brains that already built it: +// the hash index is built first (CONCURRENTLY on Postgres), so the lookups +// stay indexed throughout, then the btree is dropped (CONCURRENTLY on +// Postgres). Each step is a no-op once done, so a rerun after an interruption +// picks up where it stopped. An older gbrain runs against the new index +// unchanged, since its queries are the same. +export const LEGACY_TITLE_BTREE_INDEX = 'idx_pages_source_title_lower'; + +export const v326: Migration = { + version: 326, + name: 'pages_title_lower_hash_index', + idempotent: true, + transaction: false, + sql: '', + handler: async engine => { + const index = PAGES_NAME_LOOKUP_INDEXES[0]; + if (await buildIndexOnline(engine, 326, index, { notice: migrationNotice }) === 'building') { + throw new Error(`Index ${index.name} is still being built by another session; rerun: gbrain apply-migrations --yes`); + } + await runMigrationStatement(engine, 326, engine.kind === 'postgres' + ? `DROP INDEX CONCURRENTLY IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}` + : `DROP INDEX IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}`); + }, +}; diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts index cbbfd47dcc0..0d16cba21f5 100644 --- a/src/core/transcripts/ingest.ts +++ b/src/core/transcripts/ingest.ts @@ -348,7 +348,7 @@ export async function runTranscriptsIngest( const stored = opts.dryRun ? { layout: 'single' as const, partTargetBytes: pageCeiling, existingSlug: null } : await storedTranscriptLayout(engine, opts.sourceId ?? 'default', session.meta, pageCeiling); - const rendered = renderSessionParts(redacted, { sourcePath: path, layout: stored.layout, partTargetBytes: stored.partTargetBytes }); + const rendered = renderSessionParts(redacted, { sourcePath: path, layout: stored.layout, partTargetBytes: stored.partTargetBytes, existing: stored.existingSlug !== null }); if (stored.existingSlug) adoptExistingBaseSlug(rendered, stored.existingSlug); outcome.baseSlug = rendered.baseSlug; outcome.parts = rendered.parts.length; diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts index 570c55e4bfa..48f400dd1e5 100644 --- a/src/core/transcripts/render.ts +++ b/src/core/transcripts/render.ts @@ -83,6 +83,16 @@ export const OVERLAP_MESSAGES = 2; /** Adapter-schema version stamped into transcript_import frontmatter. */ export const TRANSCRIPT_IMPORT_VERSION = 1; +/** + * #9779: the longest title a transcript page gets, in characters. Some + * harnesses report a session's opening text as its title, which can run to + * 100 KB; the full text is already in the page body. A longer title is cut at + * a codepoint boundary and ends in an ellipsis, so a cut title reads as cut. + * A session whose page already exists (`existing`) keeps its title as given, + * so a re-import never rewrites a page only to shorten its title. + */ +export const TRANSCRIPT_TITLE_MAX_CHARS = 200; + // ── Redaction ──────────────────────────────────────────────────────────────── /** Default user-pattern file — the same convention skillpack harvest uses. */ @@ -361,7 +371,7 @@ export function transcriptPartId(meta: Pick TRANSCRIPT_TITLE_MAX_CHARS && !opts.existing ? cps.slice(0, TRANSCRIPT_TITLE_MAX_CHARS - 1).join('').trimEnd() + '…' : cps.join('')) + || `${meta.harness} session ${meta.sessionId.slice(0, 12)}`; const parts: RenderedPart[] = groups.map((group, idx) => { const part = idx + 1; diff --git a/src/schema.sql b/src/schema.sql index 8a052f002ed..498dd0dd878 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -281,8 +281,9 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); --- v240: the entity name lookups (exact title, alias title check, slug suffix) as index scans. -CREATE INDEX IF NOT EXISTS idx_pages_source_title_lower ON pages (source_id, lower(title)); +-- v240/v326: the entity name lookups (exact title, alias title check, slug suffix) as index scans. Hash, not btree: +-- a btree entry must fit in 2,704 bytes, and a page title has no length limit (#9779). +CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); -- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first. CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC); diff --git a/test/e2e/entity-names-parity-postgres.test.ts b/test/e2e/entity-names-parity-postgres.test.ts index b6cc3c74a22..64b0a3baa36 100644 --- a/test/e2e/entity-names-parity-postgres.test.ts +++ b/test/e2e/entity-names-parity-postgres.test.ts @@ -52,7 +52,7 @@ import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts'; expect(plans.some(p => p.sql.startsWith('SELECT slug, source_id, title'))).toBe(true); expect(plans.some(p => p.sql.startsWith('WITH a AS MATERIALIZED'))).toBe(true); for (const p of plans) { - const wanted = p.sql.startsWith('WITH a') ? ['idx_pages_source_title_lower'] : ['idx_pages_source_title_lower', 'idx_pages_slug_trgm']; + const wanted = p.sql.startsWith('WITH a') ? ['idx_pages_title_lower_hash'] : ['idx_pages_title_lower_hash', 'idx_pages_slug_trgm']; expect({ sql: p.sql, seqScan: /Seq Scan on pages\b/.test(p.plan), indexes: wanted.filter(i => p.plan.includes(i)) }) .toEqual({ sql: p.sql, seqScan: false, indexes: wanted }); } diff --git a/test/e2e/long-title-index-9779-postgres.test.ts b/test/e2e/long-title-index-9779-postgres.test.ts new file mode 100644 index 00000000000..02ad007504d --- /dev/null +++ b/test/e2e/long-title-index-9779-postgres.test.ts @@ -0,0 +1,25 @@ +/** + * #9779 on real Postgres: the twin of test/long-title-index-9779.test.ts. The + * v326 replacement builds and drops CONCURRENTLY here, so this is the arm that + * proves the online path. + * + * Gated by DATABASE_URL — skips gracefully without real Postgres. + */ +import { afterAll, beforeEach, describe, test } from 'bun:test'; +import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts'; +import { expectReplacementPastV240, expectUpgradeFromBeforeV240 } from '../helpers/long-title-index.ts'; + +const describePg = hasDatabase() ? describe : describe.skip; + +describePg('long page titles (#9779, Postgres)', () => { + beforeEach(async () => { await setupDB(); }, 240_000); + afterAll(async () => { await teardownDB(); }); + + test('a brain before v240 holding 3,000-byte and 100 KB titles upgrades, and the pages are found by title through the index', async () => { + await expectUpgradeFromBeforeV240(getEngine()); + }, 240_000); + + test('a brain with the old title btree gets the hash index, then saves a 3,000-byte title; a rerun changes nothing', async () => { + await expectReplacementPastV240(getEngine()); + }, 240_000); +}); diff --git a/test/e2e/whois-postgres.test.ts b/test/e2e/whois-postgres.test.ts index fa39fa0c470..e332ce9d85e 100644 --- a/test/e2e/whois-postgres.test.ts +++ b/test/e2e/whois-postgres.test.ts @@ -76,7 +76,7 @@ describePg('whois on real Postgres (GBRA-156)', () => { test('every probe is served by an index: no sequential scan of pages or page_aliases', async () => { const plan = await whoisCandidatePlan(getEngine()); expect(plan).not.toMatch(/Seq Scan on (pages|page_aliases)\b/); - for (const index of ['idx_pages_source_title_lower', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index); + for (const index of ['idx_pages_title_lower_hash', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index); expect(plan).toMatch(/(on|using) page_aliases_\w+/); }); }); diff --git a/test/entity-names-parity.test.ts b/test/entity-names-parity.test.ts index 2a291619735..fdd47159ef8 100644 --- a/test/entity-names-parity.test.ts +++ b/test/entity-names-parity.test.ts @@ -124,7 +124,7 @@ describe('entity names[] lookups are index scans (v240)', () => { expect(plans.some(p => p.sql.startsWith('SELECT slug, source_id, title'))).toBe(true); expect(plans.some(p => p.sql.startsWith('WITH a AS MATERIALIZED'))).toBe(true); for (const p of plans) { - const wanted = p.sql.startsWith('WITH a') ? ['idx_pages_source_title_lower'] : ['idx_pages_source_title_lower', 'idx_pages_slug_trgm']; + const wanted = p.sql.startsWith('WITH a') ? ['idx_pages_title_lower_hash'] : ['idx_pages_title_lower_hash', 'idx_pages_slug_trgm']; expect({ sql: p.sql, seqScan: /Seq Scan on pages\b/.test(p.plan), indexes: wanted.filter(i => p.plan.includes(i)) }) .toEqual({ sql: p.sql, seqScan: false, indexes: wanted }); } diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json index 232dd136f52..ba82a3b52a2 100644 --- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json +++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json @@ -1512,8 +1512,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json index 94fbfa806a8..65c6c0fad4e 100644 --- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json +++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json @@ -1512,8 +1512,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json index 01952bce4ea..4731aae2ec3 100644 --- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json +++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json @@ -1510,8 +1510,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json index 0fac98492d0..6c80ccb694f 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json @@ -968,7 +968,7 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json index 91c0a548485..1dcd0f912d7 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json @@ -968,7 +968,7 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json index 7f8a79ca8e3..c82e73cc2a1 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json @@ -967,7 +967,7 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json index 889aee2ca02..31935f939eb 100644 --- a/test/fixtures/goldens/catalog/postgres-db-initschema.json +++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json @@ -999,7 +999,7 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json index 6f3affa912c..d7ffdc1de1d 100644 --- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json +++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json @@ -1515,8 +1515,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json index b834231b76c..8be5c07123f 100644 --- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json +++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json @@ -1515,8 +1515,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json index e46a0b28e64..f2ded9cdda1 100644 --- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json +++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json @@ -1513,8 +1513,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json index f8a9cd6091c..d3d41e69edb 100644 --- a/test/fixtures/goldens/migrations/records.json +++ b/test/fixtures/goldens/migrations/records.json @@ -1,6 +1,6 @@ { "golden": { - "count": 320, + "count": 321, "gaps": [ 17, 18, @@ -27,12 +27,13 @@ "INGEST_LOG_MARKED_INDEX": "1099f19af7873878974239a9a6f1a627827221eebd75aea01896246e0809e91c", "INGEST_LOG_UNMARKED_INDEX": "c94e6b009f830527d2f1d6af1683bee94189474e8e67aa4c60165ab4abbd8726", "ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35", + "LEGACY_TITLE_BTREE_INDEX": "e686c5cb1a0f1773e0f925e35f477f20f7709e745b0e0e41092c4301bd1b65ea", "LINKS_SUPERSEDES_INDEX": "a1353995111ef65c1347f295081cf8336dd5da955db7e0e330558d34fd21a4c6", "LINK_TRANSITIONS_IDENTITY_INDEX": "2d5e1c6cc9cf17721591e55a364017be841c85022d300e8dbc3e4109353ebf96", "LINK_TRANSITIONS_IDENTITY_NEXT_INDEX": "d83de92fbee21a623b16f8ba4cfb35d4f51478717265323962920133ea029139", "OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX": "e9b472d9db37733e908ea40512ad3f9520d7a6729ce207b0d279d43d3beb5b2f", "PAGES_FOLDER_RULE_IDS_INDEX": "f0929fed2e69d1045a1e3a6e8b4267e4323d658c6305e5ae1f568fc71195f684", - "PAGES_NAME_LOOKUP_INDEXES": "1ca830342164b5606e96cf0090645364f9145d36178d90f166230189fe8d2705", + "PAGES_NAME_LOOKUP_INDEXES": "6095ac01105dc3f441ba85d6a3f8fd4fdf5b224b963e38fb1de9bfd98edb2866", "PAGES_PAGE_READERS_INDEX": "01a92fc19f866e0791bde647e7220a4666561b94888dccaa1643276c384ba057", "PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a", "PAGES_SEGMENTED_BODY_BYTES_INDEX": "c904a4f68cf190cce6bc68c03219c7b62d05b77eeb557db946a4f58a4f965e57", @@ -106,7 +107,7 @@ "widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6", "withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59" }, - "latest": 325, + "latest": 326, "records": [ { "handler": { @@ -5307,6 +5308,39 @@ "transaction": "absent", "verify": "absent", "version": 325 + }, + { + "handler": { + "form": "arrow", + "helpers": [ + "LEGACY_TITLE_BTREE_INDEX", + "PAGES_NAME_LOOKUP_INDEXES", + "PLANNER_REPAIR_TABLES", + "analyzeAfterIndexBuild", + "analyzeDeferred", + "analyzeYieldingToVacuum", + "buildIndexOnline", + "dropInvalidConcurrentIndex", + "lockTableForAnalyze", + "migrationNotice", + "migrationStatementTimeoutMs", + "quietMigrationNotices", + "runMigrationStatement", + "tableRows", + "withSchemaLockTimeout" + ], + "sha256": "b9ebefed56c10ccb9ebdbfe62f3ef04603f30af48f4c69709fcf936afe02f2db" + }, + "idempotent": true, + "name": "pages_title_lower_hash_index", + "sql": { + "length": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "sqlFor": "absent", + "transaction": false, + "verify": "absent", + "version": 326 } ], "versions": [ @@ -5629,7 +5663,8 @@ 322, 323, 324, - 325 + 325, + 326 ] }, "normalizer": "migrations-record-v1" diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json index 5e16b5956ff..cd52ecde71d 100644 --- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json +++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json @@ -1512,8 +1512,8 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))", "idx_pages_source_type": "CREATE INDEX idx_pages_source_type ON public.pages USING btree (source_id, type) WHERE (deleted_at IS NULL)", + "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/helpers/long-title-index.ts b/test/helpers/long-title-index.ts new file mode 100644 index 00000000000..09860ce7067 --- /dev/null +++ b/test/helpers/long-title-index.ts @@ -0,0 +1,95 @@ +/** + * #9779: the scenarios behind test/long-title-index-9779.test.ts (PGLite) and + * test/e2e/long-title-index-9779-postgres.test.ts (Postgres). A btree entry + * must fit in 2,704 bytes, so the old title index refused long titles; the + * titles here are incompressible (TOAST compression would shrink repetitive + * text under the limit and hide the bug). + */ +import { expect } from 'bun:test'; +import type { BrainEngine } from '../../src/core/engine.ts'; +import { exactIdentityStatement } from '../../src/core/engine-sql/exact-identity.ts'; +import { PAGES_NAME_LOOKUP_INDEXES } from '../../src/core/schema-migrations/v240-pages-name-lookup-indexes.ts'; +import { LEGACY_TITLE_BTREE_INDEX, v326 } from '../../src/core/schema-migrations/v326-pages-title-lower-hash-index.ts'; +import { LATEST_SCHEMA_VERSION } from '../../src/core/schema-migrations/latest.generated.ts'; + +export const TITLE_INDEX = PAGES_NAME_LOOKUP_INDEXES[0].name; +const LEGACY_BTREE_SQL = `CREATE INDEX ${LEGACY_TITLE_BTREE_INDEX} ON pages (source_id, lower(title))`; + +/** `bytes` ASCII characters a compressor cannot shrink much (a fixed LCG, so runs are repeatable). */ +export function incompressibleTitle(bytes: number, seed: number): string { + const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '; + let x = seed >>> 0; + let s = 'Session '; + while (s.length < bytes) { + x = (Math.imul(x, 1664525) + 1013904223) >>> 0; + s += alphabet[x % alphabet.length]; + } + return s.slice(0, bytes); +} + +async function indexDef(engine: BrainEngine, name: string): Promise { + const [row] = await engine.executeRaw<{ def: string | null }>('SELECT pg_get_indexdef(to_regclass($1)) AS def', [name]); + return row?.def ?? null; +} + +export async function expectReplacedIndexes(engine: BrainEngine): Promise { + expect(await indexDef(engine, TITLE_INDEX)).toContain('USING hash (lower(title))'); + expect(await indexDef(engine, LEGACY_TITLE_BTREE_INDEX)).toBeNull(); +} + +/** The exact-title lookups (whois's candidate read and the plain `lower(title) = key` predicate) find the page by its long title. */ +export async function expectFoundByTitle(engine: BrainEngine, slug: string, title: string): Promise { + const { text, params } = exactIdentityStatement({ + probes: { titleKeys: [title.toLowerCase()], titleRaw: title, basenames: [], aliasKeys: [], emails: [] }, + sourceIds: ['default'], types: { types: ['person'], per_source: [] }, limit: 10, + }); + expect((await engine.executeRaw<{ slug: string }>(text, params)).map(r => r.slug)).toEqual([slug]); + expect((await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE lower(title) = lower($1)', [title])).map(r => r.slug)).toEqual([slug]); +} + +/** The lookup predicate plans an index scan on the hash index once the table is big enough that a scan would cost more. */ +export async function expectTitleLookupIndexed(engine: BrainEngine, title: string): Promise { + await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title) SELECT 'default', 'notes/filler-' || g, 'note', 'Filler ' || g + FROM generate_series(1, 3000) g ON CONFLICT DO NOTHING`); + await engine.executeRaw('ANALYZE pages'); + const plan = (await engine.executeRaw>('EXPLAIN SELECT slug FROM pages WHERE lower(title) = lower($1)', [title])) + .map(r => Object.values(r)[0]).join('\n'); + expect(plan).toContain(TITLE_INDEX); + expect(plan).not.toMatch(/Seq Scan on pages\b/); +} + +/** + * A brain at v239 holding pages with a 3,000-byte and a 100 KB title: neither + * the v240 index nor its btree exists yet. Every later migration runs again. + */ +export async function expectUpgradeFromBeforeV240(engine: BrainEngine): Promise { + await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX}`); + await engine.executeRaw(`DROP INDEX IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}`); + const short = incompressibleTitle(3_000, 1); + const long = incompressibleTitle(100_000, 2); + await engine.putPage('people/long-title-3k', { type: 'person', title: short, compiled_truth: 'Body.' }); + await engine.putPage('people/long-title-100k', { type: 'person', title: long, compiled_truth: 'Body.' }); + await engine.setConfig('version', '239'); + await engine.initSchema(); + expect(await engine.getConfig('version')).toBe(String(LATEST_SCHEMA_VERSION)); + await expectReplacedIndexes(engine); + await expectFoundByTitle(engine, 'people/long-title-3k', short); + await expectFoundByTitle(engine, 'people/long-title-100k', long); + await expectTitleLookupIndexed(engine, long); +} + +/** A brain past v240 that built the old btree: v326 replaces it, a long title then saves, and a rerun changes nothing. */ +export async function expectReplacementPastV240(engine: BrainEngine): Promise { + await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX}`); + await engine.executeRaw(LEGACY_BTREE_SQL); + await engine.putPage('people/short-title', { type: 'person', title: 'Alice Example', compiled_truth: 'Body.' }); + await engine.setConfig('version', String(v326.version - 1)); + await engine.initSchema(); + await expectReplacedIndexes(engine); + const title = incompressibleTitle(3_000, 3); + await engine.putPage('people/saved-long-title', { type: 'person', title, compiled_truth: 'Body.' }); + await expectFoundByTitle(engine, 'people/saved-long-title', title); + await expectFoundByTitle(engine, 'people/short-title', 'alice EXAMPLE'); + await v326.handler!(engine); + await expectReplacedIndexes(engine); +} diff --git a/test/large-pages/page-timeline-tsvector-bound.test.ts b/test/large-pages/page-timeline-tsvector-bound.test.ts index 4b72c581ac5..b2aecab3b53 100644 --- a/test/large-pages/page-timeline-tsvector-bound.test.ts +++ b/test/large-pages/page-timeline-tsvector-bound.test.ts @@ -57,8 +57,8 @@ describe('page timeline tsvector bound (PGLite)', () => { }, 60_000); test('worst title + densest timeline + densest entries stay under the lexeme cap', async () => { - // The title btree (idx_pages_source_title_lower, 2,704-byte rows) caps a - // title near 2.7 KB; 200 CJK pairs are 2,400 bytes of the densest text. + // A long title of the densest text: 200 CJK pairs are 2,400 bytes. No index + // caps a title since #9779; transcript imports cap theirs at 200 characters. const title = hyphenPairs(0x4e00, 200); const timeline = hyphenPairs(0x20000, Math.ceil(PAGE_TIMELINE_FTS_MAX_CHARS / 10) + 500, 4); const page = await engine.putPage('large/worst', { type: 'note', title, compiled_truth: 'Body.', timeline: 'seed' }); diff --git a/test/long-title-index-9779.test.ts b/test/long-title-index-9779.test.ts new file mode 100644 index 00000000000..16539c7962d --- /dev/null +++ b/test/long-title-index-9779.test.ts @@ -0,0 +1,57 @@ +/** + * #9779 on PGLite: page titles of any length are indexed, saved and migrated, + * and transcript imports cap the titles they make. The Postgres twin is + * test/e2e/long-title-index-9779-postgres.test.ts. + */ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { parseMarkdown } from '../src/core/markdown.ts'; +import { renderSessionParts, TRANSCRIPT_TITLE_MAX_CHARS } from '../src/core/transcripts/render.ts'; +import type { RedactedSession } from '../src/core/transcripts/render.ts'; +import { expectReplacementPastV240, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; + +let engine: PGLiteEngine; + +describe('long page titles (#9779, PGLite)', () => { + beforeEach(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + }, 120_000); + afterEach(async () => { await engine.disconnect(); }, 60_000); + + test('a brain before v240 holding 3,000-byte and 100 KB titles upgrades, and the pages are found by title through the index', async () => { + await expectUpgradeFromBeforeV240(engine); + }, 120_000); + + test('a brain with the old title btree gets the hash index, then saves a 3,000-byte title; a rerun changes nothing', async () => { + await expectReplacementPastV240(engine); + }, 120_000); +}); + +describe('transcript titles (#9779)', () => { + const session = (title: string): RedactedSession => ({ + session: { + meta: { harness: 'claude-code', sessionId: 'session-alice-example-0001', title, startedAt: '2026-01-02T03:04:05Z' }, + messages: [{ role: 'user', timestamp: '2026-01-02T03:04:05Z', text: 'Hello.' }], + }, + imperativesFlagged: 0, + redactionCount: 0, + } as unknown as RedactedSession); + const titleOf = (opts: { existing?: boolean }, title: string) => + parseMarkdown(renderSessionParts(session(title), { sourcePath: '', ...opts }).parts[0]!.content).title; + + test('a new page gets at most 200 characters, cut at a codepoint and ending in an ellipsis', () => { + const long = '😀' + incompressibleTitle(5_000, 4).replace(/ /g, 'x'); + const title = titleOf({}, long); + expect([...title].length).toBe(TRANSCRIPT_TITLE_MAX_CHARS); + expect(title.endsWith('…')).toBe(true); + expect(long.startsWith(title.slice(0, -1))).toBe(true); + expect(titleOf({}, 'Short session title')).toBe('Short session title'); + }); + + test('a session whose page already exists keeps its title as given', () => { + const long = incompressibleTitle(5_000, 5).replace(/ /g, 'x'); + expect(titleOf({ existing: true }, long)).toBe(long); + }); +}); diff --git a/test/whois.test.ts b/test/whois.test.ts index 44a4f0cfaa8..14212687c9b 100644 --- a/test/whois.test.ts +++ b/test/whois.test.ts @@ -146,7 +146,7 @@ describe('whois candidate read', () => { test('every probe is served by an index: no sequential scan of pages or page_aliases', async () => { const plan = await whoisCandidatePlan(engine); expect(plan).not.toMatch(/Seq Scan on (pages|page_aliases)\b/); - for (const index of ['idx_pages_source_title_lower', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index); + for (const index of ['idx_pages_title_lower_hash', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index); expect(plan).toMatch(/(on|using) page_aliases_\w+/); }); }); From be6e01c6502a3a7e121738206502f8798f2622a2 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:29:15 +0000 Subject: [PATCH 18/37] Drop the old title index with one statement on both engines, and give each test brain its own setup The v326 drop runs DROP INDEX CONCURRENTLY on PGLite too, so the migration has no engine-kind branch, and it returns without dropping while another session still builds the hash index instead of throwing. The PGLite test builds each brain in beforeAll and disconnects it in afterAll. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../v326-pages-title-lower-hash-index.ts | 15 +++++-------- test/fixtures/goldens/migrations/records.json | 2 +- test/long-title-index-9779.test.ts | 22 ++++++++++++++----- 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts index d839fa77c73..39782d3dcb5 100644 --- a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts +++ b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts @@ -13,8 +13,10 @@ import { PAGES_NAME_LOOKUP_INDEXES } from './v240-pages-name-lookup-indexes.ts'; // title's hash; the lookups compare lower(title) exactly as before, so they // use it unchanged. This replaces the btree on brains that already built it: // the hash index is built first (CONCURRENTLY on Postgres), so the lookups -// stay indexed throughout, then the btree is dropped (CONCURRENTLY on -// Postgres). Each step is a no-op once done, so a rerun after an interruption +// stay indexed throughout, then the btree is dropped CONCURRENTLY (PGLite +// runs the same statement). The btree is dropped only once the hash index is +// valid: when another session is still building it, that session's run drops +// the btree. Each step is a no-op once done, so a rerun after an interruption // picks up where it stopped. An older gbrain runs against the new index // unchanged, since its queries are the same. export const LEGACY_TITLE_BTREE_INDEX = 'idx_pages_source_title_lower'; @@ -26,12 +28,7 @@ export const v326: Migration = { transaction: false, sql: '', handler: async engine => { - const index = PAGES_NAME_LOOKUP_INDEXES[0]; - if (await buildIndexOnline(engine, 326, index, { notice: migrationNotice }) === 'building') { - throw new Error(`Index ${index.name} is still being built by another session; rerun: gbrain apply-migrations --yes`); - } - await runMigrationStatement(engine, 326, engine.kind === 'postgres' - ? `DROP INDEX CONCURRENTLY IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}` - : `DROP INDEX IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}`); + if (await buildIndexOnline(engine, 326, PAGES_NAME_LOOKUP_INDEXES[0], { notice: migrationNotice }) === 'building') return; + await runMigrationStatement(engine, 326, `DROP INDEX CONCURRENTLY IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}`); }, }; diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json index d3d41e69edb..03174deb5d1 100644 --- a/test/fixtures/goldens/migrations/records.json +++ b/test/fixtures/goldens/migrations/records.json @@ -5329,7 +5329,7 @@ "tableRows", "withSchemaLockTimeout" ], - "sha256": "b9ebefed56c10ccb9ebdbfe62f3ef04603f30af48f4c69709fcf936afe02f2db" + "sha256": "cc4c06e2cc14661c81aca36d4f2dc75e6736b7fda5e353eb23d96c9b80c7a4b4" }, "idempotent": true, "name": "pages_title_lower_hash_index", diff --git a/test/long-title-index-9779.test.ts b/test/long-title-index-9779.test.ts index 16539c7962d..66f74b4487c 100644 --- a/test/long-title-index-9779.test.ts +++ b/test/long-title-index-9779.test.ts @@ -3,26 +3,36 @@ * and transcript imports cap the titles they make. The Postgres twin is * test/e2e/long-title-index-9779-postgres.test.ts. */ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { parseMarkdown } from '../src/core/markdown.ts'; import { renderSessionParts, TRANSCRIPT_TITLE_MAX_CHARS } from '../src/core/transcripts/render.ts'; import type { RedactedSession } from '../src/core/transcripts/render.ts'; import { expectReplacementPastV240, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; -let engine: PGLiteEngine; - -describe('long page titles (#9779, PGLite)', () => { - beforeEach(async () => { +// Each scenario rewinds the schema version, so each gets its own brain. +describe('long page titles before v240 (#9779, PGLite)', () => { + let engine: PGLiteEngine; + beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000); - afterEach(async () => { await engine.disconnect(); }, 60_000); + afterAll(async () => { await engine.disconnect(); }, 60_000); test('a brain before v240 holding 3,000-byte and 100 KB titles upgrades, and the pages are found by title through the index', async () => { await expectUpgradeFromBeforeV240(engine); }, 120_000); +}); + +describe('long page titles past v240 (#9779, PGLite)', () => { + let engine: PGLiteEngine; + beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + }, 120_000); + afterAll(async () => { await engine.disconnect(); }, 60_000); test('a brain with the old title btree gets the hash index, then saves a 3,000-byte title; a rerun changes nothing', async () => { await expectReplacementPastV240(engine); From db28b465ae4b41162eec91af08c8739087237990 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:35:47 +0000 Subject: [PATCH 19/37] A starter-surface caller can date a remembered fact with valid_from (GST-3186) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../gst3186-remember-valid-from-starter.md | 4 ++++ src/mcp/surface.ts | 1 + test/surface-param-confinement-9669.test.ts | 16 ++++++++++++++++ 3 files changed, 21 insertions(+) create mode 100644 changelog.d/gst3186-remember-valid-from-starter.md diff --git a/changelog.d/gst3186-remember-valid-from-starter.md b/changelog.d/gst3186-remember-valid-from-starter.md new file mode 100644 index 00000000000..29ba58282b0 --- /dev/null +++ b/changelog.d/gst3186-remember-valid-from-starter.md @@ -0,0 +1,4 @@ +**An MCP client on the starter tool list can now say when a remembered fact was true by passing `valid_from` to `remember`.** + +### Fixed +- Since starter clients were limited to the parameters their tool list shows, a single `remember` call with `valid_from` was refused with `param_not_on_surface`, although the same date was already accepted inside `items`. Ingest clients that know when each message was said can now date a single fact too. `valid_from` still doesn't appear in the starter tool list, so the list's size is unchanged. diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts index 045cfc6f689..5a12feb3d04 100644 --- a/src/mcp/surface.ts +++ b/src/mcp/surface.ts @@ -283,6 +283,7 @@ export const STARTER_CALLABLE_PARAMS: Readonly { + const stored = async (fact: string) => (await engine.executeRaw<{ valid_from: Date | string }>( + `SELECT valid_from FROM facts WHERE source_id = 'default' AND fact = $1`, [fact]))[0]; + const single = await dispatchToolCall(engine, 'remember', + { fact: 'acme-example signed the lease', entity: 'acme-example', provenance: 'meeting notes', valid_from: '2025-03-01' }, stdio('starter')); + expect(envelope(single).code).not.toBe(CODE); + expect(single.isError).toBeFalsy(); + const batch = await dispatchToolCall(engine, 'remember', + { items: [{ fact: 'acme-example opened an office', entity: 'acme-example', provenance: 'meeting notes', valid_from: '2025-03-01' }] }, stdio('starter')); + expect(batch.isError).toBeFalsy(); + const [a, b] = [await stored('acme-example signed the lease'), await stored('acme-example opened an office')]; + expect(new Date(a!.valid_from).toISOString()).toBe('2025-03-01T00:00:00.000Z'); + expect(new Date(b!.valid_from).toISOString()).toBe(new Date(a!.valid_from).toISOString()); + expect(filterOpsForSurface(operations.filter(op => op.name === 'remember'), 'starter')[0]!.params).not.toHaveProperty('valid_from'); + }); + test('param_not_on_surface is one registered code, and a call to a hidden tool still gets unknown_tool', async () => { expect(CODE in CODES).toBe(true); expect(operations.some(op => op.name === 'get_versions') && !allowedOpNames(operations, 'starter').has('get_versions')).toBe(true); From 8b9c81ca0e22ad6cd650ffb64023bc9588afdbc9 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:38:59 +0000 Subject: [PATCH 20/37] Connect the PGLite brains in the long-title test cold, so a version rewind replays its migrations A brain restored from the test runners' schema snapshot does not replay migrations after a rewind, so under bun run test and the stress gate the upgrade scenarios never ran v240 or v326. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- test/long-title-index-9779.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/long-title-index-9779.test.ts b/test/long-title-index-9779.test.ts index 66f74b4487c..06ccb224b26 100644 --- a/test/long-title-index-9779.test.ts +++ b/test/long-title-index-9779.test.ts @@ -6,17 +6,18 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { parseMarkdown } from '../src/core/markdown.ts'; +import { withColdPglite } from './helpers/with-snapshot.ts'; import { renderSessionParts, TRANSCRIPT_TITLE_MAX_CHARS } from '../src/core/transcripts/render.ts'; import type { RedactedSession } from '../src/core/transcripts/render.ts'; import { expectReplacementPastV240, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; -// Each scenario rewinds the schema version, so each gets its own brain. +// Each scenario rewinds the schema version, so each gets its own brain, connected +// cold: a snapshot-restored brain does not replay migrations after a rewind. describe('long page titles before v240 (#9779, PGLite)', () => { let engine: PGLiteEngine; beforeAll(async () => { engine = new PGLiteEngine(); - await engine.connect({}); - await engine.initSchema(); + await withColdPglite(async () => { await engine.connect({}); await engine.initSchema(); }); }, 120_000); afterAll(async () => { await engine.disconnect(); }, 60_000); @@ -29,8 +30,7 @@ describe('long page titles past v240 (#9779, PGLite)', () => { let engine: PGLiteEngine; beforeAll(async () => { engine = new PGLiteEngine(); - await engine.connect({}); - await engine.initSchema(); + await withColdPglite(async () => { await engine.connect({}); await engine.initSchema(); }); }, 120_000); afterAll(async () => { await engine.disconnect(); }, 60_000); From 864743b3833de002409983cdb380d4e9888fc383 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:45:18 +0000 Subject: [PATCH 21/37] The starter-surface runbook lists remember valid_from as callable (GST-3186) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- docs/operations/mcp-surface-runbook.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md index 5316c018f71..a1909f94b6c 100644 --- a/docs/operations/mcp-surface-runbook.md +++ b/docs/operations/mcp-surface-runbook.md @@ -61,7 +61,7 @@ connection may widen, and otherwise asks the user, because only the operator wid a pinned client. `STARTER_CALLABLE_PARAMS` in `src/mcp/surface.ts` lists the few hidden parameters a starter caller may still pass, each with its reason (page windows, the shared-skill follower, the thin client's source binding, the -connection check, a delegating client's `submit_agent` `queue`, `model` and +connection check, `remember` `valid_from` (already accepted inside `items`), a delegating client's `submit_agent` `queue`, `model` and `allowed_slug_prefixes`, `list_pages` paging with `offset`). An agent job (`submit_agent`) records the surface of the connection that submitted it, and its tool calls are refused the same way; a job queued before the surface was recorded keeps the full surface until From a85a04fbe1d994413938a71e1dca9d6646be0499 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 08:48:41 +0000 Subject: [PATCH 22/37] Keep re-imported transcript titles capped, and retry v326 while its index is still building\n\nA transcript page written under the 200-character title cap no longer loses the cap on its next re-import; only a page stored with a longer title keeps it. v326 now fails instead of recording itself applied while another session still builds the hash index, so the next upgrade drops the old btree. Docs and TODOS name the new index. Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: src/core/transcripts/ingest.ts:351:functional-contract reader=core Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- TODOS.md | 2 +- .../architecture/key-files/core-services-3.md | 2 +- docs/architecture/key-files/engines-2.md | 2 +- rust/docs/store/keyword.md | 4 +- src/core/engine-sql/exact-identity.ts | 2 +- .../v326-pages-title-lower-hash-index.ts | 12 +++-- src/core/transcripts/ingest.ts | 16 +++--- src/core/transcripts/render.ts | 6 ++- test/fixtures/goldens/migrations/records.json | 4 +- test/long-title-index-9779.test.ts | 52 +++++++++++++++++++ 10 files changed, 83 insertions(+), 19 deletions(-) diff --git a/TODOS.md b/TODOS.md index b9bda0f083b..5bdbb9c7fdf 100644 --- a/TODOS.md +++ b/TODOS.md @@ -2,7 +2,7 @@ ## Rust engine search follow-ups (filed 2026-11-18, #9730) -- [ ] **P2 — `rust-title-index-row-limit`: the Rust store keeps a title that PGLite and Postgres refuse (#9730).** **What:** PGLite and Postgres refuse a page whose `lower(title)` row in the btree index `idx_pages_source_title_lower` (`src/schema.sql`) is over 8191 bytes, with `index row requires N bytes, maximum size is 8191`. The Rust store has no such index and stores the page. A title of a few KB is enough on the SQL engines; the exact threshold depends on how well Postgres compresses the value. **Why:** a write that the SQL engines refuse must refuse the same way on Rust, or a brain moved between engines changes what it holds. **Fix:** design how Rust can refuse the same write with the same message (a Rust check can only approximate the compressed size), then add a parity case that uses an incompressible (random) title so every engine refuses it. Do not add a case that pins the current divergence as equal. **Effort:** M. **Priority:** P2. +- [x] **P2 — `rust-title-index-row-limit`: the Rust store keeps a title that PGLite and Postgres refuse (#9730).** **Done (#9779):** the gap closed from the SQL side: v240 and v326 index `lower(title)` with the hash index `idx_pages_title_lower_hash`, which stores only the title's hash, so PGLite and Postgres now hold a title of any length, as the Rust store does; `test/long-title-index-9779.test.ts` covers both SQL engines. **What (as filed):** PGLite and Postgres refuse a page whose `lower(title)` row in the btree index `idx_pages_source_title_lower` (`src/schema.sql`) is over 8191 bytes, with `index row requires N bytes, maximum size is 8191`. The Rust store has no such index and stores the page. A title of a few KB is enough on the SQL engines; the exact threshold depends on how well Postgres compresses the value. **Why:** a write that the SQL engines refuse must refuse the same way on Rust, or a brain moved between engines changes what it holds. **Fix:** design how Rust can refuse the same write with the same message (a Rust check can only approximate the compressed size), then add a parity case that uses an incompressible (random) title so every engine refuses it. Do not add a case that pins the current divergence as equal. **Effort:** M. **Priority:** P2. ## Rust engine store reads follow-ups (filed 2026-11-18, #9759) diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md index 87bf001d4c2..8bdbfa2c29d 100644 --- a/docs/architecture/key-files/core-services-3.md +++ b/docs/architecture/key-files/core-services-3.md @@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL - `src/core/entity-references-config.ts` — the one reader for `entity.names_references` (default on: found `names` rows and siblings carry `referenced_by_count` and a row-level `next` to the card) and `entity.record_types` (comma-separated canonical page types, default empty: no `records`), plus `readRowPageStatus` for `entity.row_page_status` (F3, default on: `page_status` on `context_pack` cards and newer-mention rows and on `get_backlinks` rows; record rows keep it when off). `readEntityReferencesConfig(engine)` fails closed to `{namesRow: true, recordTypes: []}`; the names verb and the MCP instruction builder (`readInstructionContent`) both read it. Test: `test/mcp-instructions-references.test.ts`. - `src/core/verbs/entity-source.ts` — which sources `entity` and `context_pack` read: `entitySources` returns the walk (home first: the ambient GBRAIN_SOURCE / .gbrain-source binding or a thin client's `prefer_source_id`, else the connection's source; then every other source in `federatedSearchScope` sorted by id; a bound stdio connection walks its binding's explicit-read set; a trusted local `__all__` walks every live source, a remote one stays fail-closed). An explicit `source_id` (or an `entity_refs` item, `entityRefs`) is a pin checked by `federatedSearchScope` + `assertExplicitSourceLive`, refused with recall's selector errors (`scope_denied`, `not_found`, `invalid_params`). `ambientMissNotice` is the `source_binding_narrowed` info notice when the ambient source had no match. Test: `test/entity-source-federation.test.ts`. -- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote, sources?})`: the zero-LLM sub-100ms card behind the `entity` verb. With `sources` (`selectAcrossSources`), the first source with a hit owns the card and every read behind it, and `card.entity.source_id` names it; suggestions carry `source_id`. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Candidate selection is the exported `selectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined})` (typed result: `hit` with the best page row, its `compiled_truth` a bounded withdrawal-overlaid prefix from `page-window/bounded-lead.ts`, and runners-up, `miss` with keyword near-misses, `withheld` when every match is quarantined and omitted); `entityLookupScope` reads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), and `readAka` is the card's `aka` read. `entity names[]` calls the same three directly. The exact-title / slug-suffix arm and the alias resolver's title check are index scans since v240 (`idx_pages_source_title_lower`, `idx_pages_slug_trgm`). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exempt `amends`, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only for remote callers other than the brain owner, `worldOnlyFacts`, GST-2951); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)). `buildEntityCard` also returns `factRows`, the full fact rows the card read (its visibility, eligibility and source already applied), outside the card. `assemblePack` (`src/core/context/turn-context.ts`) turns up to `RECENT_FACTS_CAP` per packed card into `entityFacts`, attributed to the card's `(source_id, slug)` and deduplicated by fact id; `renderPack` puts them under `## Entity facts` before hot memory and renders a fact in both once. The `context_pack` op returns them as `entity_facts[]` beside unchanged `facts[]`, packs them after cards under `budget_tokens`, drops them with their card, and prices a hot fact already shown there at zero. Test: `test/context-pack-entity-facts.test.ts`. +- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote, sources?})`: the zero-LLM sub-100ms card behind the `entity` verb. With `sources` (`selectAcrossSources`), the first source with a hit owns the card and every read behind it, and `card.entity.source_id` names it; suggestions carry `source_id`. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Candidate selection is the exported `selectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined})` (typed result: `hit` with the best page row, its `compiled_truth` a bounded withdrawal-overlaid prefix from `page-window/bounded-lead.ts`, and runners-up, `miss` with keyword near-misses, `withheld` when every match is quarantined and omitted); `entityLookupScope` reads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), and `readAka` is the card's `aka` read. `entity names[]` calls the same three directly. The exact-title / slug-suffix arm and the alias resolver's title check are index scans since v240 (`idx_pages_title_lower_hash`, `idx_pages_slug_trgm`). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exempt `amends`, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only for remote callers other than the brain owner, `worldOnlyFacts`, GST-2951); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)). `buildEntityCard` also returns `factRows`, the full fact rows the card read (its visibility, eligibility and source already applied), outside the card. `assemblePack` (`src/core/context/turn-context.ts`) turns up to `RECENT_FACTS_CAP` per packed card into `entityFacts`, attributed to the card's `(source_id, slug)` and deduplicated by fact id; `renderPack` puts them under `## Entity facts` before hot memory and renders a fact in both once. The `context_pack` op returns them as `entity_facts[]` beside unchanged `facts[]`, packs them after cards under `budget_tokens`, drops them with their card, and prices a hot fact already shown there at zero. Test: `test/context-pack-entity-facts.test.ts`. - `src/core/context/pack-brief.ts` — `contextPackBrief(ctx, p, {sourceId, includePrivate, eligibility})`: the `context_pack` pull brief for a named `counterparty` (`intent` meeting/reply), built on `proactive-brief.ts`; null when no counterparty is passed. Loaded by dynamic import so the op module stays light. - `src/core/mentions/newer-mentions.ts` — `readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined})`: the entity page's `COALESCE(effective_date, updated_at)`, then `readReferrerPage` (limit `NEWER_MENTIONS_CAP` 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within `NEWER_MENTIONS_CARD_CHARS` (2,000) of rendered rows; `more` when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized `include_quarantined`; `renderNewerMentionRow` labels each preview with its page's trust fields (`renderTrustedInline`; a quarantined one as external data). `isNewerMentionsEnabled` reads `mentions.newer_on_cards` (unset = on). `assemblePack` (`src/core/context/turn-context.ts`) reads them after cards and hot facts under the pack deadline and `NEWER_MENTIONS_PACK_CHARS` (6,000), `renderPack` puts them in a section after hot memory, and the `context_pack` op packs them last under `budget_tokens`. Test: `test/context-pack-newer-mentions.test.ts`. diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md index c8856ce2bc5..eeb537526e4 100644 --- a/docs/architecture/key-files/engines-2.md +++ b/docs/architecture/key-files/engines-2.md @@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL - `src/core/engine-sql/cycle-locks.ts` + `src/core/db-lock.ts` + `src/core/engine-capability-refusal.ts` — the `gbrain_cycle_locks` lease statements as typed `BrainEngine` methods (capability `cycle_lock`): `acquireCycleLock` (insert, or steal an expired lease past the steal grace; returns `{id, fence}` or null), `refreshCycleLock` (token-fenced renewal; false when the lease is gone), `releaseCycleLock`, `readCycleLocks` (by id, ids, stale or all), `deleteCycleLock` and `deleteCycleLockIfStale` (snapshot-matched deletes). The statement text lives once here; transport stays per engine: Postgres runs acquire/release/delete under `retryReadOnlyAutocommit` (and notes the direct-pool lease on a successful acquire) and runs the renewal on the direct session pool through `executeRawDirect` with the caller's AbortSignal (#1794); PGLite runs them on its database handle and does not forward the signal. `db-lock.ts` keeps identity, steal-grace policy and snapshot mapping, and does not branch on `engine.kind`. A capability refusal (`engine_capability_missing`) from these methods propagates out of `tryAcquireDbLock`'s best-effort takeover (`rethrowCapabilityRefusal`). `BrainEngine.listSourceLocalPaths` (SQL in `engine-sql/sources.ts`) is the registered-path read `withSourceFilesystemLock` uses to pick its lock root. Still raw on the lock path: `fenceLockRow` (managed sync fences) and `buildTenantLockId`. Pinned by `test/engine-parity/cycle-locks.test.ts`. - `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin). - `src/core/engine-sql/graph-rank.ts` — #7168: `rankEntitiesStatement(opts)`, the one `rank_entities` aggregate for both engines (a statement builder: the op runs it through `executeRaw` with its statement deadline, like `extractionLagStatement`). Edges are distinct `(from, to, link_type)` triples between live, in-scope endpoints (both endpoints scoped by `sourceIds`), self-links, non-ranking types (`rankingLinkSql`) and, unless `includeMentions`, mention rows excluded. Retired pages (`retiredPageSql`) fold into their `superseded_by`/`merged_into` target in the same source through a recursive chain over retired pages only, capped at `MAX_RETIREMENT_HOPS`; edges dedupe after folding and folded self-links drop. With `remote` every endpoint, chain hop, fold target and non-null link origin must be in scope, live, unquarantined, in an unarchived source and (with `excludePrivate`) not private, so a hidden target never folds. Ordered by the direction's count, then slug and source id (`COLLATE "C"`), LIMIT after folding. Tests: `test/rank-entities.test.ts`. -- `src/core/engine-sql/exact-identity.ts` — GBRA-156: `exactIdentityStatement(opts)`, the `whois` candidate read (a statement builder the op runs through `executeRaw`): a UNION of equality probes each served by an existing index, `lower(title)` (`idx_pages_source_title_lower`; the raw query is also lowered by the database), the slug basename (`idx_pages_slug_basename`, accent-folded by the slug grammar), `page_aliases.alias_norm`, and one GIN containment arm per address and shape (`email: x`, `email: [x]`, `emails: x`, `emails: [x]`; one OR of them plans a scan). Every probe and row stays in `sourceIds`; rows are live, in an unarchived source, of a type the `EntityTypeFilter` admits, and with `remote` unquarantined and (with `excludePrivate`) not private. The rows are candidates; the op verifies each. Accent-insensitive titles are found only through the lowered title (same accents, or none in the title) or the slug basename; a case-insensitive frontmatter email only through its as-written or lowercase value or a declared alias. Closing those gaps needs expression indexes (a migration). Tests: the index-plan case in `test/whois.test.ts` and `test/e2e/whois-postgres.test.ts`. +- `src/core/engine-sql/exact-identity.ts` — GBRA-156: `exactIdentityStatement(opts)`, the `whois` candidate read (a statement builder the op runs through `executeRaw`): a UNION of equality probes each served by an existing index, `lower(title)` (`idx_pages_title_lower_hash`; the raw query is also lowered by the database), the slug basename (`idx_pages_slug_basename`, accent-folded by the slug grammar), `page_aliases.alias_norm`, and one GIN containment arm per address and shape (`email: x`, `email: [x]`, `emails: x`, `emails: [x]`; one OR of them plans a scan). Every probe and row stays in `sourceIds`; rows are live, in an unarchived source, of a type the `EntityTypeFilter` admits, and with `remote` unquarantined and (with `excludePrivate`) not private. The rows are candidates; the op verifies each. Accent-insensitive titles are found only through the lowered title (same accents, or none in the title) or the slug basename; a case-insensitive frontmatter email only through its as-written or lowercase value or a declared alias. Closing those gaps needs expression indexes (a migration). Tests: the index-plan case in `test/whois.test.ts` and `test/e2e/whois-postgres.test.ts`. - `src/core/engine-sql/chunks.ts` `upsertChunksOnce` — a chunk replacement inside the caller's transaction: the batched `chunkWriteInvalidations` guard, then one prune (`moveDisplacedChunksAndPrune`: a row whose vector still matches its text (`movableChunkSql`) and whose exact text and source reappear at another index is parked at a negative index and moved there; rows outside the new set are deleted), then one multi-row INSERT per `jsonRowBatches` batch (at most `ROW_BATCH_MAX_ROWS` rows and `ROW_BATCH_MAX_BYTES` encoded bytes; the first is pipelined with the seal). A failure in any batch rolls back the prune and every earlier batch. Tests: `engine-sql-chunks-batched-write.test.ts`, the multi-batch case in `helpers/engine-sql-rollback-cases.ts`. Its `sealChunks` is `BrainEngine.sealChunks`, run inside the engine's page transaction: lock and read the live page, refuse a missing, deleted or segmented page, an archived source and a stale `expectedRevision`, then delete the chunks, insert the new ones with the seal chunker version, set the search vector and `text_projection_revision`, and drop the page's queued projection job. Both engines delegate to it; the engine parity suite seals its fixture chunks through it. - `src/core/engine-sql/persistence-state.ts` + `transaction-settings.ts` + `belief.ts` + `access-control.ts` (and `getSource` in `sources.ts`, `getConfigValues` in `config.ts`) — the typed reads and writes the default `importFromContent` path runs instead of `executeRaw`: `readManagedModeRows`, `getSourceStrictness`, `readPersistenceBrainId`, `readLocalWriterRow`, `insertLocalWriterRow`, `readTransactionSettings`, `applyTransactionSettings`, `readLedgerSource`, `isFolderRestricted`, `getSource`, `getConfigValues`. `getConfigValues` orders by key; `readLedgerSource` is a fragment that binds the coverage key as a parameter; the two transaction-settings methods each run one `unnest` statement that binds the setting names as parameters, and reject a name outside `[a-z_][a-z0-9_.]*`, so the dynamic-SQL guard passes. Both engines delegate in one line each, so the planned Rust engine implements the methods and refuses `raw_sql`. `folderRestricted` runs only when the fence step yields fixes or issues. Pinned by `test/engine-parity/import-path.test.ts`. diff --git a/rust/docs/store/keyword.md b/rust/docs/store/keyword.md index aa2f10bf52d..75b3d9403f2 100644 --- a/rust/docs/store/keyword.md +++ b/rust/docs/store/keyword.md @@ -174,8 +174,8 @@ A store written before those checks may hold a page SQL can never hold. `searchT nothing (`titles::readable_page_vector`, which skips only the size error) rather than failing every search in its scope. The refusal is a parity case (`test/engine-parity/page-vector-overflow.test.ts`; the arm's `putPage` always writes with `index: false`); the chunking path, the repeated `putPage` that no longer fits and the stored page are Rust unit tests in -`keyword/titles.rs` (the SQL engines cannot hold a title that large: `idx_pages_source_title_lower` refuses a title of -about 8 KB first). +`keyword/titles.rs` (before #9779 the SQL engines refused a title of about 8 KB in the btree `idx_pages_source_title_lower`; +the hash index `idx_pages_title_lower_hash` that replaced it holds a title of any length). ## The page filter diff --git a/src/core/engine-sql/exact-identity.ts b/src/core/engine-sql/exact-identity.ts index cbb6e1341d2..d029b148934 100644 --- a/src/core/engine-sql/exact-identity.ts +++ b/src/core/engine-sql/exact-identity.ts @@ -5,7 +5,7 @@ * Every arm is an equality probe an existing index serves, so the read never * scans a source's pages: * - * title lower(title) = key idx_pages_source_title_lower + * title lower(title) = key idx_pages_title_lower_hash * basename slug basename = key idx_pages_slug_basename (the slug * grammar already folds accents) * alias page_aliases.alias_norm = key the (source_id, alias_norm) indexes diff --git a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts index 39782d3dcb5..09e1a897d78 100644 --- a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts +++ b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts @@ -1,3 +1,4 @@ +import type { BrainEngine } from '../engine.ts'; import type { Migration } from './types.ts'; import { buildIndexOnline, migrationNotice, runMigrationStatement } from './helpers.ts'; import { PAGES_NAME_LOOKUP_INDEXES } from './v240-pages-name-lookup-indexes.ts'; @@ -15,12 +16,17 @@ import { PAGES_NAME_LOOKUP_INDEXES } from './v240-pages-name-lookup-indexes.ts'; // the hash index is built first (CONCURRENTLY on Postgres), so the lookups // stay indexed throughout, then the btree is dropped CONCURRENTLY (PGLite // runs the same statement). The btree is dropped only once the hash index is -// valid: when another session is still building it, that session's run drops -// the btree. Each step is a no-op once done, so a rerun after an interruption +// valid: when another session is still building it, v326 fails instead of +// recording itself applied, so the next upgrade retries the drop. Each step is a no-op once done, so a rerun after an interruption // picks up where it stopped. An older gbrain runs against the new index // unchanged, since its queries are the same. export const LEGACY_TITLE_BTREE_INDEX = 'idx_pages_source_title_lower'; +async function buildHashIndex(engine: BrainEngine): Promise { + const built = await buildIndexOnline(engine, 326, PAGES_NAME_LOOKUP_INDEXES[0], { notice: migrationNotice }); + if (built === 'building') throw new Error(`${PAGES_NAME_LOOKUP_INDEXES[0].name} is being built by another session; rerun the migration once it finishes`); +} + export const v326: Migration = { version: 326, name: 'pages_title_lower_hash_index', @@ -28,7 +34,7 @@ export const v326: Migration = { transaction: false, sql: '', handler: async engine => { - if (await buildIndexOnline(engine, 326, PAGES_NAME_LOOKUP_INDEXES[0], { notice: migrationNotice }) === 'building') return; + await buildHashIndex(engine); await runMigrationStatement(engine, 326, `DROP INDEX CONCURRENTLY IF EXISTS ${LEGACY_TITLE_BTREE_INDEX}`); }, }; diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts index 0d16cba21f5..41e41b84721 100644 --- a/src/core/transcripts/ingest.ts +++ b/src/core/transcripts/ingest.ts @@ -62,6 +62,7 @@ import { renderPartContent, renderSessionParts, transcriptPartId, + TRANSCRIPT_TITLE_MAX_CHARS, type RedactedSession, type RenderedPart, type RenderSessionResult, @@ -346,9 +347,9 @@ export async function runTranscriptsIngest( outcome.imperatives = redacted.imperativesFlagged; pageCeiling ??= opts.dryRun ? Math.floor(PAGE_MAX_BYTES * PAGE_CEILING_FILL) : await transcriptPageCeiling(engine); const stored = opts.dryRun - ? { layout: 'single' as const, partTargetBytes: pageCeiling, existingSlug: null } + ? { layout: 'single' as const, partTargetBytes: pageCeiling, existingSlug: null, titleOverCap: false } : await storedTranscriptLayout(engine, opts.sourceId ?? 'default', session.meta, pageCeiling); - const rendered = renderSessionParts(redacted, { sourcePath: path, layout: stored.layout, partTargetBytes: stored.partTargetBytes, existing: stored.existingSlug !== null }); + const rendered = renderSessionParts(redacted, { sourcePath: path, layout: stored.layout, partTargetBytes: stored.partTargetBytes, existing: stored.titleOverCap }); if (stored.existingSlug) adoptExistingBaseSlug(rendered, stored.existingSlug); outcome.baseSlug = rendered.baseSlug; outcome.parts = rendered.parts.length; @@ -703,10 +704,10 @@ const IMPORTER_INGESTED_VIA = 'cli:transcripts-ingest'; * (or the ceiling, when that is lower) and the current ceiling. */ async function storedTranscriptLayout(engine: BrainEngine, sourceId: string, meta: ParsedSession['meta'], pageCeiling: number): - Promise<{ layout: TranscriptLayout; partTargetBytes: number; existingSlug: string | null }> { + Promise<{ layout: TranscriptLayout; partTargetBytes: number; existingSlug: string | null; titleOverCap: boolean }> { const [first, second] = [transcriptPartId(meta, 1), transcriptPartId(meta, 2)]; - const rows = await engine.executeRaw<{ slug: string; fid: string; ti: unknown; trusted: boolean }>( - `SELECT p.slug, p.frontmatter->>'id' AS fid, p.frontmatter->'transcript_import' AS ti, + const rows = await engine.executeRaw<{ slug: string; title: string; fid: string; ti: unknown; trusted: boolean }>( + `SELECT p.slug, p.title, p.frontmatter->>'id' AS fid, p.frontmatter->'transcript_import' AS ti, CASE WHEN p.revision_write_request_id IS NULL THEN p.ingested_via IS NULL OR p.ingested_via = $4 WHEN r.id IS NOT NULL THEN r.principal_kind = 'local_cli' AND r.intent->>'ingested_via' IS NOT DISTINCT FROM $4 ELSE p.revision_principal_kind IS NOT DISTINCT FROM 'local_cli' AND p.ingested_via IS NOT DISTINCT FROM $4 END AS trusted @@ -724,11 +725,12 @@ async function storedTranscriptLayout(engine: BrainEngine, sourceId: string, met || (partOne !== undefined && partOne.trusted !== true && row.slug === `${partOne.slug}-p2`))); const one = importMeta(partOne); const split = partTwo !== undefined || (one !== null && !(Number(one.of) <= 1)); - if (!split) return { layout: 'single', partTargetBytes: pageCeiling, existingSlug: partOne?.slug ?? null }; + const titleOverCap = [...(partOne?.title ?? '')].length > TRANSCRIPT_TITLE_MAX_CHARS; + if (!split) return { layout: 'single', partTargetBytes: pageCeiling, existingSlug: partOne?.slug ?? null, titleOverCap }; const floor = Math.min(PART_TARGET_BYTES, pageCeiling); const pinned = [one?.part_bytes, importMeta(partTwo)?.part_bytes] .find(v => Number.isSafeInteger(v) && (v as number) >= floor && (v as number) <= pageCeiling) as number | undefined; - return { layout: 'split', partTargetBytes: pinned ?? floor, existingSlug: partOne?.slug ?? null }; + return { layout: 'split', partTargetBytes: pinned ?? floor, existingSlug: partOne?.slug ?? null, titleOverCap }; } /** Fold one file's adapter diagnostics into its outcome and the run result (drift, skipped lines, truncation). */ diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts index 48f400dd1e5..02b45881763 100644 --- a/src/core/transcripts/render.ts +++ b/src/core/transcripts/render.ts @@ -88,8 +88,10 @@ export const TRANSCRIPT_IMPORT_VERSION = 1; * harnesses report a session's opening text as its title, which can run to * 100 KB; the full text is already in the page body. A longer title is cut at * a codepoint boundary and ends in an ellipsis, so a cut title reads as cut. - * A session whose page already exists (`existing`) keeps its title as given, - * so a re-import never rewrites a page only to shorten its title. + * A session whose stored page already has a title over the cap (`existing`, + * a page written before the cap) keeps its title as given, so a re-import + * never rewrites a page only to shorten its title; a page written under the + * cap stays capped. */ export const TRANSCRIPT_TITLE_MAX_CHARS = 200; diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json index 03174deb5d1..1036e876276 100644 --- a/test/fixtures/goldens/migrations/records.json +++ b/test/fixtures/goldens/migrations/records.json @@ -62,6 +62,7 @@ "analyzeYieldingToVacuum": "edba1beff1547ea5c2e9f902efe44ab24e8d7016b2253603dcbba92d4137ca9a", "backfillChunkVectors": "1c8cc09a28aa3e906fe2f112b71cd3aa61f750a99984e35a029cff9458272aa1", "backfillPageVectors": "a325a5eee3bab49723af311f21b38a1ee4a0eaff1fb3c7e1539aa4dcb287ed66", + "buildHashIndex": "c34dfce66c3ac9d323ba298220dcad7c507a9481c663053f4833dbe158dfabe5", "buildIndexOnline": "aea86be06da261a76f6fad15def8f417cb5318c7991d2ded3cd86aeed82fb2cc", "buildOriginIndexIfClean": "cc6d16f50a4b5e303b87338700b9cded9784fc9cc9391c795bdd755e32385e6c", "checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b", @@ -5319,6 +5320,7 @@ "analyzeAfterIndexBuild", "analyzeDeferred", "analyzeYieldingToVacuum", + "buildHashIndex", "buildIndexOnline", "dropInvalidConcurrentIndex", "lockTableForAnalyze", @@ -5329,7 +5331,7 @@ "tableRows", "withSchemaLockTimeout" ], - "sha256": "cc4c06e2cc14661c81aca36d4f2dc75e6736b7fda5e353eb23d96c9b80c7a4b4" + "sha256": "87148f1195d5caf8077eb0e9a6abf7380ac4412a37a5ab99dbbeb2c237cbfa59" }, "idempotent": true, "name": "pages_title_lower_hash_index", diff --git a/test/long-title-index-9779.test.ts b/test/long-title-index-9779.test.ts index 06ccb224b26..c30e07ae740 100644 --- a/test/long-title-index-9779.test.ts +++ b/test/long-title-index-9779.test.ts @@ -4,11 +4,17 @@ * test/e2e/long-title-index-9779-postgres.test.ts. */ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { BrainEngine } from '../src/core/engine.ts'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { parseMarkdown } from '../src/core/markdown.ts'; import { withColdPglite } from './helpers/with-snapshot.ts'; import { renderSessionParts, TRANSCRIPT_TITLE_MAX_CHARS } from '../src/core/transcripts/render.ts'; import type { RedactedSession } from '../src/core/transcripts/render.ts'; +import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts'; +import { v326 } from '../src/core/schema-migrations/v326-pages-title-lower-hash-index.ts'; import { expectReplacementPastV240, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; // Each scenario rewinds the schema version, so each gets its own brain, connected @@ -39,6 +45,52 @@ describe('long page titles past v240 (#9779, PGLite)', () => { }, 120_000); }); +test('v326 fails, without dropping the old btree, while another session still builds the hash index (#9779)', async () => { + const statements: string[] = []; + const engine = { + kind: 'postgres', + executeRaw: async (sql: string) => { + statements.push(sql); + return sql.includes('pg_stat_progress_create_index') ? [{ valid: false, building: true }] : []; + }, + runMigration: async (_version: number, sql: string) => { statements.push(sql); }, + } as unknown as BrainEngine; + await expect(v326.handler!(engine)).rejects.toThrow('idx_pages_title_lower_hash is being built by another session'); + expect(statements.some(sql => sql.includes('DROP INDEX'))).toBe(false); +}); + +describe('transcript re-imports (#9779, PGLite)', () => { + let engine: PGLiteEngine; + let tmp: string; + beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + tmp = mkdtempSync(join(tmpdir(), 'gb-long-title-reimport-')); + }, 120_000); + afterAll(async () => { await engine.disconnect(); rmSync(tmp, { recursive: true, force: true }); }, 60_000); + + test('a page written under the cap stays capped, and a page stored with a longer title keeps it', async () => { + const name = 'alice-example long session '.repeat(20).trim(); + const path = join(tmp, 'conversations.json'); + const importWith = async (messages: number) => { + writeFileSync(path, JSON.stringify([{ uuid: 'long-title-1', name, created_at: '2026-08-01T10:00:00Z', + chat_messages: Array.from({ length: messages }, (_, i) => ({ + uuid: `m${i}`, sender: i % 2 ? 'assistant' : 'human', created_at: `2026-08-01T10:00:0${i}Z`, text: `message ${i}` })) }])); + const result = await runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', format: 'claude-export' }); + expect(result.sessionsImported).toBe(1); + const rows = await engine.executeRaw<{ slug: string; title: string }>('SELECT slug, title FROM pages WHERE deleted_at IS NULL'); + expect(rows).toHaveLength(1); + return rows[0]!; + }; + const first = await importWith(2); + expect([...first.title].length).toBe(TRANSCRIPT_TITLE_MAX_CHARS); + expect((await importWith(4)).title).toBe(first.title); + await engine.executeRaw('UPDATE pages SET title = $1 WHERE slug = $2', [name, first.slug]); + expect((await importWith(6)).title).toBe(name); + }, 120_000); +}); + describe('transcript titles (#9779)', () => { const session = (title: string): RedactedSession => ({ session: { From 5a56a4a32448f28e751a91a7beb41c90dd6d0712 Mon Sep 17 00:00:00 2001 From: Vorflux AI <249966464+vorflux[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:56:11 +0000 Subject: [PATCH 23/37] Let /ship reuse Linux CI test runs instead of rerunning the full suite locally The test and e2e run profiles in .gstack/pregate.json now say their runners are Linux. /ship's accept step only carries a CI run's tests stage when the profile's os matches the machine, so without it a Linux ship machine ran the whole selection again (or hit its time limit). --- .gstack/pregate.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.gstack/pregate.json b/.gstack/pregate.json index 983140ad2f4..7d4a76df592 100644 --- a/.gstack/pregate.json +++ b/.gstack/pregate.json @@ -183,13 +183,15 @@ "workflow": "test.yml", "events": ["workflow_dispatch", "push"], "jobs": ["full-suite"], - "artifact": "full-suite-tree" + "artifact": "full-suite-tree", + "os": "Linux" }, "e2e": { "workflow": "e2e.yml", "events": ["workflow_dispatch", "push"], "jobs": ["e2e-full-suite"], - "artifact": "e2e-full-suite-tree" + "artifact": "e2e-full-suite-tree", + "os": "Linux" }, "native-locks.yml/native": { "workflow": "test.yml", From f9139cae5734be71b468ea525970ccdae1b5781b Mon Sep 17 00:00:00 2001 From: Vorflux AI <249966464+vorflux[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:03:17 +0000 Subject: [PATCH 24/37] Add the release note for reusing Linux CI test runs in /ship --- changelog.d/vorflux-pregate-linux-os.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/vorflux-pregate-linux-os.md diff --git a/changelog.d/vorflux-pregate-linux-os.md b/changelog.d/vorflux-pregate-linux-os.md new file mode 100644 index 00000000000..48a89a35b9b --- /dev/null +++ b/changelog.d/vorflux-pregate-linux-os.md @@ -0,0 +1,4 @@ +**Shipping a gbrain change no longer reruns the full test suite on the developer's machine when Linux CI already passed at the same code.** + +### Changed +- For contributors: `.gstack/pregate.json` now records that the CI `test` and `e2e` jobs run on Linux. `/ship` reuses a passed CI run of those jobs only when the local machine runs the same operating system, and without this field it could not match them, so it ran the whole suite locally (about an hour). Nothing changes for gbrain users. From 9f76908c7388789df857daac81efb834136fd2c4 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 09:04:33 +0000 Subject: [PATCH 25/37] Leave the title index out of schema.sql, and count the part suffix toward the transcript title cap schema.sql replays on every boot, where a plain CREATE INDEX on an existing brain blocks page writes for the whole build and leaves v326 nothing to build online. Like v270 and v284, the index is now built only by v240 and v326, each online. A split transcript's part titles, suffix included, stay within 200 characters, so a capped part never measures as over the cap on re-import. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/pglite-schema.generated.ts | 1 - src/core/schema-embedded.generated.ts | 6 +-- src/core/transcripts/render.ts | 15 ++++-- src/schema.sql | 6 +-- .../long-title-index-9779-postgres.test.ts | 43 +++++++++++++-- .../catalog/pglite-schema-blob-default.json | 1 - .../pglite-schema-blob-fts-portuguese.json | 1 - .../catalog/pglite-schema-blob-high-dims.json | 1 - .../catalog/postgres-db-initschema.json | 1 - test/helpers/long-title-index.ts | 38 +++++++++++++ test/long-title-index-9779.test.ts | 53 ++++++++++++++++++- 11 files changed, 145 insertions(+), 21 deletions(-) diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts index f83e59f2166..1faa1ccb5d0 100644 --- a/src/core/pglite-schema.generated.ts +++ b/src/core/pglite-schema.generated.ts @@ -142,7 +142,6 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); -CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id); CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idx diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts index 0428d0f46d2..51288f33441 100644 --- a/src/core/schema-embedded.generated.ts +++ b/src/core/schema-embedded.generated.ts @@ -285,9 +285,9 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); --- v240/v326: the entity name lookups (exact title, alias title check, slug suffix) as index scans. Hash, not btree: --- a btree entry must fit in 2,704 bytes, and a page title has no length limit (#9779). -CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); +-- v240: the entity name lookups (exact title, alias title check, slug suffix) as index scans. The exact-title +-- index (idx_pages_title_lower_hash, a hash index: a page title has no length limit, #9779) is not here: v240 and +-- v326 build it online, and this file replays on every boot, where a plain CREATE INDEX would block page writes. CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); -- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first. CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC); diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts index 02b45881763..47f5f8f3f5b 100644 --- a/src/core/transcripts/render.ts +++ b/src/core/transcripts/render.ts @@ -87,7 +87,8 @@ export const TRANSCRIPT_IMPORT_VERSION = 1; * #9779: the longest title a transcript page gets, in characters. Some * harnesses report a session's opening text as its title, which can run to * 100 KB; the full text is already in the page body. A longer title is cut at - * a codepoint boundary and ends in an ellipsis, so a cut title reads as cut. + * a codepoint boundary and ends in an ellipsis, so a cut title reads as cut; + * a split session's " (part N)" suffix counts toward the cap. * A session whose stored page already has a title over the cap (`existing`, * a page written before the cap) keeps its title as given, so a re-import * never rewrites a page only to shorten its title; a page written under the @@ -427,9 +428,13 @@ export function renderSessionParts( throw new Error(`session ${meta.sessionId} renders ${groups.length} parts at ${partTargetBytes} bytes per part, over the ${TRANSCRIPT_MAX_PARTS}-part cap; nothing was written for it`); } const single = (opts.layout ?? 'single') === 'single' && groups.length === 1; - const cps = [...(meta.title?.trim() ?? '')]; - const title = (cps.length > TRANSCRIPT_TITLE_MAX_CHARS && !opts.existing ? cps.slice(0, TRANSCRIPT_TITLE_MAX_CHARS - 1).join('').trimEnd() + '…' : cps.join('')) - || `${meta.harness} session ${meta.sessionId.slice(0, 12)}`; + const title = meta.title?.trim() || `${meta.harness} session ${meta.sessionId.slice(0, 12)}`; + const partTitle = (part: number): string => { + const suffix = single ? '' : ` (part ${part})`; + const cps = [...title]; + const room = TRANSCRIPT_TITLE_MAX_CHARS - suffix.length; + return (cps.length > room && !opts.existing ? cps.slice(0, room - 1).join('').trimEnd() + '…' : title) + suffix; + }; const parts: RenderedPart[] = groups.map((group, idx) => { const part = idx + 1; @@ -440,7 +445,7 @@ export function renderSessionParts( : new Set(group.filter((b) => redacted.imperativeFlags![b.message]).map((b) => b.message)).size; const fm: Record = { type: 'conversation', - title: single ? title : `${title} (part ${part})`, + title: partTitle(part), date: dateIso.slice(0, 10), id: frontmatterId, transcript_import: { diff --git a/src/schema.sql b/src/schema.sql index 498dd0dd878..769559b3d3d 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -281,9 +281,9 @@ CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type); CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter); CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', ''))); --- v240/v326: the entity name lookups (exact title, alias title check, slug suffix) as index scans. Hash, not btree: --- a btree entry must fit in 2,704 bytes, and a page title has no length limit (#9779). -CREATE INDEX IF NOT EXISTS idx_pages_title_lower_hash ON pages USING hash (lower(title)); +-- v240: the entity name lookups (exact title, alias title check, slug suffix) as index scans. The exact-title +-- index (idx_pages_title_lower_hash, a hash index: a page title has no length limit, #9779) is not here: v240 and +-- v326 build it online, and this file replays on every boot, where a plain CREATE INDEX would block page writes. CREATE INDEX IF NOT EXISTS idx_pages_slug_trgm ON pages USING GIN (slug gin_trgm_ops); -- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first. CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC); diff --git a/test/e2e/long-title-index-9779-postgres.test.ts b/test/e2e/long-title-index-9779-postgres.test.ts index 02ad007504d..7c72c9e95ee 100644 --- a/test/e2e/long-title-index-9779-postgres.test.ts +++ b/test/e2e/long-title-index-9779-postgres.test.ts @@ -1,13 +1,17 @@ /** * #9779 on real Postgres: the twin of test/long-title-index-9779.test.ts. The - * v326 replacement builds and drops CONCURRENTLY here, so this is the arm that - * proves the online path. + * v240 and v326 builds run CONCURRENTLY here, so this is the arm that proves + * the online path, including the rebuild of an INVALID leftover. * * Gated by DATABASE_URL — skips gracefully without real Postgres. */ import { afterAll, beforeEach, describe, test } from 'bun:test'; -import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts'; -import { expectReplacementPastV240, expectUpgradeFromBeforeV240 } from '../helpers/long-title-index.ts'; +import { randomUUID } from 'node:crypto'; +import postgres from '#postgres'; +import { PostgresEngine } from '../../src/core/postgres-engine.ts'; +import { assertSafeE2eDatabaseUrl, getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts'; +import { expectFreshBrainHasTitleIndex, expectInvalidTitleIndexRebuilt, expectReplacementPastV240, expectReplayBuildsNoTitleIndex, + expectUpgradeFromBeforeV240 } from '../helpers/long-title-index.ts'; const describePg = hasDatabase() ? describe : describe.skip; @@ -22,4 +26,35 @@ describePg('long page titles (#9779, Postgres)', () => { test('a brain with the old title btree gets the hash index, then saves a 3,000-byte title; a rerun changes nothing', async () => { await expectReplacementPastV240(getEngine()); }, 240_000); + + test('a boot that replays schema.sql on an existing brain builds no title index', async () => { + await expectReplayBuildsNoTitleIndex(getEngine()); + }, 240_000); + + test('an INVALID title index left by an interrupted online build is dropped and rebuilt by the next upgrade', async () => { + await expectInvalidTitleIndexRebuilt(getEngine()); + }, 240_000); + + test('a fresh brain has the index, valid', async () => { + const url = process.env.DATABASE_URL!; + assertSafeE2eDatabaseUrl(url); + const name = `gbrain_test_title_${randomUUID().replace(/-/g, '')}`; + const admin = postgres(url, { max: 1, prepare: false, onnotice: () => {} }); + try { + await admin.unsafe(`CREATE DATABASE ${name}`); + const fresh = new PostgresEngine(); + try { + const u = new URL(url); + u.pathname = `/${name}`; + await fresh.connect({ database_url: u.toString(), poolSize: 2 }); + await fresh.initSchema(); + await expectFreshBrainHasTitleIndex(fresh); + } finally { + await fresh.disconnect(); + await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); + } + } finally { + await admin.end({ timeout: 5 }); + } + }, 240_000); }); diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json index 6c80ccb694f..b2e82e3cecb 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json @@ -968,7 +968,6 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json index 1dcd0f912d7..0d78b36ed8a 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json @@ -968,7 +968,6 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json index c82e73cc2a1..e0e4e18b288 100644 --- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json +++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json @@ -967,7 +967,6 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json index 31935f939eb..be093850644 100644 --- a/test/fixtures/goldens/catalog/postgres-db-initschema.json +++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json @@ -999,7 +999,6 @@ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))", "idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)", "idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)", - "idx_pages_title_lower_hash": "CREATE INDEX idx_pages_title_lower_hash ON public.pages USING hash (lower(title))", "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))", "idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)", "idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)", diff --git a/test/helpers/long-title-index.ts b/test/helpers/long-title-index.ts index 09860ce7067..a5de5b953d9 100644 --- a/test/helpers/long-title-index.ts +++ b/test/helpers/long-title-index.ts @@ -93,3 +93,41 @@ export async function expectReplacementPastV240(engine: BrainEngine): Promise { + const [row] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [TITLE_INDEX]); + return row ? row.valid : null; +} + +/** The boot-time replay of schema.sql builds no title index (a plain CREATE INDEX there would block page writes); the migrations own it. */ +export async function expectReplayBuildsNoTitleIndex(engine: BrainEngine): Promise { + await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX}`); + await engine.initSchema(); + expect(await indexDef(engine, TITLE_INDEX)).toBeNull(); + await v326.handler!(engine); + await expectReplacedIndexes(engine); +} + +/** A fresh brain ends with the title index present and valid, built by the migrations alone. */ +export async function expectFreshBrainHasTitleIndex(engine: BrainEngine): Promise { + await expectReplacedIndexes(engine); + expect(await indexValid(engine)).toBe(true); +} + +/** + * Postgres: an interrupted concurrent build leaves an INVALID index under the + * name. The next upgrade drops and rebuilds it instead of taking it as built. + */ +export async function expectInvalidTitleIndexRebuilt(engine: BrainEngine): Promise { + await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX}`); + await engine.executeRaw(LEGACY_BTREE_SQL); + await engine.putPage('people/invalid-build', { type: 'person', title: 'Carol Example', compiled_truth: 'Body.' }); + await expect(engine.executeRaw(`CREATE INDEX CONCURRENTLY ${TITLE_INDEX} ON pages USING hash ((1 / (length(title) - length(title))))`)) + .rejects.toThrow('division by zero'); + expect(await indexValid(engine)).toBe(false); + await engine.setConfig('version', String(v326.version - 1)); + await engine.initSchema(); + await expectReplacedIndexes(engine); + expect(await indexValid(engine)).toBe(true); + await expectFoundByTitle(engine, 'people/invalid-build', 'carol example'); +} diff --git a/test/long-title-index-9779.test.ts b/test/long-title-index-9779.test.ts index c30e07ae740..2fa38c91379 100644 --- a/test/long-title-index-9779.test.ts +++ b/test/long-title-index-9779.test.ts @@ -15,7 +15,7 @@ import { renderSessionParts, TRANSCRIPT_TITLE_MAX_CHARS } from '../src/core/tran import type { RedactedSession } from '../src/core/transcripts/render.ts'; import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts'; import { v326 } from '../src/core/schema-migrations/v326-pages-title-lower-hash-index.ts'; -import { expectReplacementPastV240, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; +import { expectFreshBrainHasTitleIndex, expectReplacementPastV240, expectReplayBuildsNoTitleIndex, expectUpgradeFromBeforeV240, incompressibleTitle } from './helpers/long-title-index.ts'; // Each scenario rewinds the schema version, so each gets its own brain, connected // cold: a snapshot-restored brain does not replay migrations after a rewind. @@ -45,6 +45,23 @@ describe('long page titles past v240 (#9779, PGLite)', () => { }, 120_000); }); +describe('the title index is the migrations\' alone (#9779, PGLite)', () => { + let engine: PGLiteEngine; + beforeAll(async () => { + engine = new PGLiteEngine(); + await withColdPglite(async () => { await engine.connect({}); await engine.initSchema(); }); + }, 120_000); + afterAll(async () => { await engine.disconnect(); }, 60_000); + + test('a fresh brain has the index, valid', async () => { + await expectFreshBrainHasTitleIndex(engine); + }); + + test('a boot that replays schema.sql on an existing brain builds no title index', async () => { + await expectReplayBuildsNoTitleIndex(engine); + }, 120_000); +}); + test('v326 fails, without dropping the old btree, while another session still builds the hash index (#9779)', async () => { const statements: string[] = []; const engine = { @@ -91,6 +108,40 @@ describe('transcript re-imports (#9779, PGLite)', () => { }, 120_000); }); +describe('split transcript re-imports (#9779, PGLite)', () => { + let engine: PGLiteEngine; + let tmp: string; + beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + await engine.setConfig('content_sanity.bytes_block', '60000'); + tmp = mkdtempSync(join(tmpdir(), 'gb-long-title-split-')); + }, 120_000); + afterAll(async () => { await engine.disconnect(); rmSync(tmp, { recursive: true, force: true }); }, 60_000); + + test('every part of a split session is titled at most 200 characters with its part suffix, and stays so on re-import', async () => { + const name = 'bob-example split session '.repeat(20).trim(); + const path = join(tmp, 'conversations.json'); + const importWith = async (messages: number) => { + writeFileSync(path, JSON.stringify([{ uuid: 'long-title-split-1', name, created_at: '2026-08-01T10:00:00Z', + chat_messages: Array.from({ length: messages }, (_, i) => ({ + uuid: `m${i}`, sender: i % 2 ? 'assistant' : 'human', created_at: `2026-08-01T10:00:0${i}Z`, text: `message ${i} ` + incompressibleTitle(30_000, 10 + i) })) }])); + await runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', format: 'claude-export' }); + return engine.executeRaw<{ slug: string; title: string }>('SELECT slug, title FROM pages WHERE deleted_at IS NULL ORDER BY slug'); + }; + const first = await importWith(3); + expect(first.length).toBeGreaterThan(1); + first.forEach((row, i) => { + expect([...row.title].length).toBeLessThanOrEqual(TRANSCRIPT_TITLE_MAX_CHARS); + expect(row.title.endsWith(` (part ${i + 1})`)).toBe(true); + }); + const again = await importWith(4); + expect(again.slice(0, first.length).map(r => r.title)).toEqual(first.map(r => r.title)); + for (const row of again) expect([...row.title].length).toBeLessThanOrEqual(TRANSCRIPT_TITLE_MAX_CHARS); + }, 120_000); +}); + describe('transcript titles (#9779)', () => { const session = (title: string): RedactedSession => ({ session: { From 5bdbb42cdaa0a0348ba4d183528356bdd0714aff Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 09:05:07 +0000 Subject: [PATCH 26/37] Say in v326 that schema.sql no longer carries the title index Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../v326-pages-title-lower-hash-index.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts index 09e1a897d78..7ad282d8735 100644 --- a/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts +++ b/src/core/schema-migrations/v326-pages-title-lower-hash-index.ts @@ -9,16 +9,17 @@ import { PAGES_NAME_LOOKUP_INDEXES } from './v240-pages-name-lookup-indexes.ts'; // #9779: v240 first indexed the exact-title lookups with a btree on // (source_id, lower(title)). A btree entry must fit in 2,704 bytes, so on a // brain past v240 a page whose title is longer could not be saved, and the -// index could not be built on a brain that already held one. v240 and -// schema.sql now build a hash index on lower(title), which stores only the -// title's hash; the lookups compare lower(title) exactly as before, so they -// use it unchanged. This replaces the btree on brains that already built it: +// index could not be built on a brain that already held one. v240 now builds +// a hash index on lower(title), which stores only the title's hash; the +// lookups compare lower(title) exactly as before, so they use it unchanged. +// schema.sql leaves it out: it replays on every boot, where a plain CREATE +// INDEX would block page writes. This replaces the btree on brains that built it: // the hash index is built first (CONCURRENTLY on Postgres), so the lookups // stay indexed throughout, then the btree is dropped CONCURRENTLY (PGLite // runs the same statement). The btree is dropped only once the hash index is // valid: when another session is still building it, v326 fails instead of -// recording itself applied, so the next upgrade retries the drop. Each step is a no-op once done, so a rerun after an interruption -// picks up where it stopped. An older gbrain runs against the new index +// recording itself applied, so the next upgrade retries the drop. Each step is +// a no-op once done, so a rerun after an interruption picks up where it stopped. An older gbrain runs against the new index // unchanged, since its queries are the same. export const LEGACY_TITLE_BTREE_INDEX = 'idx_pages_source_title_lower'; From 519a4cd439ad72102032dfbfa1c92e17b45a2447 Mon Sep 17 00:00:00 2001 From: Vorflux AI <249966464+vorflux[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:14:03 +0000 Subject: [PATCH 27/37] Record the runner OS in CI run evidence so /ship accepts the Linux test runs The test and e2e run profiles now require os: Linux, and gstack refuses a run whose tree.json records no OS. scripts/ci-full-suite-tree.sh now writes os from RUNNER_OS, and docs/ci-event-parity.md describes the field. --- docs/ci-event-parity.md | 10 +++++++++- scripts/ci-full-suite-tree.sh | 11 ++++++++--- test/scripts/full-ci-workflow.test.ts | 5 +++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.md index cfb680b278c..74bf23ae8ad 100644 --- a/docs/ci-event-parity.md +++ b/docs/ci-event-parity.md @@ -234,6 +234,9 @@ inventory: the same run, attempt and commit. Otherwise both are left out with a warning: the run still counts for merge, but gstack refuses it (`inventory_uncovered`). A push that reused a run has no `full-suite` job, so it is never evidence. +- `tree.json` carries `os`, the runner's OS from `RUNNER_OS` (`Linux` for both + jobs). A run profile that sets `os` refuses a run whose `tree.json` records a + different OS or none (`os_mismatch`). - `bash scripts/pregate-remote-gate.sh --list` prints the inventory: the gate command with `--list` (`scripts/ci-ubicloud.ts --list`), the same lanes and discovery the gate runs, one file per line. It exits non-zero when the @@ -259,7 +262,12 @@ inventory: (`test.yml`, job `full-suite`, artifact `full-suite-tree`) and `e2e` (`e2e.yml`, job `e2e-full-suite`, artifact `e2e-full-suite-tree`), each accepting `workflow_dispatch` and `push` runs from the last 24 hours, and - `remote_gate_runs` naming both with this inventory command. gstack reads them + `remote_gate_runs` naming both with this inventory command. Both profiles set + `os` to `Linux`, the OS of the runners that execute these jobs: gstack uses a + run only when its `tree.json` records that OS, and the final pregate's tests + stage reuses it only on a machine running the same OS (on macOS or Windows + that stage runs the selected tests locally; the lane carries below don't + need it). gstack reads the profiles only from `origin/`, so a branch cannot loosen them. gstack accepts these keys from 1.91.377.0 on. diff --git a/scripts/ci-full-suite-tree.sh b/scripts/ci-full-suite-tree.sh index cdccb4866a8..fc01fa68415 100755 --- a/scripts/ci-full-suite-tree.sh +++ b/scripts/ci-full-suite-tree.sh @@ -5,8 +5,12 @@ # aggregate succeeded. scripts/ci-reuse.ts reads the artifact on a push to master; # `gstack-pregate clear --run` reads it as run evidence for the remote gate. # Input (environment): ARTIFACT_DIR, RUN_ID, RUN_ATTEMPT, WORKFLOW, EVENT, and -# optionally MANIFEST, the run's ci-manifest.json (scripts/ci-manifest.ts). +# optionally MANIFEST, the run's ci-manifest.json (scripts/ci-manifest.ts), and +# RUNNER_OS, which GitHub Actions sets on every runner. # Output: $ARTIFACT_DIR/tree.json and step-summary lines. +# `os` is the runner's OS (Linux, macOS or Windows) when RUNNER_OS is set. +# gstack refuses a run under a .gstack/pregate.json run profile that sets `os` +# unless tree.json records that OS (gstack docs/pregate.md#run-evidence). # `files` (every test file the run loaded, repo-relative, across lanes and # arms; a file whose tests all skipped counts, because the remote gate's # inventory lists the same env- and platform-gated files) and `tests` (its @@ -45,8 +49,9 @@ else fi fi jq -n --arg tree "$tree" --arg sha "$sha" --arg workflow "$WORKFLOW" --arg event "$EVENT" \ - --argjson run_id "$RUN_ID" --argjson run_attempt "$RUN_ATTEMPT" --slurpfile evidence "$evidence" \ - '{tree: $tree, sha: $sha, workflow: $workflow, event: $event, run_id: $run_id, run_attempt: $run_attempt, profile: "full"} + $evidence[0]' \ + --argjson run_id "$RUN_ID" --argjson run_attempt "$RUN_ATTEMPT" --slurpfile evidence "$evidence" --arg os "${RUNNER_OS:-}" \ + '{tree: $tree, sha: $sha, workflow: $workflow, event: $event, run_id: $run_id, run_attempt: $run_attempt, profile: "full"} + + (if $os == "" then {} else {os: $os} end) + $evidence[0]' \ > "$ARTIFACT_DIR/tree.json" rm -f "$evidence" jq -c 'del(.files)' "$ARTIFACT_DIR/tree.json" diff --git a/test/scripts/full-ci-workflow.test.ts b/test/scripts/full-ci-workflow.test.ts index ddd4da7b4e7..6b306cf7467 100644 --- a/test/scripts/full-ci-workflow.test.ts +++ b/test/scripts/full-ci-workflow.test.ts @@ -134,6 +134,11 @@ describe('full CI on pull requests', () => { tree: git('rev-parse', 'HEAD^{tree}').stdout.trim(), sha: git('rev-parse', 'HEAD').stdout.trim(), workflow: 'Test', event: 'workflow_dispatch', run_id: 42, run_attempt: 2, profile: 'full', }); + // On a runner, tree.json records RUNNER_OS: a run profile with `os` refuses a run that records none. + const onRunner = bash(`bash ${join(root, 'scripts/ci-full-suite-tree.sh')}`, + { ARTIFACT_DIR: out, RUN_ID: '42', RUN_ATTEMPT: '2', WORKFLOW: 'Test', EVENT: 'workflow_dispatch', RUNNER_OS: 'Linux', GITHUB_STEP_SUMMARY: join(dir, 'summary.md') }, dir); + expect(onRunner.status, onRunner.stderr).toBe(0); + expect(JSON.parse(readFileSync(join(out, 'tree.json'), 'utf8')).os).toBe('Linux'); } finally { rmSync(dir, { recursive: true, force: true }); } From b43bddaf9ecb6aba42c084373792533f1efc0f49 Mon Sep 17 00:00:00 2001 From: Vorflux AI <249966464+vorflux[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:14:09 +0000 Subject: [PATCH 28/37] Mention the recorded runner OS in the release note --- changelog.d/vorflux-pregate-linux-os.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/vorflux-pregate-linux-os.md b/changelog.d/vorflux-pregate-linux-os.md index 48a89a35b9b..a7c4181aa71 100644 --- a/changelog.d/vorflux-pregate-linux-os.md +++ b/changelog.d/vorflux-pregate-linux-os.md @@ -1,4 +1,4 @@ **Shipping a gbrain change no longer reruns the full test suite on the developer's machine when Linux CI already passed at the same code.** ### Changed -- For contributors: `.gstack/pregate.json` now records that the CI `test` and `e2e` jobs run on Linux. `/ship` reuses a passed CI run of those jobs only when the local machine runs the same operating system, and without this field it could not match them, so it ran the whole suite locally (about an hour). Nothing changes for gbrain users. +- For contributors: `.gstack/pregate.json` now records that the CI `test` and `e2e` jobs run on Linux, and each full run's `tree.json` now records the runner's OS, which gstack requires before it accepts the run. `/ship` reuses a passed CI run of those jobs only when the local machine runs the same operating system, and without this field it could not match them, so it ran the whole suite locally (about an hour). Nothing changes for gbrain users. From 3b37568cb877250f6cd6e889dd0df967263d6faf Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 09:27:38 +0000 Subject: [PATCH 29/37] A secret store restore ties an original only to a page that still holds its marker (GST-3178) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/secret-restore-marker.md | 9 +++ docs/guides/secret-store.md | 15 ++-- scripts/engine-raw-sql-baseline.tsv | 2 +- scripts/page-body-readers-baseline.tsv | 1 + src/commands/secrets.ts | 1 + src/core/page-state/rename-alias.ts | 6 +- src/core/secret-store/backup.ts | 6 +- src/core/secret-store/marker-sql.ts | 18 +++++ src/core/secret-store/store.ts | 41 ++++++---- test/fixtures/goldens/sql-text/pages.json | 7 +- test/secret-store-backup.test.ts | 6 +- test/secret-store-purge.test.ts | 94 +++++++++++++++++++---- 12 files changed, 157 insertions(+), 49 deletions(-) create mode 100644 changelog.d/secret-restore-marker.md create mode 100644 src/core/secret-store/marker-sql.ts diff --git a/changelog.d/secret-restore-marker.md b/changelog.d/secret-restore-marker.md new file mode 100644 index 00000000000..043d31bc815 --- /dev/null +++ b/changelog.d/secret-restore-marker.md @@ -0,0 +1,9 @@ +--- +important: security +--- +**A secret store restore ties an original only to a page that still holds its marker.** + +### Fixed +- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug, so that page's readers never pass the `reveal_secret` read check for it. A place comes back only on a page whose text holds the entry's marker. +- A backup that names a page by a slug it had before a rename now ties the entry to the pages that hold its marker (counted as `reattached`), or skips it when none does (`skipped_no_page`), so a restore never brings back what a purge removed. This replaces the 0.60.744.0 note saying such an entry would be restored without a place. +- A rename no longer moves a leftover place with no page onto the renamed page unless that page holds its marker. diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index 25eb57fd4c3..6cd3c546d6d 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -131,10 +131,13 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t a host whose keyring holds the key the backup names (import the escrow copy first), and it skips, and lists, any row that does not authenticate under it. An entry already here is left as it is, even when the backup's copy differs; the places the backup recorded for it that this brain lacks are added, so a later purge of one page never removes an - original another page still holds. A restore only adds rows and never deletes one, and each restored place is tied - to the page that holds its slug in this brain now. - An original whose every recorded place was on a page this brain does not hold is skipped and counted as - `skipped_no_page` ("skipped because their page is not in this brain"): the page was purged, or is not synced yet, + original another page still holds. A restore only adds rows and never deletes one, and it ties each restored place + only to a page whose text holds the entry's marker: the page at the backed-up slug when that page holds it, and + otherwise every page in the source that does (counted as `reattached`: the page was renamed before the backup named + it by its current slug). A page that merely took an old slug never gets the original. A page whose body is stored in segments + counts as holding the marker at its backed-up slug, and is never found by the search across the source. + An original recorded only on pages, none of which in this brain holds its marker, is skipped and counted as + `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, or is not synced yet, and a restore cannot tell which, so it never brings back what a page purge removed. Sync the pages, then run the same restore again; it adds what it skipped. When every entry is skipped that way (a rebuilt brain before sync), the restore refuses with `invalid_params` and writes nothing, so a script never reads it as finished. @@ -169,8 +172,4 @@ store is backed up, and warns when: - It does not erase bytes physically: dead database rows and WAL can hold old text until the database reclaims them. - An original an older gbrain left an occurrence for after its page was purged stays: that occurrence still names it, so the cascade and doctor's count treat it as referenced. -- A restore from a backup taken before a rename can tie an original to a different page that has since taken the - renamed page's old slug, and that page's readers then pass the `reveal_secret` read check for it. It needs both: an - older backup and another page now at that slug. After a restore, `gbrain secrets list` shows the pages each original - is tied to. A backup taken after the rename names the new slug. - Markers written before the store existed (`` with no id) stay unrecoverable. diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv index 4cbb72b441b..ff233e2e36a 100644 --- a/scripts/engine-raw-sql-baseline.tsv +++ b/scripts/engine-raw-sql-baseline.tsv @@ -1100,7 +1100,7 @@ src/core/search/transcript-quote.ts execute_raw 3 src/core/search/two-pass.ts execute_raw 5 src/core/secret-store/restore.ts execute_raw 3 secret restore reads the page revision and live knowledge_revision and flips secret_store.status; no typed engine method for the secret store exists yet src/core/secret-store/spool.ts execute_raw 1 GST-2988 PR 2 spool: reads every allowed (restored) key_id and value_mac from secret_store to rebuild allowed.json; branched before the #9641 ratchet; no typed engine method for the secret store exists yet -src/core/secret-store/store.ts execute_raw 22 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; all move behind typed engine methods with the rest after gbrain#9694 +src/core/secret-store/store.ts execute_raw 23 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +1: restore ties an entry whose backed-up slugs name no page holding its marker to the pages that hold it; all move behind typed engine methods with the rest after gbrain#9694 src/core/serve-sync-runner.ts execute_raw 1 src/core/session-lane.ts execute_raw 3 src/core/shared-skills/adopted-packs.ts execute_raw 1 diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv index 553ce2f4667..7cb249b40f2 100644 --- a/scripts/page-body-readers-baseline.tsv +++ b/scripts/page-body-readers-baseline.tsv @@ -664,6 +664,7 @@ src/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBod src/core/search/safe-chunks.ts bodyWriteChunkVersion sql SEGW spliced into inline body writes only; a segmented row refuses those writes (CHECK) src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) src/core/search/safe-chunks.ts protectedTakesFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) +src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit at a named slug and never in a search across a source src/core/secret-store/restore.ts previewRestore sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit and the apply reads it whole src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE src/core/shared-skills/migration-export.ts exportInventory field INLINE diff --git a/src/commands/secrets.ts b/src/commands/secrets.ts index 2955318123e..ed9a6793abb 100644 --- a/src/commands/secrets.ts +++ b/src/commands/secrets.ts @@ -136,6 +136,7 @@ export async function runSecrets(engine: BrainEngine, args: string[]): Promise new` in slug_aliases when a page is renamed, inside the @@ -81,7 +82,7 @@ export async function recordSlugLineAlias(tx: Pick, * caller's rename transaction. The new slug is free (the page UPDATE * succeeded), so fence rows or aliases still keyed to it belong to a purged * page and yield to the moved ones. A secret occurrence moves only when it is the renamed page's own (its - * page_id is that page, or the stale row a fallback rename retires, or none): an occurrence another page holds under + * page_id is that page or the stale row a fallback rename retires, or it has none and the page holds its marker): an occurrence another page holds under * an older slug stays with that page. An ontology observation the new slug * already holds is dropped before its key moves (B-10, dropRekeyDuplicates). * A brain whose schema predates the facts or alias tables skips them inside a @@ -108,7 +109,8 @@ export async function moveSlugBindings( AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)`), sql(`UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`), sql(`UPDATE secret_store_occurrence SET slug = $3 WHERE source_id = $1 AND slug = $2 AND commit_sha IS NULL - AND (page_id IS NULL OR page_id IN (SELECT id FROM pages WHERE source_id = $1 AND slug IN ($2, $3)))`), + AND (page_id IN (SELECT id FROM pages WHERE source_id = $1 AND slug IN ($2, $3)) OR (page_id IS NULL + AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug IN ($2, $3) AND ${pageHoldsSql('p', "':' || secret_store_occurrence.entry_id || '>'", true)})))`), ]; for (const statement of statements) { try { diff --git a/src/core/secret-store/backup.ts b/src/core/secret-store/backup.ts index dc3b1bbf29a..5be77025c43 100644 --- a/src/core/secret-store/backup.ts +++ b/src/core/secret-store/backup.ts @@ -137,9 +137,9 @@ export async function backupDue(engine: BrainEngine, backend?: string): Promise< return entries.some(row => row.created_at > last || row.updated_at > last) || occurrences.some(o => o.created_at > last); } -export interface RestoreResult { object: string; key_id: string; inserted: number; existing: number; skipped_no_page: number; unreadable: string[]; occurrences: number } +export interface RestoreResult { object: string; key_id: string; inserted: number; existing: number; skipped_no_page: number; reattached: number; unreadable: string[]; occurrences: number } -export const SKIPPED_NO_PAGE_TEXT = 'skipped because their page is not in this brain (purged, or not synced yet)'; +export const SKIPPED_NO_PAGE_TEXT = 'skipped because no page in this brain holds their marker (purged, or not synced yet)'; export const SKIPPED_NO_PAGE_NEXT = 'Sync the pages, then run the same restore again.'; /** @@ -180,5 +180,5 @@ export async function restoreBackup(engine: BrainEngine, storage: StorageBackend if (body.entries.length && written.skipped_no_page === body.entries.length) { throw opError('invalid_params', `Nothing was restored from ${object}: all ${written.skipped_no_page} entr${written.skipped_no_page === 1 ? 'y was' : 'ies were'} ${SKIPPED_NO_PAGE_TEXT}.`, SKIPPED_NO_PAGE_NEXT); } - return { object, key_id: doc.key_id, inserted: written.entries, existing: verified.length - written.entries - written.skipped_no_page, skipped_no_page: written.skipped_no_page, unreadable, occurrences: written.occurrences }; + return { object, key_id: doc.key_id, inserted: written.entries, existing: verified.length - written.entries - written.skipped_no_page, skipped_no_page: written.skipped_no_page, reattached: written.reattached, unreadable, occurrences: written.occurrences }; } diff --git a/src/core/secret-store/marker-sql.ts b/src/core/secret-store/marker-sql.ts new file mode 100644 index 00000000000..7cdb8ef5afc --- /dev/null +++ b/src/core/secret-store/marker-sql.ts @@ -0,0 +1,18 @@ +/** + * SQL that is true when page `p` (an alias over pages) holds `needle` (a SQL text expression, a marker's `:>`) in a + * field the redactor rewrites: its own columns, its raw data, timeline entries, takes, outgoing link contexts or facts + * (repair/secret-spans.ts reads the same stores). A segmented page keeps its body in segments SQL does not read: with + * `segmented` it counts as holding the marker (a check at one named slug, as secret-store/restore.ts does), and + * without it never does (a search across a source must not match every segmented page). + */ +export function pageHoldsSql(p: string, needle: string, segmented = false): string { + const has = (text: string) => `strpos(${text}, ${needle}) > 0`; + return `(${has(`${p}.title || ' ' || coalesce(${p}.compiled_truth, '') || ' ' || coalesce(${p}.timeline, '') || ' ' || ${p}.frontmatter::text`)} + OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = ${p}.id AND ${has('hr.data::text')}) + OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = ${p}.id OR ht.event_page_id = ${p}.id) AND ${has("ht.summary || ' ' || ht.detail || ' ' || ht.source")}) + OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = ${p}.id AND ${has("coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')")}) + OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = ${p}.id AND ${has('hl.context')}) + OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = ${p}.source_id AND (hf.source_markdown_slug = ${p}.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = ${p}.slug)) + AND ${has("coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')")})${segmented ? ` + OR ${p}.body_storage = 'segmented'` : ''})`; +} diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index 865fd283273..b156d10a0b3 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -13,6 +13,7 @@ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'node:crypto'; import type { BrainEngine } from '../engine.ts'; import { opError } from '../ops/contract.ts'; +import { pageHoldsSql } from './marker-sql.ts'; import { createAuditWriter } from '../audit/audit-writer.ts'; import { currentKey, keyById, keyIdOf, macKeyOf, SECRET_STORE_KEY_ENV, storeHost, keyringDir } from './keyring.ts'; @@ -218,18 +219,21 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac /** * Writes backed-up entries the store does not hold (by id, and never over a row that holds the same value, so a local - * row changed since the backup stays as it is), with the occurrences of the entries it wrote. An occurrence on a page - * (a slug and no commit) comes back only while that page exists in the source, live or soft-deleted; an entry whose - * every occurrence was on pages this brain does not hold is not written (`skipped_no_page`): the page was purged, or is - * not synced yet, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the - * pages, then run the same restore again; it adds what it skipped. An - * occurrence's page_id is the id of the page that holds its slug in the source now, never the backed-up number (a - * rebuilt brain numbers its pages in another order, and the purge cascade trusts page_id); entries of a source this - * brain no longer has are skipped. + * row changed since the backup stays as it is), with the occurrences of the entries it wrote or already holds. A place + * on a page (a slug and no commit) comes back only on a page whose text holds the entry's marker, so a restore never + * ties an original to a page that merely took its old slug. An entry recorded only on pages is written only while some + * page in its source holds its marker; otherwise it is not written (`skipped_no_page`): the page was purged, or is not + * synced yet, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the + * pages, then run the same restore again; it adds what it skipped. When no backed-up slug names a page holding the + * marker (the page was renamed before occurrences moved with it), the entry is tied to every page that holds it + * (`reattached`). An occurrence's page_id is the id of the page that holds its slug now, never the backed-up number + * (a rebuilt brain numbers its pages in another order, and the purge cascade trusts page_id); entries of a source + * this brain no longer has are skipped. */ -export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number }> { - let written = 0, occ = 0, skippedNoPage = 0; +export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number; reattached: number }> { + let written = 0, occ = 0, skippedNoPage = 0, reattached = 0; const onPage = (o: BackupOccurrenceRow) => o.commit_sha === null && o.slug !== null; + const holds = (p: string, segmented = false) => pageHoldsSql(p, "':' || $1 || '>'", segmented); const byEntry = new Map(); for (const o of occurrences) byEntry.set(o.entry_id, [...(byEntry.get(o.entry_id) ?? []), o]); await engine.transaction(async tx => { @@ -239,12 +243,12 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry const anchored = own.length === 0 || own.some(o => !onPage(o)); const inserted = await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2) - AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($14::text[]))) + AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND (${holds('p')} OR (p.slug = ANY($14::text[]) AND ${holds('p', true)})))) ON CONFLICT DO NOTHING RETURNING id`, [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at, anchored, pageSlugs]); if (inserted.length) written++; else { - const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($4::text[])) AS paged + const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND (${holds('p')} OR (p.slug = ANY($4::text[]) AND ${holds('p', true)}))) AS paged FROM (SELECT 1) one LEFT JOIN (SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1) h ON true`, [row.id, row.source_id, row.value_mac, pageSlugs]); if (held!.same === null && !anchored && !held!.paged) skippedNoPage++; if (!held!.same) continue; @@ -252,15 +256,24 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry for (const o of own) { occ += (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,commit_sha,path,line,pre_field_sha256,created_by,created_at) SELECT $1,$2,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz - WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3)) + WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3 AND ${holds('p', true)})) AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x WHERE x.entry_id=$1 AND x.source_id=$2 AND x.slug IS NOT DISTINCT FROM $3 AND x.field=$4 AND x.commit_sha IS NOT DISTINCT FROM $6 AND x.path IS NOT DISTINCT FROM $7 AND x.line IS NOT DISTINCT FROM $8::integer AND x.origin=$5 AND x.pre_field_sha256 IS NOT DISTINCT FROM $9 AND x.created_by=$10 AND date_trunc('milliseconds', x.created_at) = $11::timestamptz) RETURNING 1`, [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at])).length; } + const first = own.find(onPage); + if (!first) continue; + const tied = (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,pre_field_sha256,created_by,created_at) + SELECT $1,$2,p.id,p.slug,$3,$4,$5,$6,$7::timestamptz FROM pages p WHERE p.source_id=$2 AND ${holds('p')} + AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x JOIN pages q ON q.source_id = x.source_id AND q.slug = x.slug + WHERE x.entry_id=$1 AND x.commit_sha IS NULL AND ${holds('q', true)}) RETURNING 1`, + [row.id, row.source_id, first.field, first.origin, first.pre_field_sha256, first.created_by, first.created_at])).length; + occ += tied; + if (tied) reattached++; } }); - return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage }; + return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage, reattached }; } /** diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json index f8820011624..f9e4a4f038d 100644 --- a/test/fixtures/goldens/sql-text/pages.json +++ b/test/fixtures/goldens/sql-text/pages.json @@ -1994,10 +1994,13 @@ "string", "string", "string", + "string", + "string", + "string", "string" ], - "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IS NULL OR page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)))", - "textSha256": "dc82a72d28c14eaf8b2e4848234a3c3ce9b4281001969f91ef6f47a969eb4e3c" + "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug IN ($8, $9) AND (strpos(p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text, ':' || secret_store_occurrence.entry_id || '>') > 0 OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND strpos(hr.data::text, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND strpos(ht.summary || ' ' || ht.detail || ' ' || ht.source, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND strpos(coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, ''), ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND strpos(hl.context, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND strpos(coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, ''), ':' || secret_store_occurrence.entry_id || '>') > 0) OR p.body_storage = 'segmented'))))", + "textSha256": "9115eaacc9d0e74e54d81a088a886f1f1b237a56f565b4cfbcf56cc445eafa63" }, { "event": "savepoint-release", diff --git a/test/secret-store-backup.test.ts b/test/secret-store-backup.test.ts index 218ef7a33f9..c83f3c33ac6 100644 --- a/test/secret-store-backup.test.ts +++ b/test/secret-store-backup.test.ts @@ -13,7 +13,7 @@ import { join } from 'node:path'; import type { BrainEngine } from '../src/core/engine.ts'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { currentKey, escrowExported, exportKeyEscrow, keyringStatus, markEscrowExported } from '../src/core/secret-store/keyring.ts'; -import { recordOccurrence, reveal, seal } from '../src/core/secret-store/store.ts'; +import { markerOf, recordOccurrence, reveal, seal } from '../src/core/secret-store/store.ts'; import { backupDue, backupIfDue, backupStatusFile, backupStore, readBackupStatus, restoreBackup, storageIdentity, BACKUP_OBJECT_PREFIX } from '../src/core/secret-store/backup.ts'; import { createStorage } from '../src/core/storage.ts'; import { runSecrets } from '../src/commands/secrets.ts'; @@ -98,10 +98,10 @@ for (const { name, make } of engines) { expect(await b.engine.executeRaw('SELECT 1 FROM secret_store')).toEqual([]); }); await expect(restoreBackup(b.engine, storage, out.object)).rejects.toMatchObject({ code: 'invalid_params', - message: expect.stringContaining('skipped because their page is not in this brain'), suggestion: 'Sync the pages, then run the same restore again.' }); + message: expect.stringContaining('skipped because no page in this brain holds their marker'), suggestion: 'Sync the pages, then run the same restore again.' }); expect(await b.engine.executeRaw('SELECT 1 FROM secret_store')).toEqual([]); expect(await b.engine.executeRaw('SELECT 1 FROM secret_store_occurrence')).toEqual([]); - await b.engine.putPage('notes/deploy-plan', { type: 'note', title: 'Deploy plan', compiled_truth: 'Deploy notes.', timeline: '', frontmatter: {} }, { sourceId: 'default' }); + await b.engine.putPage('notes/deploy-plan', { type: 'note', title: 'Deploy plan', compiled_truth: `Deploy notes. ${markerOf('github_token', sealed.id)}`, timeline: '', frontmatter: {} }, { sourceId: 'default' }); const restored = await restoreBackup(b.engine, storage, out.object); expect(restored).toMatchObject({ inserted: out.entries, existing: 0, skipped_no_page: 0, unreadable: [] }); expect((await reveal(b.engine, sealed.id, 'test')).value).toBe(TOKEN); diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index edea168fbec..04716f5925d 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -8,7 +8,7 @@ import { describe, expect, test } from 'bun:test'; import { randomUUID } from 'node:crypto'; import { operations } from '../src/core/operations.ts'; import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts'; -import { recordOccurrence, reveal, seal } from '../src/core/secret-store/store.ts'; +import { markerOf, recordOccurrence, reveal, seal } from '../src/core/secret-store/store.ts'; import { scrubPurgedSlugStores } from '../src/core/persistence/purge-slug-stores.ts'; import { backupDue, backupStore, restoreBackup } from '../src/core/secret-store/backup.ts'; import { carryRenameIdentity } from '../src/commands/sync/renames.ts'; @@ -22,17 +22,26 @@ import { testBackends } from './helpers/test-backends.ts'; import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts'; const deleteOp = operations.find(o => o.name === 'delete_page')!; + +/** Records an occurrence the way the redactor does: the page it names (by id, else by slug) holds the entry's marker. */ +async function record(b: BeliefBrain, o: Parameters[1]) { + await recordOccurrence(b.engine, o); + if (o.commit || (!o.pageId && !o.slug)) return; + await b.engine.executeRaw(`UPDATE pages SET compiled_truth = compiled_truth || ' ' || $4 WHERE source_id = $1 AND (id = $2 OR ($2::integer IS NULL AND slug = $3))`, + [o.sourceId, o.pageId ?? null, o.slug ?? null, markerOf('github_token', o.entryId)]); +} const value = (tag: string) => ['ghp', tag.padEnd(36, 'Q')].join('_'); /** Three originals on page `slug`: one only there, one also on `other`, one also recorded on a publish commit. */ -async function seed(b: BeliefBrain, slug: string, other: string) { +async function seed(b: BeliefBrain, slug: string, other: string, marked = false) { + const rec = (o: Parameters[1]) => marked ? record(b, o) : recordOccurrence(b.engine, o); const ids: Record<'only' | 'shared' | 'committed', string> = { only: '', shared: '', committed: '' }; for (const kind of ['only', 'shared', 'committed'] as const) { ids[kind] = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`${kind}${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: ids[kind], sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair', path: `${slug}.md` }); + await rec({ entryId: ids[kind], sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair', path: `${slug}.md` }); } - await recordOccurrence(b.engine, { entryId: ids.shared, sourceId: b.sourceId, slug: other, field: 'compiled_truth', origin: 'repair', path: `${other}.md` }); - await recordOccurrence(b.engine, { entryId: ids.committed, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'publish_rebuild', commit: 'a'.repeat(40), path: `${slug}.md` }); + await rec({ entryId: ids.shared, sourceId: b.sourceId, slug: other, field: 'compiled_truth', origin: 'repair', path: `${other}.md` }); + await rec({ entryId: ids.committed, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'publish_rebuild', commit: 'a'.repeat(40), path: `${slug}.md` }); return ids; } @@ -53,11 +62,11 @@ function expectCascade(s: Awaited>, ids: Record { const brain = (run: (b: BeliefBrain) => Promise) => beliefBrain(run, { databaseUrl: engineCase.databaseUrl, enable: false }); - const pages = async (b: BeliefBrain) => { + const pages = async (b: BeliefBrain, marked = false) => { const slug = `notes/deploy-${randomUUID().slice(0, 6)}`, other = `notes/other-${randomUUID().slice(0, 6)}`; await b.put(slug, beliefPage({ prose: 'Deploy notes.' })); await b.put(other, beliefPage({ prose: 'Other notes.' })); - return { slug, other, ids: await seed(b, slug, other) }; + return { slug, other, ids: await seed(b, slug, other, marked) }; }; test('gbrain delete --purge removes the page\'s occurrences and the original only it referenced; shared and committed originals stay', async () => { @@ -144,7 +153,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-purge-bucket-')); try { const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); - const { slug, ids } = await pages(b); + const { slug, ids } = await pages(b, true); const out = await backupStore(b.engine, storage); await b.engine.executeRaw("UPDATE secret_store SET status = 'allowed', updated_at = now() WHERE id = $1", [ids.shared]); await b.engine.deletePages([slug], { sourceId: b.sourceId }); @@ -189,12 +198,12 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const pageId = async (s: string) => (await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, s]))[0]!.id; const oldId = await pageId(slug); const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`rebuilt${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, pageId: oldId, slug, field: 'compiled_truth', origin: 'repair' }); + await record(b, { entryId: id, sourceId: b.sourceId, pageId: oldId, slug, field: 'compiled_truth', origin: 'repair' }); const out = await backupStore(b.engine, storage); await b.engine.deletePages([slug], { sourceId: b.sourceId }); await b.engine.putPage(unrelated, { type: 'note', title: 'Unrelated', compiled_truth: 'Unrelated.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); await b.engine.executeRaw('UPDATE pages SET id = $3 WHERE source_id = $1 AND slug = $2', [b.sourceId, unrelated, oldId]); - await b.engine.putPage(slug, { type: 'note', title: 'Rebuilt', compiled_truth: 'Rebuilt.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.putPage(slug, { type: 'note', title: 'Rebuilt', compiled_truth: `Rebuilt. ${markerOf('github_token', id)}`, timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ skipped_no_page: 0 }); const [occ] = await b.engine.executeRaw<{ page_id: number | null }>('SELECT page_id FROM secret_store_occurrence WHERE entry_id = $1', [id]); expect(occ!.page_id).toBe(await pageId(slug)); @@ -209,7 +218,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-existing-bucket-')); try { const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); - const { slug, other, ids } = await pages(b); + const { slug, other, ids } = await pages(b, true); const out = await backupStore(b.engine, storage); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1 AND slug = $2', [ids.shared, other]); const restored = await restoreBackup(b.engine, storage, out.object); @@ -270,8 +279,8 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const slug = `notes/two-${randomUUID().slice(0, 6)}`; await b.put(slug, beliefPage({ prose: 'Two records.' })); const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`two${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair', path: `${slug}.md` }); - await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'publish_rebuild', path: `${slug}.md` }); + await record(b, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair', path: `${slug}.md` }); + await record(b, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'publish_rebuild', path: `${slug}.md` }); const out = await backupStore(b.engine, storage); expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 0, occurrences: 0 }); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); @@ -292,7 +301,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`rs${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair' }); + await record(b, { entryId: id, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair' }); const out = await backupStore(b.engine, storage); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); await b.engine.executeRaw('UPDATE secret_store SET id = $2 WHERE id = $1', [id, `ss_${'f'.repeat(12)}`]); @@ -306,7 +315,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-rename-due-')); try { const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); - const { slug } = await pages(b); + const { slug } = await pages(b, true); await backupStore(b.engine, storage); expect(await backupDue(b.engine)).toBe(false); await b.engine.updateSlug(slug, `notes/renamed-${randomUUID().slice(0, 6)}`, { sourceId: b.sourceId }); @@ -326,7 +335,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`or${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, pageId: page!.id, slug: first, field: 'compiled_truth', origin: 'repair' }); + await record(b, { entryId: id, sourceId: b.sourceId, pageId: page!.id, slug: first, field: 'compiled_truth', origin: 'repair' }); await b.engine.updateSlug(now, last, { sourceId: b.sourceId }); const out = await backupStore(b.engine, storage); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); @@ -354,6 +363,59 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); + test('a restore never ties an original to a page that took its old slug without its marker; it ties it to the page that holds the marker', async () => { + await brain(async b => { + const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-reused-slug-')); + try { + const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); + const foo = `notes/foo-${randomUUID().slice(0, 6)}`, bar = `notes/bar-${randomUUID().slice(0, 6)}`; + await b.engine.putPage(foo, { type: 'note', title: 'Owner', compiled_truth: 'Owner.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + const [page] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, foo]); + const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`ru${randomUUID().slice(0, 6)}`) })).id; + await record(b, { entryId: id, sourceId: b.sourceId, pageId: page!.id, slug: foo, field: 'compiled_truth', origin: 'repair' }); + const out = await backupStore(b.engine, storage); + await b.engine.updateSlug(foo, bar, { sourceId: b.sourceId }); + await b.engine.putPage(foo, { type: 'note', title: 'Unrelated', compiled_truth: 'Took the old slug.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE id = $1', [id]); + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 0, reattached: 1 }); + expect(await b.engine.executeRaw('SELECT slug, page_id FROM secret_store_occurrence WHERE entry_id = $1', [id])).toEqual([{ slug: bar, page_id: page!.id }]); + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 0, occurrences: 0, reattached: 0 }); + } finally { rmSync(bucket, { recursive: true, force: true }); } + }); + }, 120_000); + + test('a backup that names a page by a slug it had before an older rename restores onto the page holding the marker', async () => { + await brain(async b => { + const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-old-backup-')); + try { + const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); + const first = `notes/first-${randomUUID().slice(0, 6)}`, now = `notes/now-${randomUUID().slice(0, 6)}`; + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`ob${randomUUID().slice(0, 6)}`) })).id; + await b.engine.putPage(now, { type: 'note', title: 'Renamed', compiled_truth: `Renamed long ago. ${markerOf('github_token', id)}`, timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug: first, field: 'compiled_truth', origin: 'repair' }); + const out = await backupStore(b.engine, storage); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE id = $1', [id]); + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 0, reattached: 1 }); + expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [id])).map(r => r.slug)).toEqual([now]); + } finally { rmSync(bucket, { recursive: true, force: true }); } + }); + }, 120_000); + + test('a rename leaves an occurrence with no page under the old slug when the renamed page does not hold its marker', async () => { + await brain(async b => { + const from = `notes/from-${randomUUID().slice(0, 6)}`, to = `notes/to-${randomUUID().slice(0, 6)}`; + await b.engine.putPage(from, { type: 'note', title: 'Took the slug', compiled_truth: 'No marker here.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + const leftover = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`lo${randomUUID().slice(0, 6)}`) })).id; + await recordOccurrence(b.engine, { entryId: leftover, sourceId: b.sourceId, slug: from, field: 'compiled_truth', origin: 'repair' }); + await b.engine.updateSlug(from, to, { sourceId: b.sourceId }); + expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [leftover])).map(r => r.slug)).toEqual([from]); + }); + }, 120_000); + test('a rename that fails partway leaves the page and its secret occurrences where they were', async () => { await brain(async b => { const foo = `notes/foo-${randomUUID().slice(0, 6)}`, bar = `notes/bar-${randomUUID().slice(0, 6)}`; From bb0754bfed9a7326be9174ce43968df65a7c5d39 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 09:49:17 +0000 Subject: [PATCH 30/37] A restore ties a place only at its backed-up slug, by the full marker, and never undoes a racing purge Review round 1: tying an old-backup entry to every page holding the marker would bind a copied marker, so that path is gone and a stale-slug entry is skipped. The marker check matches a whole marker, the rename's page-less branch checks only the page at the new slug, and an entry whose places all failed to land is taken back out. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/secret-restore-marker.md | 9 ++-- docs/guides/secret-store.md | 14 +++--- scripts/engine-raw-sql-baseline.tsv | 2 +- scripts/page-body-readers-baseline.tsv | 2 +- src/commands/secrets.ts | 1 - src/core/page-state/rename-alias.ts | 4 +- src/core/secret-store/backup.ts | 4 +- src/core/secret-store/marker-sql.ts | 18 ++++---- src/core/secret-store/store.ts | 46 +++++++++----------- test/fixtures/goldens/sql-text/pages.json | 5 +-- test/secret-store-purge.test.ts | 52 +++++++++++++++++++---- 11 files changed, 94 insertions(+), 63 deletions(-) diff --git a/changelog.d/secret-restore-marker.md b/changelog.d/secret-restore-marker.md index 043d31bc815..f21c41918d1 100644 --- a/changelog.d/secret-restore-marker.md +++ b/changelog.d/secret-restore-marker.md @@ -1,9 +1,10 @@ --- important: security --- -**A secret store restore ties an original only to a page that still holds its marker.** +**A secret store restore ties an original only to the page at its backed-up slug, and only when that page still holds its marker.** ### Fixed -- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug, so that page's readers never pass the `reveal_secret` read check for it. A place comes back only on a page whose text holds the entry's marker. -- A backup that names a page by a slug it had before a rename now ties the entry to the pages that hold its marker (counted as `reattached`), or skips it when none does (`skipped_no_page`), so a restore never brings back what a purge removed. This replaces the 0.60.744.0 note saying such an entry would be restored without a place. -- A rename no longer moves a leftover place with no page onto the renamed page unless that page holds its marker. +- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug, or to a page that quotes its id, so that page's readers never pass the `reveal_secret` read check for it. +- A backup that names a page by a slug it had before a rename (one taken before 0.60.744.0) skips that entry (`skipped_no_page`) instead of tying it to another page, and a restore never brings back what a purge removed. This replaces the 0.60.744.0 note saying such an entry would be restored without a place. +- A restore that loses the race with a purge of the same page no longer leaves the sealed original behind. +- A rename no longer moves a leftover place with no page onto the renamed page unless the page now at the new slug holds its marker. diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index 6cd3c546d6d..d1d269824fe 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -131,13 +131,13 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t a host whose keyring holds the key the backup names (import the escrow copy first), and it skips, and lists, any row that does not authenticate under it. An entry already here is left as it is, even when the backup's copy differs; the places the backup recorded for it that this brain lacks are added, so a later purge of one page never removes an - original another page still holds. A restore only adds rows and never deletes one, and it ties each restored place - only to a page whose text holds the entry's marker: the page at the backed-up slug when that page holds it, and - otherwise every page in the source that does (counted as `reattached`: the page was renamed before the backup named - it by its current slug). A page that merely took an old slug never gets the original. A page whose body is stored in segments - counts as holding the marker at its backed-up slug, and is never found by the search across the source. - An original recorded only on pages, none of which in this brain holds its marker, is skipped and counted as - `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, or is not synced yet, + original another page still holds. A restore only adds rows and never deletes one it did not write, and it ties a restored place to + the page at its backed-up slug only when that page holds the entry's marker (`:>`), so a page + that merely took an old slug, or quotes the id, never gets the original, and neither does another page a copy of + the marker sits on. A page whose body is stored in segments, which the check cannot read, counts as holding it. + An original recorded only on pages, none of which at its backed-up slugs holds its marker, is skipped and counted as + `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, is not synced + yet, or was renamed before the backup named it by its current slug (a backup from before 0.60.744.0), and a restore cannot tell which, so it never brings back what a page purge removed. Sync the pages, then run the same restore again; it adds what it skipped. When every entry is skipped that way (a rebuilt brain before sync), the restore refuses with `invalid_params` and writes nothing, so a script never reads it as finished. diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv index ff233e2e36a..0c3d06df77e 100644 --- a/scripts/engine-raw-sql-baseline.tsv +++ b/scripts/engine-raw-sql-baseline.tsv @@ -1100,7 +1100,7 @@ src/core/search/transcript-quote.ts execute_raw 3 src/core/search/two-pass.ts execute_raw 5 src/core/secret-store/restore.ts execute_raw 3 secret restore reads the page revision and live knowledge_revision and flips secret_store.status; no typed engine method for the secret store exists yet src/core/secret-store/spool.ts execute_raw 1 GST-2988 PR 2 spool: reads every allowed (restored) key_id and value_mac from secret_store to rebuild allowed.json; branched before the #9641 ratchet; no typed engine method for the secret store exists yet -src/core/secret-store/store.ts execute_raw 23 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +1: restore ties an entry whose backed-up slugs name no page holding its marker to the pages that hold it; all move behind typed engine methods with the rest after gbrain#9694 +src/core/secret-store/store.ts execute_raw 23 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +1: restore takes back out an entry it wrote whose every place failed to land because its page was purged while the restore ran; all move behind typed engine methods with the rest after gbrain#9694 src/core/serve-sync-runner.ts execute_raw 1 src/core/session-lane.ts execute_raw 3 src/core/shared-skills/adopted-packs.ts execute_raw 1 diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv index 7cb249b40f2..a8e4f6b0c9e 100644 --- a/scripts/page-body-readers-baseline.tsv +++ b/scripts/page-body-readers-baseline.tsv @@ -664,7 +664,7 @@ src/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBod src/core/search/safe-chunks.ts bodyWriteChunkVersion sql SEGW spliced into inline body writes only; a segmented row refuses those writes (CHECK) src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) src/core/search/safe-chunks.ts protectedTakesFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) -src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit at a named slug and never in a search across a source +src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL for the page at one named slug; a segmented page counts as a hit src/core/secret-store/restore.ts previewRestore sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit and the apply reads it whole src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE src/core/shared-skills/migration-export.ts exportInventory field INLINE diff --git a/src/commands/secrets.ts b/src/commands/secrets.ts index ed9a6793abb..2955318123e 100644 --- a/src/commands/secrets.ts +++ b/src/commands/secrets.ts @@ -136,7 +136,6 @@ export async function runSecrets(engine: BrainEngine, args: string[]): Promise, * caller's rename transaction. The new slug is free (the page UPDATE * succeeded), so fence rows or aliases still keyed to it belong to a purged * page and yield to the moved ones. A secret occurrence moves only when it is the renamed page's own (its - * page_id is that page or the stale row a fallback rename retires, or it has none and the page holds its marker): an occurrence another page holds under + * page_id is that page or the stale row a fallback rename retires, or it has none and the page now at the new slug holds its marker): an occurrence another page holds under * an older slug stays with that page. An ontology observation the new slug * already holds is dropped before its key moves (B-10, dropRekeyDuplicates). * A brain whose schema predates the facts or alias tables skips them inside a @@ -110,7 +110,7 @@ export async function moveSlugBindings( sql(`UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`), sql(`UPDATE secret_store_occurrence SET slug = $3 WHERE source_id = $1 AND slug = $2 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $1 AND slug IN ($2, $3)) OR (page_id IS NULL - AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug IN ($2, $3) AND ${pageHoldsSql('p', "':' || secret_store_occurrence.entry_id || '>'", true)})))`), + AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $3 AND ${pageHoldsSql('p', 'secret_store_occurrence.entry_id')})))`), ]; for (const statement of statements) { try { diff --git a/src/core/secret-store/backup.ts b/src/core/secret-store/backup.ts index 5be77025c43..826dd3a3206 100644 --- a/src/core/secret-store/backup.ts +++ b/src/core/secret-store/backup.ts @@ -137,7 +137,7 @@ export async function backupDue(engine: BrainEngine, backend?: string): Promise< return entries.some(row => row.created_at > last || row.updated_at > last) || occurrences.some(o => o.created_at > last); } -export interface RestoreResult { object: string; key_id: string; inserted: number; existing: number; skipped_no_page: number; reattached: number; unreadable: string[]; occurrences: number } +export interface RestoreResult { object: string; key_id: string; inserted: number; existing: number; skipped_no_page: number; unreadable: string[]; occurrences: number } export const SKIPPED_NO_PAGE_TEXT = 'skipped because no page in this brain holds their marker (purged, or not synced yet)'; export const SKIPPED_NO_PAGE_NEXT = 'Sync the pages, then run the same restore again.'; @@ -180,5 +180,5 @@ export async function restoreBackup(engine: BrainEngine, storage: StorageBackend if (body.entries.length && written.skipped_no_page === body.entries.length) { throw opError('invalid_params', `Nothing was restored from ${object}: all ${written.skipped_no_page} entr${written.skipped_no_page === 1 ? 'y was' : 'ies were'} ${SKIPPED_NO_PAGE_TEXT}.`, SKIPPED_NO_PAGE_NEXT); } - return { object, key_id: doc.key_id, inserted: written.entries, existing: verified.length - written.entries - written.skipped_no_page, skipped_no_page: written.skipped_no_page, reattached: written.reattached, unreadable, occurrences: written.occurrences }; + return { object, key_id: doc.key_id, inserted: written.entries, existing: verified.length - written.entries - written.skipped_no_page, skipped_no_page: written.skipped_no_page, unreadable, occurrences: written.occurrences }; } diff --git a/src/core/secret-store/marker-sql.ts b/src/core/secret-store/marker-sql.ts index 7cdb8ef5afc..f0799f53693 100644 --- a/src/core/secret-store/marker-sql.ts +++ b/src/core/secret-store/marker-sql.ts @@ -1,18 +1,18 @@ /** - * SQL that is true when page `p` (an alias over pages) holds `needle` (a SQL text expression, a marker's `:>`) in a - * field the redactor rewrites: its own columns, its raw data, timeline entries, takes, outgoing link contexts or facts - * (repair/secret-spans.ts reads the same stores). A segmented page keeps its body in segments SQL does not read: with - * `segmented` it counts as holding the marker (a check at one named slug, as secret-store/restore.ts does), and - * without it never does (a search across a source must not match every segmented page). + * SQL that is true when page `p` (an alias over pages) holds a store marker for entry `idExpr` (a SQL text expression + * naming an `ss_` id): `:>` in a field the redactor rewrites, its own columns, its raw data, + * timeline entries, takes, outgoing link contexts or facts (repair/secret-spans.ts reads the same stores). A page whose + * body is stored in segments, which SQL does not read, counts as holding it, as in secret-store/restore.ts; callers + * ask only about the page at one named slug. */ -export function pageHoldsSql(p: string, needle: string, segmented = false): string { - const has = (text: string) => `strpos(${text}, ${needle}) > 0`; +export function pageHoldsSql(p: string, idExpr: string): string { + const has = (text: string) => `(${text}) ~ ('')`; return `(${has(`${p}.title || ' ' || coalesce(${p}.compiled_truth, '') || ' ' || coalesce(${p}.timeline, '') || ' ' || ${p}.frontmatter::text`)} + OR ${p}.body_storage = 'segmented' OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = ${p}.id AND ${has('hr.data::text')}) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = ${p}.id OR ht.event_page_id = ${p}.id) AND ${has("ht.summary || ' ' || ht.detail || ' ' || ht.source")}) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = ${p}.id AND ${has("coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')")}) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = ${p}.id AND ${has('hl.context')}) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = ${p}.source_id AND (hf.source_markdown_slug = ${p}.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = ${p}.slug)) - AND ${has("coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')")})${segmented ? ` - OR ${p}.body_storage = 'segmented'` : ''})`; + AND ${has("coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')")}))`; } diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index b156d10a0b3..e33f222db3c 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -220,20 +220,20 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac /** * Writes backed-up entries the store does not hold (by id, and never over a row that holds the same value, so a local * row changed since the backup stays as it is), with the occurrences of the entries it wrote or already holds. A place - * on a page (a slug and no commit) comes back only on a page whose text holds the entry's marker, so a restore never - * ties an original to a page that merely took its old slug. An entry recorded only on pages is written only while some - * page in its source holds its marker; otherwise it is not written (`skipped_no_page`): the page was purged, or is not - * synced yet, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the - * pages, then run the same restore again; it adds what it skipped. When no backed-up slug names a page holding the - * marker (the page was renamed before occurrences moved with it), the entry is tied to every page that holds it - * (`reattached`). An occurrence's page_id is the id of the page that holds its slug now, never the backed-up number - * (a rebuilt brain numbers its pages in another order, and the purge cascade trusts page_id); entries of a source - * this brain no longer has are skipped. + * on a page (a slug and no commit) comes back only when the page at that slug holds the entry's marker, so a restore + * never ties an original to a page that merely took its old slug, or to another page a copy of its marker sits on. An + * entry recorded only on pages is written only while one of those pages holds its marker, and an entry whose places + * all failed to land (its page purged while the restore ran) is taken back out; otherwise it is not written + * (`skipped_no_page`): the page was purged, is not synced yet, or was renamed before the backup named it by its + * current slug, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the + * pages, then run the same restore again; it adds what it skipped. An occurrence's page_id is the id of the page that + * holds its slug now, never the backed-up number (a rebuilt brain numbers its pages in another order, and the purge + * cascade trusts page_id); entries of a source this brain no longer has are skipped. */ -export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number; reattached: number }> { - let written = 0, occ = 0, skippedNoPage = 0, reattached = 0; +export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number }> { + let written = 0, occ = 0, skippedNoPage = 0; const onPage = (o: BackupOccurrenceRow) => o.commit_sha === null && o.slug !== null; - const holds = (p: string, segmented = false) => pageHoldsSql(p, "':' || $1 || '>'", segmented); + const holds = (p: string) => pageHoldsSql(p, '$1'); const byEntry = new Map(); for (const o of occurrences) byEntry.set(o.entry_id, [...(byEntry.get(o.entry_id) ?? []), o]); await engine.transaction(async tx => { @@ -243,12 +243,12 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry const anchored = own.length === 0 || own.some(o => !onPage(o)); const inserted = await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2) - AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND (${holds('p')} OR (p.slug = ANY($14::text[]) AND ${holds('p', true)})))) + AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($14::text[]) AND ${holds('p')})) ON CONFLICT DO NOTHING RETURNING id`, [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at, anchored, pageSlugs]); if (inserted.length) written++; else { - const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND (${holds('p')} OR (p.slug = ANY($4::text[]) AND ${holds('p', true)}))) AS paged + const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($4::text[]) AND ${holds('p')}) AS paged FROM (SELECT 1) one LEFT JOIN (SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1) h ON true`, [row.id, row.source_id, row.value_mac, pageSlugs]); if (held!.same === null && !anchored && !held!.paged) skippedNoPage++; if (!held!.same) continue; @@ -256,24 +256,20 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry for (const o of own) { occ += (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,commit_sha,path,line,pre_field_sha256,created_by,created_at) SELECT $1,$2,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz - WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3 AND ${holds('p', true)})) + WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3 AND ${holds('p')})) AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x WHERE x.entry_id=$1 AND x.source_id=$2 AND x.slug IS NOT DISTINCT FROM $3 AND x.field=$4 AND x.commit_sha IS NOT DISTINCT FROM $6 AND x.path IS NOT DISTINCT FROM $7 AND x.line IS NOT DISTINCT FROM $8::integer AND x.origin=$5 AND x.pre_field_sha256 IS NOT DISTINCT FROM $9 AND x.created_by=$10 AND date_trunc('milliseconds', x.created_at) = $11::timestamptz) RETURNING 1`, [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at])).length; } - const first = own.find(onPage); - if (!first) continue; - const tied = (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,pre_field_sha256,created_by,created_at) - SELECT $1,$2,p.id,p.slug,$3,$4,$5,$6,$7::timestamptz FROM pages p WHERE p.source_id=$2 AND ${holds('p')} - AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x JOIN pages q ON q.source_id = x.source_id AND q.slug = x.slug - WHERE x.entry_id=$1 AND x.commit_sha IS NULL AND ${holds('q', true)}) RETURNING 1`, - [row.id, row.source_id, first.field, first.origin, first.pre_field_sha256, first.created_by, first.created_at])).length; - occ += tied; - if (tied) reattached++; + if (!inserted.length || anchored) continue; + if ((await tx.executeRaw('DELETE FROM secret_store s WHERE s.id=$1 AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.entry_id=s.id) RETURNING 1', [row.id])).length) { + written--; + skippedNoPage++; + } } }); - return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage, reattached }; + return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage }; } /** diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json index f9e4a4f038d..18f699f1fa7 100644 --- a/test/fixtures/goldens/sql-text/pages.json +++ b/test/fixtures/goldens/sql-text/pages.json @@ -1996,11 +1996,10 @@ "string", "string", "string", - "string", "string" ], - "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug IN ($8, $9) AND (strpos(p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text, ':' || secret_store_occurrence.entry_id || '>') > 0 OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND strpos(hr.data::text, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND strpos(ht.summary || ' ' || ht.detail || ' ' || ht.source, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND strpos(coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, ''), ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND strpos(hl.context, ':' || secret_store_occurrence.entry_id || '>') > 0) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND strpos(coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, ''), ':' || secret_store_occurrence.entry_id || '>') > 0) OR p.body_storage = 'segmented'))))", - "textSha256": "9115eaacc9d0e74e54d81a088a886f1f1b237a56f565b4cfbcf56cc445eafa63" + "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug = $8 AND ((p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text) ~ ('') OR p.body_storage = 'segmented' OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND (hr.data::text) ~ ('')) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND (ht.summary || ' ' || ht.detail || ' ' || ht.source) ~ ('')) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND (coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')) ~ ('')) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND (hl.context) ~ ('')) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND (coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')) ~ (''))))))", + "textSha256": "46adadccf552b92a71f417ce5fd00cc2dc7b6bd3f2230bfa001bc19555ca3c85" }, { "event": "savepoint-release", diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index 04716f5925d..b0405801fb6 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -363,7 +363,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); - test('a restore never ties an original to a page that took its old slug without its marker; it ties it to the page that holds the marker', async () => { + test('a restore never ties an original to a page that took its old slug, even one quoting the entry id, and skips it', async () => { await brain(async b => { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-reused-slug-')); try { @@ -375,17 +375,17 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { await record(b, { entryId: id, sourceId: b.sourceId, pageId: page!.id, slug: foo, field: 'compiled_truth', origin: 'repair' }); const out = await backupStore(b.engine, storage); await b.engine.updateSlug(foo, bar, { sourceId: b.sourceId }); - await b.engine.putPage(foo, { type: 'note', title: 'Unrelated', compiled_truth: 'Took the old slug.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.putPage(foo, { type: 'note', title: 'Unrelated', compiled_truth: `Took the old slug; see :${id}> and ${id}.`, timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); await b.engine.executeRaw('DELETE FROM secret_store WHERE id = $1', [id]); - expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 0, reattached: 1 }); - expect(await b.engine.executeRaw('SELECT slug, page_id FROM secret_store_occurrence WHERE entry_id = $1', [id])).toEqual([{ slug: bar, page_id: page!.id }]); - expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 0, occurrences: 0, reattached: 0 }); + await expect(restoreBackup(b.engine, storage, out.object)).rejects.toMatchObject({ code: 'invalid_params' }); + expect(await b.engine.executeRaw('SELECT 1 FROM secret_store_occurrence WHERE entry_id = $1', [id])).toEqual([]); + expect(await b.engine.executeRaw('SELECT 1 FROM secret_store WHERE id = $1', [id])).toEqual([]); } finally { rmSync(bucket, { recursive: true, force: true }); } }); }, 120_000); - test('a backup that names a page by a slug it had before an older rename restores onto the page holding the marker', async () => { + test('a backup that names a page by a slug it had before an older rename skips that entry, and never ties it to the page holding the marker', async () => { await brain(async b => { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-old-backup-')); try { @@ -399,8 +399,8 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { const out = await backupStore(b.engine, storage); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE entry_id = $1', [id]); await b.engine.executeRaw('DELETE FROM secret_store WHERE id = $1', [id]); - expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 0, reattached: 1 }); - expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [id])).map(r => r.slug)).toEqual([now]); + await expect(restoreBackup(b.engine, storage, out.object)).rejects.toMatchObject({ code: 'invalid_params' }); + expect(await b.engine.executeRaw('SELECT 1 FROM secret_store_occurrence WHERE entry_id = $1', [id])).toEqual([]); } finally { rmSync(bucket, { recursive: true, force: true }); } }); }, 120_000); @@ -416,6 +416,42 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); + test('a page stored in segments counts as holding the marker at a backed-up slug, and a segmented page elsewhere never does', async () => { + await brain(async b => { + const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-segmented-')); + try { + const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); + const seg = `notes/segmented-${randomUUID().slice(0, 6)}`, gone = `notes/gone-${randomUUID().slice(0, 6)}`, other = `notes/other-seg-${randomUUID().slice(0, 6)}`; + for (const slug of [seg, other]) await b.engine.putPage(slug, { type: 'note', title: 'Long', compiled_truth: 'Long page.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.executeRaw("UPDATE pages SET body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_bytes = 10 WHERE source_id = $1 AND slug = ANY($2::text[])", [b.sourceId, [seg, other]]); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + const atSlug = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`sg${randomUUID().slice(0, 6)}`) })).id; + const nowhere = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`nw${randomUUID().slice(0, 6)}`) })).id; + await recordOccurrence(b.engine, { entryId: atSlug, sourceId: b.sourceId, slug: seg, field: 'compiled_truth', origin: 'repair' }); + await recordOccurrence(b.engine, { entryId: nowhere, sourceId: b.sourceId, slug: gone, field: 'compiled_truth', origin: 'repair' }); + const out = await backupStore(b.engine, storage); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 1 }); + expect(await b.engine.executeRaw('SELECT entry_id, slug FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId])).toEqual([{ entry_id: atSlug, slug: seg }]); + expect(await b.engine.executeRaw('SELECT id FROM secret_store WHERE id = $1', [nowhere])).toEqual([]); + } finally { rmSync(bucket, { recursive: true, force: true }); } + }); + }, 120_000); + + test('a fallback rename leaves a place with no page under the stale slug when only the stale row, not the new one, holds its marker', async () => { + await brain(async b => { + const stale = 'notes/stale-' + randomUUID().slice(0, 6), dest = 'notes/dest-' + randomUUID().slice(0, 6); + const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('fr' + randomUUID().slice(0, 6)) })).id; + await b.engine.putPage(stale, { type: 'note', title: 'Old body', compiled_truth: 'Old body ' + markerOf('github_token', id), timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.putPage(dest, { type: 'note', title: 'New body', compiled_truth: 'New body without it.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug: stale, field: 'compiled_truth', origin: 'repair' }); + await carryRenameIdentity(b.engine, b.sourceId, stale, dest); + expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [id])).map(r => r.slug)).toEqual([stale]); + }); + }, 120_000); + test('a rename that fails partway leaves the page and its secret occurrences where they were', async () => { await brain(async b => { const foo = `notes/foo-${randomUUID().slice(0, 6)}`, bar = `notes/bar-${randomUUID().slice(0, 6)}`; From 5d56218208c51f78da44d3835580f772300637b3 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 10:07:45 +0000 Subject: [PATCH 31/37] A restore reads a segmented page's segments for the marker instead of trusting any segmented page /ship review: treating every page stored in segments as holding every marker let a restore tie an original to a large page that took its old slug. Restore now reads that page's segments; the rename's page-less branch counts only what SQL reads. Tests cover a marker in segments, frontmatter, raw data and a timeline entry. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- docs/guides/secret-store.md | 2 +- scripts/engine-raw-sql-baseline.tsv | 2 +- scripts/page-body-readers-baseline.tsv | 2 +- src/core/page-state/rename-alias.ts | 2 +- src/core/secret-store/marker-sql.ts | 8 ++-- src/core/secret-store/store.ts | 48 +++++++++++++++++------ test/fixtures/goldens/sql-text/pages.json | 4 +- test/secret-store-purge.test.ts | 29 ++++++++------ 8 files changed, 63 insertions(+), 34 deletions(-) diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index d1d269824fe..13f2b8821df 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -134,7 +134,7 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t original another page still holds. A restore only adds rows and never deletes one it did not write, and it ties a restored place to the page at its backed-up slug only when that page holds the entry's marker (`:>`), so a page that merely took an old slug, or quotes the id, never gets the original, and neither does another page a copy of - the marker sits on. A page whose body is stored in segments, which the check cannot read, counts as holding it. + the marker sits on. A page whose body is stored in segments is read segment by segment. An original recorded only on pages, none of which at its backed-up slugs holds its marker, is skipped and counted as `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, is not synced yet, or was renamed before the backup named it by its current slug (a backup from before 0.60.744.0), diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv index 0c3d06df77e..0ea6ef625b6 100644 --- a/scripts/engine-raw-sql-baseline.tsv +++ b/scripts/engine-raw-sql-baseline.tsv @@ -1100,7 +1100,7 @@ src/core/search/transcript-quote.ts execute_raw 3 src/core/search/two-pass.ts execute_raw 5 src/core/secret-store/restore.ts execute_raw 3 secret restore reads the page revision and live knowledge_revision and flips secret_store.status; no typed engine method for the secret store exists yet src/core/secret-store/spool.ts execute_raw 1 GST-2988 PR 2 spool: reads every allowed (restored) key_id and value_mac from secret_store to rebuild allowed.json; branched before the #9641 ratchet; no typed engine method for the secret store exists yet -src/core/secret-store/store.ts execute_raw 23 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +1: restore takes back out an entry it wrote whose every place failed to land because its page was purged while the restore ran; all move behind typed engine methods with the rest after gbrain#9694 +src/core/secret-store/store.ts execute_raw 24 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +2: restore reads which backed-up slugs name a page holding the marker, and takes back out an entry it wrote whose every place failed to land because its page was purged while the restore ran; all move behind typed engine methods with the rest after gbrain#9694 src/core/serve-sync-runner.ts execute_raw 1 src/core/session-lane.ts execute_raw 3 src/core/shared-skills/adopted-packs.ts execute_raw 1 diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv index a8e4f6b0c9e..20bf5b3ab61 100644 --- a/scripts/page-body-readers-baseline.tsv +++ b/scripts/page-body-readers-baseline.tsv @@ -664,7 +664,7 @@ src/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBod src/core/search/safe-chunks.ts bodyWriteChunkVersion sql SEGW spliced into inline body writes only; a segmented row refuses those writes (CHECK) src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) src/core/search/safe-chunks.ts protectedTakesFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) -src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL for the page at one named slug; a segmented page counts as a hit +src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL; a segmented body is not read here, and restore reads its segments through readSegmentedBody src/core/secret-store/restore.ts previewRestore sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit and the apply reads it whole src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE src/core/shared-skills/migration-export.ts exportInventory field INLINE diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.ts index 558701f7472..dd8db77b571 100644 --- a/src/core/page-state/rename-alias.ts +++ b/src/core/page-state/rename-alias.ts @@ -82,7 +82,7 @@ export async function recordSlugLineAlias(tx: Pick, * caller's rename transaction. The new slug is free (the page UPDATE * succeeded), so fence rows or aliases still keyed to it belong to a purged * page and yield to the moved ones. A secret occurrence moves only when it is the renamed page's own (its - * page_id is that page or the stale row a fallback rename retires, or it has none and the page now at the new slug holds its marker): an occurrence another page holds under + * page_id is that page or the stale row a fallback rename retires, or it has none and the page now at the new slug holds its marker where SQL reads it): an occurrence another page holds under * an older slug stays with that page. An ontology observation the new slug * already holds is dropped before its key moves (B-10, dropRekeyDuplicates). * A brain whose schema predates the facts or alias tables skips them inside a diff --git a/src/core/secret-store/marker-sql.ts b/src/core/secret-store/marker-sql.ts index f0799f53693..7116c791e6c 100644 --- a/src/core/secret-store/marker-sql.ts +++ b/src/core/secret-store/marker-sql.ts @@ -1,14 +1,12 @@ /** * SQL that is true when page `p` (an alias over pages) holds a store marker for entry `idExpr` (a SQL text expression - * naming an `ss_` id): `:>` in a field the redactor rewrites, its own columns, its raw data, - * timeline entries, takes, outgoing link contexts or facts (repair/secret-spans.ts reads the same stores). A page whose - * body is stored in segments, which SQL does not read, counts as holding it, as in secret-store/restore.ts; callers - * ask only about the page at one named slug. + * naming an `ss_` id): `:>` in its inline columns, its raw data, timeline entries, takes, outgoing + * link contexts or facts (repair/secret-spans.ts reads the same stores). A body stored in segments is not read here, + * so a segmented page holds a marker in SQL only through those other stores; insertBackupRows reads its segments. */ export function pageHoldsSql(p: string, idExpr: string): string { const has = (text: string) => `(${text}) ~ ('')`; return `(${has(`${p}.title || ' ' || coalesce(${p}.compiled_truth, '') || ' ' || coalesce(${p}.timeline, '') || ' ' || ${p}.frontmatter::text`)} - OR ${p}.body_storage = 'segmented' OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = ${p}.id AND ${has('hr.data::text')}) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = ${p}.id OR ht.event_page_id = ${p}.id) AND ${has("ht.summary || ' ' || ht.detail || ' ' || ht.source")}) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = ${p}.id AND ${has("coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')")}) diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index e33f222db3c..b2a661fee56 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -14,6 +14,7 @@ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'node: import type { BrainEngine } from '../engine.ts'; import { opError } from '../ops/contract.ts'; import { pageHoldsSql } from './marker-sql.ts'; +import { readSegmentedBody } from '../page-body/ingest.ts'; import { createAuditWriter } from '../audit/audit-writer.ts'; import { currentKey, keyById, keyIdOf, macKeyOf, SECRET_STORE_KEY_ENV, storeHost, keyringDir } from './keyring.ts'; @@ -220,7 +221,8 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac /** * Writes backed-up entries the store does not hold (by id, and never over a row that holds the same value, so a local * row changed since the backup stays as it is), with the occurrences of the entries it wrote or already holds. A place - * on a page (a slug and no commit) comes back only when the page at that slug holds the entry's marker, so a restore + * on a page (a slug and no commit) comes back only when the page at that slug holds the entry's marker (its segments + * read when its body is stored in segments), so a restore * never ties an original to a page that merely took its old slug, or to another page a copy of its marker sits on. An * entry recorded only on pages is written only while one of those pages holds its marker, and an entry whose places * all failed to land (its page purged while the restore ran) is taken back out; otherwise it is not written @@ -233,34 +235,31 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number }> { let written = 0, occ = 0, skippedNoPage = 0; const onPage = (o: BackupOccurrenceRow) => o.commit_sha === null && o.slug !== null; - const holds = (p: string) => pageHoldsSql(p, '$1'); const byEntry = new Map(); for (const o of occurrences) byEntry.set(o.entry_id, [...(byEntry.get(o.entry_id) ?? []), o]); await engine.transaction(async tx => { for (const row of entries) { const own = byEntry.get(row.id) ?? []; - const pageSlugs = [...new Set(own.filter(onPage).map(o => o.slug as string))]; const anchored = own.length === 0 || own.some(o => !onPage(o)); - const inserted = await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) + const holding = await holdingSlugs(tx, row.source_id, [...new Set(own.filter(onPage).map(o => o.slug as string))], row.id); + const inserted = anchored || holding.length ? await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2) - AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($14::text[]) AND ${holds('p')})) ON CONFLICT DO NOTHING RETURNING id`, - [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at, anchored, pageSlugs]); + [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at]) : []; if (inserted.length) written++; else { - const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($4::text[]) AND ${holds('p')}) AS paged - FROM (SELECT 1) one LEFT JOIN (SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1) h ON true`, [row.id, row.source_id, row.value_mac, pageSlugs]); - if (held!.same === null && !anchored && !held!.paged) skippedNoPage++; - if (!held!.same) continue; + const [held] = await tx.executeRaw<{ same: boolean }>('SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1', [row.id, row.source_id, row.value_mac]); + if (!held && !anchored && !holding.length) skippedNoPage++; + if (!held?.same) continue; } for (const o of own) { occ += (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,commit_sha,path,line,pre_field_sha256,created_by,created_at) SELECT $1,$2,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz - WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3 AND ${holds('p')})) + WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR ($3 = ANY($12::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3))) AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x WHERE x.entry_id=$1 AND x.source_id=$2 AND x.slug IS NOT DISTINCT FROM $3 AND x.field=$4 AND x.commit_sha IS NOT DISTINCT FROM $6 AND x.path IS NOT DISTINCT FROM $7 AND x.line IS NOT DISTINCT FROM $8::integer AND x.origin=$5 AND x.pre_field_sha256 IS NOT DISTINCT FROM $9 AND x.created_by=$10 AND date_trunc('milliseconds', x.created_at) = $11::timestamptz) RETURNING 1`, - [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at])).length; + [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at, holding])).length; } if (!inserted.length || anchored) continue; if ((await tx.executeRaw('DELETE FROM secret_store s WHERE s.id=$1 AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.entry_id=s.id) RETURNING 1', [row.id])).length) { @@ -272,6 +271,31 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage }; } +/** + * The backed-up slugs whose page in the source holds entry `id`'s marker now: pageHoldsSql for every store SQL reads, + * and for a page whose body is stored in segments, its segments read in order (a marker split across two is found). + */ +async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], id: string): Promise { + if (!slugs.length) return []; + const rows = await tx.executeRaw<{ id: number | string; slug: string; segmented: boolean; holds: boolean }>( + `SELECT p.id, p.slug, p.body_storage = 'segmented' AS segmented, ${pageHoldsSql('p', '$3')} AS holds FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[])`, + [sourceId, slugs, id]); + const marker = new RegExp(``); + const out: string[] = []; + for (const page of rows) { + if (page.holds) { out.push(page.slug); continue; } + if (!page.segmented) continue; + const decoder = new TextDecoder(); + let carry = ''; + for await (const part of readSegmentedBody(tx, Number(page.id), sourceId)) { + const text = carry + decoder.decode(part.bytes, { stream: true }); + if (marker.test(text)) { out.push(page.slug); break; } + carry = text.slice(-96); + } + } + return out; +} + /** * The purge cascade: a page purged for good takes its sealed originals with it. Removes the page's occurrences (those * recorded on the page itself, not the ones a publish recorded on a commit), then every entry those occurrences pointed diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json index 18f699f1fa7..e15a6d5f470 100644 --- a/test/fixtures/goldens/sql-text/pages.json +++ b/test/fixtures/goldens/sql-text/pages.json @@ -1998,8 +1998,8 @@ "string", "string" ], - "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug = $8 AND ((p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text) ~ ('') OR p.body_storage = 'segmented' OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND (hr.data::text) ~ ('')) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND (ht.summary || ' ' || ht.detail || ' ' || ht.source) ~ ('')) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND (coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')) ~ ('')) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND (hl.context) ~ ('')) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND (coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')) ~ (''))))))", - "textSha256": "46adadccf552b92a71f417ce5fd00cc2dc7b6bd3f2230bfa001bc19555ca3c85" + "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug = $8 AND ((p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text) ~ ('') OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND (hr.data::text) ~ ('')) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND (ht.summary || ' ' || ht.detail || ' ' || ht.source) ~ ('')) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND (coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')) ~ ('')) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND (hl.context) ~ ('')) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND (coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')) ~ (''))))))", + "textSha256": "7205db903a8862b256fa5e8e97c157222008f4b9a57e5da290be109930dfea47" }, { "event": "savepoint-release", diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index b0405801fb6..43348bb7e9f 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -19,6 +19,7 @@ import { join } from 'node:path'; import { secretStoreCheck } from '../src/commands/doctor/checks/secret-store.ts'; import type { DoctorContext } from '../src/commands/doctor/context.ts'; import { testBackends } from './helpers/test-backends.ts'; +import { createSegmentedPage } from './helpers/segmented-page.ts'; import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts'; const deleteOp = operations.find(o => o.name === 'delete_page')!; @@ -416,26 +417,32 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); - test('a page stored in segments counts as holding the marker at a backed-up slug, and a segmented page elsewhere never does', async () => { + test('a page stored in segments holds a marker only when its segments do, and a store row of the page counts too', async () => { await brain(async b => { const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-segmented-')); try { const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); - const seg = `notes/segmented-${randomUUID().slice(0, 6)}`, gone = `notes/gone-${randomUUID().slice(0, 6)}`, other = `notes/other-seg-${randomUUID().slice(0, 6)}`; - for (const slug of [seg, other]) await b.engine.putPage(slug, { type: 'note', title: 'Long', compiled_truth: 'Long page.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); - await b.engine.executeRaw("UPDATE pages SET body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_bytes = 10 WHERE source_id = $1 AND slug = ANY($2::text[])", [b.sourceId, [seg, other]]); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); - const atSlug = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`sg${randomUUID().slice(0, 6)}`) })).id; - const nowhere = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`nw${randomUUID().slice(0, 6)}`) })).id; - await recordOccurrence(b.engine, { entryId: atSlug, sourceId: b.sourceId, slug: seg, field: 'compiled_truth', origin: 'repair' }); - await recordOccurrence(b.engine, { entryId: nowhere, sourceId: b.sourceId, slug: gone, field: 'compiled_truth', origin: 'repair' }); + const seal1 = async (tag: string) => (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(tag + randomUUID().slice(0, 6)) })).id; + const ids = { inSegments: await seal1('sg'), notInSegments: await seal1('ns'), frontmatter: await seal1('fm'), rawData: await seal1('rd'), timeline: await seal1('te') }; + const slugs = Object.fromEntries(Object.keys(ids).map(k => [k, 'notes/' + k.toLowerCase() + '-' + randomUUID().slice(0, 6)])) as Record; + const filler = 'a long line of ordinary text\n'.repeat(3000); + await createSegmentedPage(b.engine, { slug: slugs.inSegments, sourceId: b.sourceId, truth: filler + 'held here ' + markerOf('github_token', ids.inSegments) + '\n' + filler }); + await createSegmentedPage(b.engine, { slug: slugs.notInSegments, sourceId: b.sourceId, truth: filler + 'took the old slug\n' + filler }); + await b.engine.putPage(slugs.frontmatter, { type: 'note', title: 'Frontmatter', compiled_truth: 'Body.', timeline: '', frontmatter: { token: markerOf('github_token', ids.frontmatter) } }, { sourceId: b.sourceId }); + for (const k of ['rawData', 'timeline'] as const) await b.engine.putPage(slugs[k], { type: 'note', title: k, compiled_truth: 'Body.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + const pid = async (slug: string) => (await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, slug]))[0]!.id; + await b.engine.executeRaw("INSERT INTO raw_data (page_id, source, data) VALUES ($1, 'test', $2::jsonb)", [await pid(slugs.rawData), JSON.stringify({ note: markerOf('github_token', ids.rawData) })]); + await b.engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', $2)", [await pid(slugs.timeline), 'Met ' + markerOf('github_token', ids.timeline)]); + for (const k of Object.keys(ids) as (keyof typeof ids)[]) await recordOccurrence(b.engine, { entryId: ids[k], sourceId: b.sourceId, slug: slugs[k], field: 'compiled_truth', origin: 'repair' }); const out = await backupStore(b.engine, storage); await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); - expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 1 }); - expect(await b.engine.executeRaw('SELECT entry_id, slug FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId])).toEqual([{ entry_id: atSlug, slug: seg }]); - expect(await b.engine.executeRaw('SELECT id FROM secret_store WHERE id = $1', [nowhere])).toEqual([]); + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 4, skipped_no_page: 1 }); + const tied = await b.engine.executeRaw<{ entry_id: string; slug: string }>('SELECT entry_id, slug FROM secret_store_occurrence WHERE source_id = $1 ORDER BY slug', [b.sourceId]); + expect(new Set(tied.map(t => t.entry_id))).toEqual(new Set([ids.inSegments, ids.frontmatter, ids.rawData, ids.timeline])); + expect(await b.engine.executeRaw('SELECT id FROM secret_store WHERE id = $1', [ids.notInSegments])).toEqual([]); } finally { rmSync(bucket, { recursive: true, force: true }); } }); }, 120_000); From 04df0276f14eff36ed2b21bdd3c3d9c80928bd78 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 10:16:24 +0000 Subject: [PATCH 32/37] fix: pre-landing review fixes Test the take-back of an entry whose page is gone before its place lands, and match the marker in segmented bodies with a fixed pattern instead of one built from the entry id (semgrep detect-non-literal-regexp). Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/specialist-batched#2 reader=specialist-batched Review-Finding: p1/red-team#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/secret-store/store.ts | 4 ++-- test/secret-store-purge.test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index b2a661fee56..83ef309a8c6 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -280,7 +280,7 @@ async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], const rows = await tx.executeRaw<{ id: number | string; slug: string; segmented: boolean; holds: boolean }>( `SELECT p.id, p.slug, p.body_storage = 'segmented' AS segmented, ${pageHoldsSql('p', '$3')} AS holds FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[])`, [sourceId, slugs, id]); - const marker = new RegExp(``); + const holds = (text: string) => [...text.matchAll(/]+)>/g)].some((m) => m[1] === id); const out: string[] = []; for (const page of rows) { if (page.holds) { out.push(page.slug); continue; } @@ -289,7 +289,7 @@ async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], let carry = ''; for await (const part of readSegmentedBody(tx, Number(page.id), sourceId)) { const text = carry + decoder.decode(part.bytes, { stream: true }); - if (marker.test(text)) { out.push(page.slug); break; } + if (holds(text)) { out.push(page.slug); break; } carry = text.slice(-96); } } diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index 43348bb7e9f..9a32f4235ef 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -459,6 +459,36 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); + test('a restore that writes an entry whose page is gone before its place lands takes the entry back out', async () => { + await brain(async b => { + const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-takeback-')); + try { + const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + const slug = 'notes/raced-' + randomUUID().slice(0, 6), keep = 'notes/kept-' + randomUUID().slice(0, 6); + const raced = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('rc' + randomUUID().slice(0, 6)) })).id; + const kept = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('kp' + randomUUID().slice(0, 6)) })).id; + await b.engine.putPage(slug, { type: 'note', title: 'Raced', compiled_truth: 'Raced ' + markerOf('github_token', raced), timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.putPage(keep, { type: 'note', title: 'Kept', compiled_truth: 'Kept ' + markerOf('github_token', kept), timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await recordOccurrence(b.engine, { entryId: raced, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair' }); + await recordOccurrence(b.engine, { entryId: kept, sourceId: b.sourceId, slug: keep, field: 'compiled_truth', origin: 'repair' }); + const out = await backupStore(b.engine, storage); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw(`CREATE FUNCTION test_purge_raced() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id = '${raced}' THEN DELETE FROM pages WHERE slug = '${slug}'; END IF; RETURN NEW; END $$`); + await b.engine.executeRaw('CREATE TRIGGER test_purge_raced AFTER INSERT ON secret_store FOR EACH ROW EXECUTE FUNCTION test_purge_raced()'); + try { + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 1 }); + } finally { + await b.engine.executeRaw('DROP TRIGGER test_purge_raced ON secret_store'); + await b.engine.executeRaw('DROP FUNCTION test_purge_raced()'); + } + expect((await b.engine.executeRaw<{ id: string }>('SELECT id FROM secret_store WHERE id = ANY($1::text[])', [[raced, kept]])).map(r => r.id)).toEqual([kept]); + } finally { rmSync(bucket, { recursive: true, force: true }); } + }); + }, 120_000); + test('a rename that fails partway leaves the page and its secret occurrences where they were', async () => { await brain(async b => { const foo = `notes/foo-${randomUUID().slice(0, 6)}`, bar = `notes/bar-${randomUUID().slice(0, 6)}`; From 5071243cc05fce3da1e89d605b96ec7a9a052ce1 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 10:33:36 +0000 Subject: [PATCH 33/37] fix: tie a restored place to the page the restore checked The restore now locks the pages it checks for the marker and writes each place with that checked page's id, only while the page still holds the slug, so a rename running at the same time cannot hand the original to a page that took the slug. The guide now says a copy of the marker in a timeline entry filed on the page counts as the page holding it. Review-Finding: outside-voice#1 reader=outside-voice Review-Round-Grant: GBRA-108 extra-round at 04df0276 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- docs/guides/secret-store.md | 7 +++++-- src/core/secret-store/store.ts | 26 +++++++++++++------------- test/secret-store-purge.test.ts | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index 13f2b8821df..e7f5aeb60ed 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -133,8 +133,11 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t the places the backup recorded for it that this brain lacks are added, so a later purge of one page never removes an original another page still holds. A restore only adds rows and never deletes one it did not write, and it ties a restored place to the page at its backed-up slug only when that page holds the entry's marker (`:>`), so a page - that merely took an old slug, or quotes the id, never gets the original, and neither does another page a copy of - the marker sits on. A page whose body is stored in segments is read segment by segment. + that merely took an old slug, or quotes the id, never gets the original. The marker counts when it sits in the page + itself or in a timeline entry or fact filed on or about that page, so a copy another page wrote into that page's + timeline counts too. A page whose body is stored in segments is read segment by segment. The restore ties the place + to the exact page it checked and holds that page until it commits, so a rename running at the same time cannot hand + the original to a page that takes the slug. An original recorded only on pages, none of which at its backed-up slugs holds its marker, is skipped and counted as `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, is not synced yet, or was renamed before the backup named it by its current slug (a backup from before 0.60.744.0), diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index 83ef309a8c6..6943eff5fc8 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -222,8 +222,8 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac * Writes backed-up entries the store does not hold (by id, and never over a row that holds the same value, so a local * row changed since the backup stays as it is), with the occurrences of the entries it wrote or already holds. A place * on a page (a slug and no commit) comes back only when the page at that slug holds the entry's marker (its segments - * read when its body is stored in segments), so a restore - * never ties an original to a page that merely took its old slug, or to another page a copy of its marker sits on. An + * read when its body is stored in segments; locked FOR SHARE, and the place takes that checked page's id only while it + * still holds the slug), so a restore never ties an original to a page that merely took its old slug. An * entry recorded only on pages is written only while one of those pages holds its marker, and an entry whose places * all failed to land (its page purged while the restore ran) is taken back out; otherwise it is not written * (`skipped_no_page`): the page was purged, is not synced yet, or was renamed before the backup named it by its @@ -242,24 +242,24 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry const own = byEntry.get(row.id) ?? []; const anchored = own.length === 0 || own.some(o => !onPage(o)); const holding = await holdingSlugs(tx, row.source_id, [...new Set(own.filter(onPage).map(o => o.slug as string))], row.id); - const inserted = anchored || holding.length ? await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) + const inserted = anchored || holding.size ? await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2) ON CONFLICT DO NOTHING RETURNING id`, [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at]) : []; if (inserted.length) written++; else { const [held] = await tx.executeRaw<{ same: boolean }>('SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1', [row.id, row.source_id, row.value_mac]); - if (!held && !anchored && !holding.length) skippedNoPage++; + if (!held && !anchored && !holding.size) skippedNoPage++; if (!held?.same) continue; } for (const o of own) { occ += (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,commit_sha,path,line,pre_field_sha256,created_by,created_at) - SELECT $1,$2,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz - WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR ($3 = ANY($12::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3))) + SELECT $1,$2,COALESCE($12::bigint,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3)),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz + WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.id=$12::bigint AND p.source_id=$2 AND p.slug=$3)) AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x WHERE x.entry_id=$1 AND x.source_id=$2 AND x.slug IS NOT DISTINCT FROM $3 AND x.field=$4 AND x.commit_sha IS NOT DISTINCT FROM $6 AND x.path IS NOT DISTINCT FROM $7 AND x.line IS NOT DISTINCT FROM $8::integer AND x.origin=$5 AND x.pre_field_sha256 IS NOT DISTINCT FROM $9 AND x.created_by=$10 AND date_trunc('milliseconds', x.created_at) = $11::timestamptz) RETURNING 1`, - [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at, holding])).length; + [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at, o.slug === null ? null : holding.get(o.slug) ?? null])).length; } if (!inserted.length || anchored) continue; if ((await tx.executeRaw('DELETE FROM secret_store s WHERE s.id=$1 AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.entry_id=s.id) RETURNING 1', [row.id])).length) { @@ -275,21 +275,21 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry * The backed-up slugs whose page in the source holds entry `id`'s marker now: pageHoldsSql for every store SQL reads, * and for a page whose body is stored in segments, its segments read in order (a marker split across two is found). */ -async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], id: string): Promise { - if (!slugs.length) return []; +async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], id: string): Promise> { + const out = new Map(); + if (!slugs.length) return out; const rows = await tx.executeRaw<{ id: number | string; slug: string; segmented: boolean; holds: boolean }>( - `SELECT p.id, p.slug, p.body_storage = 'segmented' AS segmented, ${pageHoldsSql('p', '$3')} AS holds FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[])`, + `SELECT p.id, p.slug, p.body_storage = 'segmented' AS segmented, ${pageHoldsSql('p', '$3')} AS holds FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) FOR SHARE OF p`, [sourceId, slugs, id]); const holds = (text: string) => [...text.matchAll(/]+)>/g)].some((m) => m[1] === id); - const out: string[] = []; for (const page of rows) { - if (page.holds) { out.push(page.slug); continue; } + if (page.holds) { out.set(page.slug, Number(page.id)); continue; } if (!page.segmented) continue; const decoder = new TextDecoder(); let carry = ''; for await (const part of readSegmentedBody(tx, Number(page.id), sourceId)) { const text = carry + decoder.decode(part.bytes, { stream: true }); - if (holds(text)) { out.push(page.slug); break; } + if (holds(text)) { out.set(page.slug, Number(page.id)); break; } carry = text.slice(-96); } } diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index 9a32f4235ef..01c5f3da46f 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -489,6 +489,38 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); + test('a restore ties a place to the page it checked, never to one that took the slug while it ran', async () => { + await brain(async b => { + const bucket = mkdtempSync(join(tmpdir(), 'gbrain-ss-pin-')); + try { + const storage = await createStorage({ backend: 'local', bucket: 'b', localPath: bucket }); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + const tag = randomUUID().slice(0, 6), slug = 'notes/pinned-' + tag, other = 'notes/taker-' + tag; + const pinned = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('pn' + tag) })).id; + await b.engine.putPage(slug, { type: 'note', title: 'Pinned', compiled_truth: 'Pinned ' + markerOf('github_token', pinned), timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await b.engine.putPage(other, { type: 'note', title: 'Taker', compiled_truth: 'No marker', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + const kept = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('kq' + tag) })).id; + await b.engine.putPage('notes/kept-' + tag, { type: 'note', title: 'Kept', compiled_truth: 'Kept ' + markerOf('github_token', kept), timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + await recordOccurrence(b.engine, { entryId: pinned, sourceId: b.sourceId, slug, field: 'compiled_truth', origin: 'repair' }); + await recordOccurrence(b.engine, { entryId: kept, sourceId: b.sourceId, slug: 'notes/kept-' + tag, field: 'compiled_truth', origin: 'repair' }); + const out = await backupStore(b.engine, storage); + await b.engine.executeRaw('DELETE FROM secret_store_occurrence WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw('DELETE FROM secret_store WHERE source_id = $1', [b.sourceId]); + await b.engine.executeRaw(`CREATE FUNCTION test_take_slug() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id = '${pinned}' THEN UPDATE pages SET slug = '${slug}-moved' WHERE slug = '${slug}'; UPDATE pages SET slug = '${slug}' WHERE slug = '${other}'; END IF; RETURN NEW; END $$`); + await b.engine.executeRaw('CREATE TRIGGER test_take_slug AFTER INSERT ON secret_store FOR EACH ROW EXECUTE FUNCTION test_take_slug()'); + try { + expect(await restoreBackup(b.engine, storage, out.object)).toMatchObject({ inserted: 1, skipped_no_page: 1 }); + } finally { + await b.engine.executeRaw('DROP TRIGGER test_take_slug ON secret_store'); + await b.engine.executeRaw('DROP FUNCTION test_take_slug()'); + } + expect(await b.engine.executeRaw('SELECT entry_id FROM secret_store_occurrence WHERE entry_id = $1', [pinned])).toEqual([]); + expect(await b.engine.executeRaw('SELECT id FROM secret_store WHERE id = $1', [pinned])).toEqual([]); + } finally { rmSync(bucket, { recursive: true, force: true }); } + }); + }, 120_000); + test('a rename that fails partway leaves the page and its secret occurrences where they were', async () => { await brain(async b => { const foo = `notes/foo-${randomUUID().slice(0, 6)}`, bar = `notes/bar-${randomUUID().slice(0, 6)}`; From 52db8131d25f91093f37e71258ced86c677032e7 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 10:39:20 +0000 Subject: [PATCH 34/37] fix: list the concept rebuild's two maintenance privacy reads and classify the secret store for it The rebuild's access comparison and the purge preview's member classification read the plain private-pages fragment; neither serves a remote caller, so both are listed as maintenance sites. The secret store's two purge tables are rows derived from the old page's text and are classified as such. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 2 +- test/remote-read-floor.test.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index e60e3eac076..a02d1d60924 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -63,7 +63,7 @@ export const REBUILD_STORES: Readonly> = { derived_generation_items: 'derived', retrieval_event_pages: 'derived', retrieval_event_links: 'derived', retrieval_feedback: 'derived', retrieval_weights: 'derived', 'eval_candidates.retrieved_slugs': 'derived', mention_gazetteer_entries: 'derived', context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', - page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', + page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', secret_store: 'derived', secret_store_occurrence: 'derived', }; /** diff --git a/test/remote-read-floor.test.ts b/test/remote-read-floor.test.ts index 511bdcaa27d..2047a0c28fc 100644 --- a/test/remote-read-floor.test.ts +++ b/test/remote-read-floor.test.ts @@ -26,6 +26,8 @@ const PLAIN: Record = { 'src/core/link-relationships.ts refreshRelationships privatePagesFilterFragment': 'write-side: records whether a link origin is public', 'src/core/ops/valid-time-read.ts resolveIdentity privatePagesFilterFragment': 'the world flag of the page; the read itself is gated by privatePagesFilterForCaller', 'src/core/persistence/change-reason.ts pageWorldVisible privatePagesFilterFragment': 'write-side: whether a change reason may be published', + 'src/core/persistence/concept-rebuild.ts ACCESS_SQL privatePagesFilterFragment': 'maintenance: compares a hidden concept\'s access with its rebuild\'s, to refuse a wider one', + 'src/core/persistence/concept-rebuild.ts readHeldConcepts privatePagesFilterFragment': 'maintenance: classifies a held concept\'s members as private for the purge preview; callers get a count or the local CLI', 'src/core/persistence/origin-twins.ts readOriginClaimants privatePagesFilterFragment': 'maintenance: classifies twin pages as private', 'src/core/persistence/rows-behind.ts scanRowsBehind privatePagesFilterFragment': 'maintenance: lineage privacy of rows behind the projection', }; From c154101d2979c7c6997506779385c084451a2a1f Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 10:50:13 +0000 Subject: [PATCH 35/37] fix: a rename moves a leftover secret place with the page again Return the rename's handling of a place with no page id to what master does: it moves with the renamed page, so no page that later takes the old slug can reveal the original. The changelog now says a full copy of the marker still counts as holding it. Review-Finding: v2/outside-voice#1 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/secret-restore-marker.md | 3 +-- docs/guides/secret-store.md | 2 +- src/core/page-state/rename-alias.ts | 6 ++---- test/fixtures/goldens/sql-text/pages.json | 6 ++---- test/secret-store-purge.test.ts | 9 +++++---- 5 files changed, 11 insertions(+), 15 deletions(-) diff --git a/changelog.d/secret-restore-marker.md b/changelog.d/secret-restore-marker.md index f21c41918d1..8dc3b60dc81 100644 --- a/changelog.d/secret-restore-marker.md +++ b/changelog.d/secret-restore-marker.md @@ -4,7 +4,6 @@ important: security **A secret store restore ties an original only to the page at its backed-up slug, and only when that page still holds its marker.** ### Fixed -- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug, or to a page that quotes its id, so that page's readers never pass the `reveal_secret` read check for it. +- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug and does not hold its marker (`:>`), so that page's readers never pass the `reveal_secret` read check for it. A page that holds a full copy of the marker, in its text or in a timeline entry or fact filed on it, still counts as holding it. - A backup that names a page by a slug it had before a rename (one taken before 0.60.744.0) skips that entry (`skipped_no_page`) instead of tying it to another page, and a restore never brings back what a purge removed. This replaces the 0.60.744.0 note saying such an entry would be restored without a place. - A restore that loses the race with a purge of the same page no longer leaves the sealed original behind. -- A rename no longer moves a leftover place with no page onto the renamed page unless the page now at the new slug holds its marker. diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index e7f5aeb60ed..87650aff899 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -133,7 +133,7 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t the places the backup recorded for it that this brain lacks are added, so a later purge of one page never removes an original another page still holds. A restore only adds rows and never deletes one it did not write, and it ties a restored place to the page at its backed-up slug only when that page holds the entry's marker (`:>`), so a page - that merely took an old slug, or quotes the id, never gets the original. The marker counts when it sits in the page + that merely took an old slug, or quotes only the id, never gets the original. The marker counts when it sits in the page itself or in a timeline entry or fact filed on or about that page, so a copy another page wrote into that page's timeline counts too. A page whose body is stored in segments is read segment by segment. The restore ties the place to the exact page it checked and holds that page until it commits, so a rename running at the same time cannot hand diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.ts index dd8db77b571..f0eb75c4cd7 100644 --- a/src/core/page-state/rename-alias.ts +++ b/src/core/page-state/rename-alias.ts @@ -2,7 +2,6 @@ import type { BrainEngine } from '../engine.ts'; import { isMissingSchemaObject } from '../utils.ts'; import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts'; import { dropRekeyDuplicates } from '../facts/ontology-rekey.ts'; -import { pageHoldsSql } from '../secret-store/marker-sql.ts'; /** * Record `old -> new` in slug_aliases when a page is renamed, inside the @@ -82,7 +81,7 @@ export async function recordSlugLineAlias(tx: Pick, * caller's rename transaction. The new slug is free (the page UPDATE * succeeded), so fence rows or aliases still keyed to it belong to a purged * page and yield to the moved ones. A secret occurrence moves only when it is the renamed page's own (its - * page_id is that page or the stale row a fallback rename retires, or it has none and the page now at the new slug holds its marker where SQL reads it): an occurrence another page holds under + * page_id is that page, or the stale row a fallback rename retires, or none): an occurrence another page holds under * an older slug stays with that page. An ontology observation the new slug * already holds is dropped before its key moves (B-10, dropRekeyDuplicates). * A brain whose schema predates the facts or alias tables skips them inside a @@ -109,8 +108,7 @@ export async function moveSlugBindings( AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)`), sql(`UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`), sql(`UPDATE secret_store_occurrence SET slug = $3 WHERE source_id = $1 AND slug = $2 AND commit_sha IS NULL - AND (page_id IN (SELECT id FROM pages WHERE source_id = $1 AND slug IN ($2, $3)) OR (page_id IS NULL - AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $3 AND ${pageHoldsSql('p', 'secret_store_occurrence.entry_id')})))`), + AND (page_id IS NULL OR page_id IN (SELECT id FROM pages WHERE source_id = $1 AND slug IN ($2, $3)))`), ]; for (const statement of statements) { try { diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json index e15a6d5f470..f8820011624 100644 --- a/test/fixtures/goldens/sql-text/pages.json +++ b/test/fixtures/goldens/sql-text/pages.json @@ -1994,12 +1994,10 @@ "string", "string", "string", - "string", - "string", "string" ], - "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)) OR (page_id IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $7 AND p.slug = $8 AND ((p.title || ' ' || coalesce(p.compiled_truth, '') || ' ' || coalesce(p.timeline, '') || ' ' || p.frontmatter::text) ~ ('') OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = p.id AND (hr.data::text) ~ ('')) OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = p.id OR ht.event_page_id = p.id) AND (ht.summary || ' ' || ht.detail || ' ' || ht.source) ~ ('')) OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = p.id AND (coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')) ~ ('')) OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = p.id AND (hl.context) ~ ('')) OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = p.source_id AND (hf.source_markdown_slug = p.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = p.slug)) AND (coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')) ~ (''))))))", - "textSha256": "7205db903a8862b256fa5e8e97c157222008f4b9a57e5da290be109930dfea47" + "sql": "UPDATE secret_store_occurrence SET slug = $1 WHERE source_id = $2 AND slug = $3 AND commit_sha IS NULL AND (page_id IS NULL OR page_id IN (SELECT id FROM pages WHERE source_id = $4 AND slug IN ($5, $6)))", + "textSha256": "dc82a72d28c14eaf8b2e4848234a3c3ce9b4281001969f91ef6f47a969eb4e3c" }, { "event": "savepoint-release", diff --git a/test/secret-store-purge.test.ts b/test/secret-store-purge.test.ts index 01c5f3da46f..8ec5e2a25ba 100644 --- a/test/secret-store-purge.test.ts +++ b/test/secret-store-purge.test.ts @@ -406,14 +406,15 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); - test('a rename leaves an occurrence with no page under the old slug when the renamed page does not hold its marker', async () => { + test('a rename moves a place with no page along with the page, so a page that later takes the old slug gets nothing', async () => { await brain(async b => { const from = `notes/from-${randomUUID().slice(0, 6)}`, to = `notes/to-${randomUUID().slice(0, 6)}`; await b.engine.putPage(from, { type: 'note', title: 'Took the slug', compiled_truth: 'No marker here.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); const leftover = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value(`lo${randomUUID().slice(0, 6)}`) })).id; await recordOccurrence(b.engine, { entryId: leftover, sourceId: b.sourceId, slug: from, field: 'compiled_truth', origin: 'repair' }); await b.engine.updateSlug(from, to, { sourceId: b.sourceId }); - expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [leftover])).map(r => r.slug)).toEqual([from]); + await b.engine.putPage(from, { type: 'note', title: 'New page at the old slug', compiled_truth: 'Unrelated.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); + expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [leftover])).map(r => r.slug)).toEqual([to]); }); }, 120_000); @@ -447,7 +448,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { }); }, 120_000); - test('a fallback rename leaves a place with no page under the stale slug when only the stale row, not the new one, holds its marker', async () => { + test('a fallback rename moves a place with no page off the stale slug it retires', async () => { await brain(async b => { const stale = 'notes/stale-' + randomUUID().slice(0, 6), dest = 'notes/dest-' + randomUUID().slice(0, 6); const id = (await seal(b.engine, { sourceId: b.sourceId, rule: 'github_token', value: value('fr' + randomUUID().slice(0, 6)) })).id; @@ -455,7 +456,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) { await b.engine.putPage(dest, { type: 'note', title: 'New body', compiled_truth: 'New body without it.', timeline: '', frontmatter: {} }, { sourceId: b.sourceId }); await recordOccurrence(b.engine, { entryId: id, sourceId: b.sourceId, slug: stale, field: 'compiled_truth', origin: 'repair' }); await carryRenameIdentity(b.engine, b.sourceId, stale, dest); - expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [id])).map(r => r.slug)).toEqual([stale]); + expect((await b.engine.executeRaw<{ slug: string }>('SELECT slug FROM secret_store_occurrence WHERE entry_id = $1', [id])).map(r => r.slug)).toEqual([dest]); }); }, 120_000); From 222963ac8f65b5866b223e040dd78fbbacb4e761 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 11:12:44 +0000 Subject: [PATCH 36/37] fix: keep a hidden concept hidden when its page holds a sealed secret original The rebuild's purge would delete a sealed original recorded only on the hidden concept's page, which nothing removes today because the automatic expiry skips a held tombstone. A page-level secret occurrence now keeps the concept hidden. A concept that only copied a redaction from a live member stays hidden too, until entries can be compared across pages. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 8 +++++--- test/concept-purge-rebuild-9653.test.ts | 5 +++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index a02d1d60924..abe9f315932 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -56,14 +56,14 @@ const DERIVED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-r */ export const REBUILD_STORES: Readonly> = { facts: 'stated', takes: 'stated', timeline_entries: 'stated', page_aliases: 'stated', slug_aliases: 'stated', tags: 'stated', - files: 'stated', raw_data: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', + files: 'stated', raw_data: 'stated', secret_store: 'stated', secret_store_occurrence: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', pages: 'derived', page_versions: 'derived', content_chunks: 'derived', query_cache: 'derived', take_proposals: 'derived', open_loops: 'derived', slug_rename_history: 'derived', trust_proposals: 'derived', decide_proposals: 'derived', decide_review_queue: 'derived', decide_review_proposals: 'derived', persistence_requests: 'derived', persistence_effects: 'derived', derived_generations: 'derived', derived_generation_items: 'derived', retrieval_event_pages: 'derived', retrieval_event_links: 'derived', retrieval_feedback: 'derived', retrieval_weights: 'derived', 'eval_candidates.retrieved_slugs': 'derived', mention_gazetteer_entries: 'derived', context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', - page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', secret_store: 'derived', secret_store_occurrence: 'derived', + page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', }; /** @@ -97,7 +97,8 @@ const DELETED_US = `floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::tex * What on or about the concept row `$1` (source `$2`, slug `$3`) synthesis did not write: REBUILD_STORES kinds for rows a * person or an agent stated, plus a title other than the slug's, a frontmatter key synthesis does not write, a stored * timeline, a file other than `.md`, dated link transitions, an attached raw_data payload, a person's decision on an - * edge proposal (rejected, undone or reverted), an entity identity, and a guest mark or promotion. + * edge proposal (rejected, undone or reverted), an entity identity, a guest mark or promotion, and a sealed secret original recorded on the page (even one copied + * from a live member, until entries can be compared across pages). */ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $2 AND (f.entity_slug = $3 OR f.source_markdown_slug = $3) AND NOT ${extractedFromPageSql('f', '$3')}) THEN 'facts' END, @@ -124,6 +125,7 @@ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM entity_identities i WHERE i.page_id = $1) THEN 'entity_identities' END, CASE WHEN EXISTS (SELECT 1 FROM guest_marks g WHERE g.page_id = $1) THEN 'guest_marks' END, CASE WHEN EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = $1) THEN 'guest_promotions' END, + CASE WHEN EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.page_id = $1 AND o.commit_sha IS NULL) THEN 'secret_store_occurrence' END, CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.frontmatter ?| $5::text[]) THEN 'labels' END ], NULL) AS kinds, diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index 33c3e04e19a..af0886ef6a9 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -345,6 +345,10 @@ for (const backend of testBackends()) { ['link_edge_proposals', async (engine, _ctx, id) => raw(engine, "INSERT INTO link_edge_proposals (source_id, from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash, status) SELECT 'default', n.id, $1, n.id, 'works_at', 'evidence-example', 'rejected' FROM pages n WHERE n.slug = 'notes/storage-ref'", [id])], ['entity_identities', async (engine, _ctx, id) => raw(engine, "INSERT INTO entity_identities (entity_id, source_id, page_id) VALUES ('entity-example', 'default', $1)", [id])], ['guest_marks', async (engine, _ctx, id) => raw(engine, "INSERT INTO guest_marks (page_id, source_id, slug_at_write, audience_member, group_slug, sender_label, saved_at, writer_kind, writer_id) VALUES ($1, 'default', $2, 'alice-example', 'group-example', 'Alice', now(), 'member', 'alice-example')", [id, CONCEPT])], + ['secret_store_occurrence', async (engine, _ctx, id) => { + await raw(engine, "INSERT INTO secret_store (id, source_id, rule, ciphertext, nonce, tag, key_id, value_mac) VALUES ('ss_0123456789ab', 'default', 'api_key', 'sealed', 'nonce', 'tag', '0123456789abcdef', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')"); + await raw(engine, "INSERT INTO secret_store_occurrence (entry_id, source_id, page_id, slug, field, origin) VALUES ('ss_0123456789ab', 'default', $1, $2, 'compiled_truth', 'repair')", [id, CONCEPT]); + }], ['guest_promotions', async (engine, _ctx, id) => raw(engine, "INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id) VALUES ($1, 'default', 'notes/promoted-example', 'member', 'alice-example')", [id])], ]; for (const [kind, add] of stated) await managedBrain(async ({ engine, ctx, root }) => { @@ -354,6 +358,7 @@ for (const backend of testBackends()) { expect(details.rebuilt).toEqual([]); expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'stated', kinds: [kind] }]); await stillHeld(engine, id, kind === 'links' ? 2 : 1); + if (kind === 'secret_store_occurrence') expect(await engine.executeRaw("SELECT 1 FROM secret_store s JOIN secret_store_occurrence o ON o.entry_id = s.id WHERE s.id = 'ss_0123456789ab' AND o.page_id = $1", [id])).toHaveLength(1); }, { databaseUrl }); }, 1_500_000); } From b7e6184bc30aa4d951efbdba9e06df01a88e7c8a Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 19 Nov 2026 11:27:43 +0000 Subject: [PATCH 37/37] fix: also keep a hidden concept hidden for a sealed secret recorded at its slug with no page The purge deletes a slug's page-level secret occurrences that name the purged page or no page at all, so the hold now matches both, as the purge's own predicate does. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/core/persistence/concept-rebuild.ts | 3 ++- test/concept-purge-rebuild-9653.test.ts | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts index abe9f315932..5c570f0d86b 100644 --- a/src/core/persistence/concept-rebuild.ts +++ b/src/core/persistence/concept-rebuild.ts @@ -125,7 +125,8 @@ const STATED_SQL = `SELECT array_remove(ARRAY[ CASE WHEN EXISTS (SELECT 1 FROM entity_identities i WHERE i.page_id = $1) THEN 'entity_identities' END, CASE WHEN EXISTS (SELECT 1 FROM guest_marks g WHERE g.page_id = $1) THEN 'guest_marks' END, CASE WHEN EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = $1) THEN 'guest_promotions' END, - CASE WHEN EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.page_id = $1 AND o.commit_sha IS NULL) THEN 'secret_store_occurrence' END, + CASE WHEN EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.source_id = $2 AND o.commit_sha IS NULL + AND (o.page_id = $1 OR (o.page_id IS NULL AND o.slug = $3))) THEN 'secret_store_occurrence' END, CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.frontmatter ?| $5::text[]) THEN 'labels' END ], NULL) AS kinds, diff --git a/test/concept-purge-rebuild-9653.test.ts b/test/concept-purge-rebuild-9653.test.ts index af0886ef6a9..80d4ebd0947 100644 --- a/test/concept-purge-rebuild-9653.test.ts +++ b/test/concept-purge-rebuild-9653.test.ts @@ -349,6 +349,10 @@ for (const backend of testBackends()) { await raw(engine, "INSERT INTO secret_store (id, source_id, rule, ciphertext, nonce, tag, key_id, value_mac) VALUES ('ss_0123456789ab', 'default', 'api_key', 'sealed', 'nonce', 'tag', '0123456789abcdef', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')"); await raw(engine, "INSERT INTO secret_store_occurrence (entry_id, source_id, page_id, slug, field, origin) VALUES ('ss_0123456789ab', 'default', $1, $2, 'compiled_truth', 'repair')", [id, CONCEPT]); }], + ['secret_store_occurrence', async engine => { + await raw(engine, "INSERT INTO secret_store (id, source_id, rule, ciphertext, nonce, tag, key_id, value_mac) VALUES ('ss_0123456789ac', 'default', 'api_key', 'sealed', 'nonce', 'tag', '0123456789abcdef', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')"); + await raw(engine, "INSERT INTO secret_store_occurrence (entry_id, source_id, page_id, slug, field, origin) VALUES ('ss_0123456789ac', 'default', NULL, $1, 'compiled_truth', 'repair')", [CONCEPT]); + }], ['guest_promotions', async (engine, _ctx, id) => raw(engine, "INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id) VALUES ($1, 'default', 'notes/promoted-example', 'member', 'alice-example')", [id])], ]; for (const [kind, add] of stated) await managedBrain(async ({ engine, ctx, root }) => { @@ -358,7 +362,7 @@ for (const backend of testBackends()) { expect(details.rebuilt).toEqual([]); expect(details.rebuild_kept).toEqual([{ source_id: 'default', slug: CONCEPT, reason: 'stated', kinds: [kind] }]); await stillHeld(engine, id, kind === 'links' ? 2 : 1); - if (kind === 'secret_store_occurrence') expect(await engine.executeRaw("SELECT 1 FROM secret_store s JOIN secret_store_occurrence o ON o.entry_id = s.id WHERE s.id = 'ss_0123456789ab' AND o.page_id = $1", [id])).toHaveLength(1); + if (kind === 'secret_store_occurrence') expect(await engine.executeRaw("SELECT 1 FROM secret_store s JOIN secret_store_occurrence o ON o.entry_id = s.id WHERE o.slug = $1", [CONCEPT])).toHaveLength(1); }, { databaseUrl }); }, 1_500_000); }