From 75a62788522261ce09ce63bc7fbc1492184e91d2 Mon Sep 17 00:00:00 2001 From: onthegonow <118165318+onthegonow@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:04:01 +0000 Subject: [PATCH 1/3] The app wires learner-server's hook into every Claude Code session on this Mac A new job, ClaudeHook (launch, then every 6 h), runs learner-server's own installer from the uploader's checkout: user-level ~/.claude/settings.json, the paired server's URL, and the Keychain lookup as the way to read the device key (never the key). It then runs the installer's --check, which asks the server with that key, and reports the result like any other job: refused or keyless is blocked, unreachable is retried. That covers the terminal CLI and the Code tab of the Claude desktop app. Chats in the desktop app and on claude.ai run no hooks and still arrive through the chat archive. Tests: the arguments and report parsing (light), the job against a stand-in bun (medium), and on the runner the real installer against the real server with a real device key into a scratch ~/.claude, with one prompt sent through the installed hook (heavy). config/learner-server.ref moves to the server commit that admits a device key on the hook's calls. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SPMjtan22onKA34S16vwNd --- README.md | 10 ++ Tests/HeavyTests/PairingE2ETests.swift | 60 ++++++++ Tests/LightTests/ClaudeHookTests.swift | 54 +++++++ Tests/MediumTests/ClaudeHookJobTests.swift | 108 ++++++++++++++ config/learner-server.ref | 2 +- menu-bar-app/ClaudeHook.swift | 162 +++++++++++++++++++++ menu-bar-app/LearnerRPC.swift | 4 +- 7 files changed, 398 insertions(+), 2 deletions(-) create mode 100644 Tests/LightTests/ClaudeHookTests.swift create mode 100644 Tests/MediumTests/ClaudeHookJobTests.swift create mode 100644 menu-bar-app/ClaudeHook.swift diff --git a/README.md b/README.md index 370c3b4..cb12cf9 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,16 @@ Codex CLI and Claude Code sessions are captured by learner-server's `clients/upl (learner-upload), not by this app (yet): it tails `~/.codex/sessions` and `~/.claude/projects` and uploads the raw session files with the same device key and client id. +The app also wires learner-server's live hook into Claude Code on this Mac (job `ClaudeHook`, +at launch and every 6 hours): it runs learner-server's `clients/hook/src/install.ts` from the +same checkout as the uploader, pointed at the paired server and at the Keychain lookup for the +device key (the key is never passed or written), then the installer's `--check`. That puts the +hook in the user-level `~/.claude/settings.json`, so it runs in every Claude Code session in +any folder: the terminal CLI and the Code tab of the Claude desktop app, which runs the same +Claude Code. A chat in the Claude desktop app or on claude.ai runs no hooks; those +conversations reach the server afterwards through the chat archive. A checkout from before +the installer existed is fast-forwarded once (only when it has no local changes). + ## Pairing with learner-server Everything goes to learner-server over HTTPS as `POST ${LEARNER_API_URL}/rpc/` with body diff --git a/Tests/HeavyTests/PairingE2ETests.swift b/Tests/HeavyTests/PairingE2ETests.swift index 79beff0..73fe6e4 100644 --- a/Tests/HeavyTests/PairingE2ETests.swift +++ b/Tests/HeavyTests/PairingE2ETests.swift @@ -232,6 +232,66 @@ struct PairingE2ETests { #expect(!keyLogged, "the key is never logged") } + /// The Claude Code hook, wired by the app's own job with learner-server's real installer + /// and a real device key, into a scratch ~/.claude (never the machine's own): the + /// installer's check passes against the server, and a prompt sent through the installed + /// hook command comes back carrying the live-feedback instructions. Needs the server + /// checkout on this machine (the runner), since the installer is run from it. + @Test(.enabled(if: Harness.localServer != nil, "needs the local harness (LEARNER_SERVER_DIR): the installer runs from that checkout")) + func theHookJobWiresClaudeCodeAndAPromptReachesTheServer() throws { + let server = try #require(Harness.localServer) + let harness = try Harness(["--topology", "same-machine"]) + defer { harness.stop() } + let ready = try #require(harness.ready(), "the harness did not start: \(harness.output.suffix(1500))") + let data = try #require(harness.pairingFile(try #require(ready["pairingFile"] as? String))) + guard case .success(let p) = Pairing.parse(data) else { Issue.record("the harness's payload does not parse"); return } + + // The key reaches the hook from a mode-600 file in the scratch folder (the Keychain's + // stand-in here: LEARNER_HOOK_KEY_FILE outranks the configured Keychain lookup). + let home = TempDir("claude-hook-e2e") + let keyFile = home.write("device-key.env", "LEARNER_API_KEY=\(p.apiKey)\n", mode: 0o600) + let scratch = ["LEARNER_HOOK_CONFIG": home.file(".claude/learning-hook.json"), + "LEARNER_HOOK_TRACE_DIR": home.file(".claude/learner-hook-traces"), + "LEARNER_HOOK_KEY_FILE": keyFile] + var c = ClaudeHook.Config() + c.jobName = "test-claude-hook-e2e-\(UUID().uuidString.prefix(8))" + defer { try? FileManager.default.removeItem(atPath: Job.stateDir + "/\(c.jobName).json") } + c.repo = server + c.bun = Live.env["LEARNER_BUN"] ?? "/opt/homebrew/bin/bun" + c.serverURL = { p.apiUrl } + c.clientId = { p.clientId } + c.paired = { true } + c.environment = scratch + c.updateCheckout = false + let outcome = ClaudeHook(config: c).runOnce() + guard case .ok(let summary, _) = outcome else { Issue.record("the hook job did not finish ok: \(outcome)"); return } + #expect(summary.hasPrefix("wired into Claude Code")) + + // What it wrote: user-level settings with the hook on every event, and a config that + // names the server and the Keychain lookup, not the key. + let settings = try #require(try? JSONSerialization.jsonObject(with: Data(home.read(".claude/settings.json").utf8)) as? [String: Any]) + let hooks = try #require(settings["hooks"] as? [String: [[String: Any]]]) + for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] { #expect(hooks[event]?.isEmpty == false, "no \(event) hook") } + let config = home.read(".claude/learning-hook.json") + #expect(config.contains(p.apiUrl) && config.contains("find-generic-password")) + let keyWritten = (config + home.read(".claude/settings.json")).contains(p.apiKey) + #expect(!keyWritten, "the key is never written into Claude Code's files") + + // One prompt, through the command Claude Code would run. + let command = try #require(((hooks["UserPromptSubmit"]?.first?["hooks"] as? [[String: Any]])?.first)?["command"] as? String) + let session = "e2e-\(UUID().uuidString.lowercased())" + let prompt = try JSONSerialization.data(withJSONObject: ["hook_event_name": "UserPromptSubmit", "session_id": session, + "prompt": "Explain why a B-tree index speeds up this lookup."]) + let turn = ChildProcess.run("/bin/sh", ["-c", command], timeout: 30, + env: ChildProcess.toolEnvironment.merging(scratch) { _, new in new }, input: prompt) + #expect(turn.status == 0) + // Bools first: a failed #expect prints its operands, and this log is public. + let taught = turn.output.contains("LEARNING LIVE FEEDBACK") && turn.output.contains(session) + #expect(taught, "the hook did not return live feedback for the prompt") + let keyPrinted = turn.output.contains(p.apiKey) + #expect(!keyPrinted, "the key is never printed") + } + static let installedBinary = NSHomeDirectory() + "/Applications/Learner Desktop.app/Contents/MacOS/learner-desktop" @Test func pairsWithAServerOnTheSameMachine() throws { diff --git a/Tests/LightTests/ClaudeHookTests.swift b/Tests/LightTests/ClaudeHookTests.swift new file mode 100644 index 0000000..82b81e3 --- /dev/null +++ b/Tests/LightTests/ClaudeHookTests.swift @@ -0,0 +1,54 @@ +import Foundation +import Testing +@testable import LearnerDesktop +import TestSupport + +// The Claude Code hook job's pure parts: what it asks learner-server's installer to do, and +// what the installer's --check report means for the tray. +@Suite("Claude Code hook", .tags(.light, .sessions), .timeLimit(.minutes(1)), .quietLog) struct ClaudeHookTests { + @Test func theInstallerIsToldHowToReadTheKeyNeverTheKey() throws { + let args = ClaudeHook.installArguments(installer: "/r/clients/hook/src/install.ts", bun: "/h/.bun/bin/bun", + serverURL: "https://learner.example/learner-api", clientId: "a-mac") + #expect(args.prefix(5) == ["/r/clients/hook/src/install.ts", "--bun", "/h/.bun/bin/bun", "--server-url", "https://learner.example/learner-api"]) + #expect(args[5] == "--key-command-json" && args.count == 7) + let command = try #require(try? JSONSerialization.jsonObject(with: Data(args[6].utf8)) as? [String]) + #expect(command == ["/usr/bin/security", "find-generic-password", "-s", "learner-server", "-a", "a-mac", "-w"]) + // The same lookup the app itself uses for its own calls. + #expect(command == ClaudeHook.keyCommand(clientId: "a-mac")) + #expect(!args[6].contains("\\"), "plain slashes, as a person would write it") + let more = ClaudeHook.installArguments(installer: "i", bun: "b", serverURL: "u", clientId: "c", catalogParts: 7) + #expect(more.suffix(2) == ["--catalog-parts", "7"]) + } + + @Test func theCheckReportIsTheLastJSONLine() throws { + let text = """ + bun: a notice that is not the report + {"ok":true,"settings":"/h/.claude/settings.json","events":{"Stop":true},"catalogParts":5,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogPartsNeeded":5} + + """ + let c = try #require(ClaudeHook.parseCheck(text)) + #expect(c == ClaudeHook.Check(ok: true, installed: true, permissions: true, config: "ok", server: "ok", catalogParts: 5, catalogPartsNeeded: 5)) + #expect(ClaudeHook.parseCheck("not json\n{\"installed\":true}\n") == nil, "an install report is not a check report") + #expect(ClaudeHook.parseCheck("") == nil) + } + + @Test func eachReportBecomesTheRightOutcome() { + func outcome(_ change: (inout ClaudeHook.Check) -> Void) -> String { + var c = ClaudeHook.Check(ok: false, installed: true, permissions: true, config: "ok", server: "ok", catalogParts: 5, catalogPartsNeeded: 5) + change(&c) + return describe(ClaudeHook.outcome(c)) + } + #expect(outcome { $0.ok = true } == "ok: wired into Claude Code (5 catalog parts)") + // Needs the owner: blocked, not retried in a loop. + #expect(outcome { $0.server = "refused (HTTP 403)" }.hasPrefix("blocked: learner-server refused the device key")) + #expect(outcome { $0.server = "no credential" }.hasPrefix("blocked: the Claude Code hook cannot read the device key")) + // Passing trouble: retried. + #expect(outcome { $0.server = "unreachable" } == "failed: the Claude Code hook cannot reach learner-server (unreachable)") + #expect(outcome { $0.server = "error (HTTP 500)" }.hasPrefix("failed: the Claude Code hook cannot reach learner-server")) + #expect(outcome { $0.installed = false }.hasPrefix("failed: the hook is not fully wired")) + #expect(outcome { $0.permissions = false }.hasPrefix("failed: the hook is not fully wired")) + #expect(outcome { $0.config = "invalid" }.contains("learning-hook.json) is invalid")) + #expect(outcome { $0.catalogPartsNeeded = 9 } == "failed: the hook carries 5 catalog parts; the server needs 9") + #expect(describe(ClaudeHook.outcome(nil)) == "failed: the hook check printed no report") + } +} diff --git a/Tests/MediumTests/ClaudeHookJobTests.swift b/Tests/MediumTests/ClaudeHookJobTests.swift new file mode 100644 index 0000000..0eec632 --- /dev/null +++ b/Tests/MediumTests/ClaudeHookJobTests.swift @@ -0,0 +1,108 @@ +import Foundation +import Testing +@testable import LearnerDesktop +import TestSupport + +// The Claude Code hook job with a stand-in bun (a shell script that records what it was +// asked and answers like learner-server's installer): when it runs the installer, what it +// passes, and what each answer does to the job. +private final class HookFixture { + static let wired = #"{"ok":true,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":5,"catalogPartsNeeded":5}"# + let dir = TempDir("claude-hook") + let name = "test-claude-hook-\(UUID().uuidString.prefix(8))" + let hook: ClaudeHook + + /// `checks`: what successive --check runs print, the last one repeating. + init(checkout: Bool = true, installer: Bool = true, paired: Bool = true, installExit: Int = 0, checks: [String] = [HookFixture.wired]) { + if checkout { dir.write("repo/clients/uploader/src/index.ts", "") } + if installer { dir.write("repo/clients/hook/src/install.ts", "") } + for (n, text) in checks.enumerated() { dir.write("check.\(n)", text + "\n") } + let bun = dir.write("bin/bun", """ + #!/bin/bash + here="\(dir.path)" + printf '%s\\n' "$*" >> "$here/calls" + env | grep -c '^LEARNER_API_KEY=' >> "$here/key-in-env" + case "$*" in + *--check*) + n=$(cat "$here/checked" 2>/dev/null || echo 0) + echo $((n + 1)) > "$here/checked" + [ -f "$here/check.$n" ] || n=\(checks.count - 1) + cat "$here/check.$n" ;; + *) echo '{"installed":true}'; echo "learner hook install failed: settings are not a JSON object" >&2; exit \(installExit) ;; + esac + """, executable: true) + var c = ClaudeHook.Config() + c.jobName = name + c.repo = dir.file("repo") + c.bun = bun + c.git = "/usr/bin/false" + c.serverURL = { "https://learner.example/learner-api" } + c.clientId = { "a-mac" } + c.paired = { paired } + c.timeout = 20 + c.updateCheckout = false + hook = ClaudeHook(config: c) + } + + deinit { try? FileManager.default.removeItem(atPath: Job.stateDir + "/\(name).json") } + + var calls: [String] { dir.read("calls").split(separator: "\n").map(String.init) } +} + +@Suite("Claude Code hook job (stand-in bun, real processes)", .tags(.medium, .sessions), .quietLog, .serialized, .timeLimit(.minutes(1))) struct ClaudeHookJobTests { + @Test func itInstallsThenChecksAndNamesOnlyTheKeychainLookup() { + let f = HookFixture() + #expect(describe(f.hook.runOnce()) == "ok: wired into Claude Code (5 catalog parts)") + #expect(f.calls.count == 2) + let install = f.calls.first ?? "" + #expect(install.hasPrefix(f.dir.file("repo/clients/hook/src/install.ts") + " --bun " + f.dir.file("bin/bun") + " --server-url https://learner.example/learner-api --key-command-json ")) + #expect(install.contains(#"["/usr/bin/security","find-generic-password","-s","learner-server","-a","a-mac","-w"]"#)) + #expect(f.calls.last == f.dir.file("repo/clients/hook/src/install.ts") + " --check") + } + + @Test func nothingRunsWithoutACheckoutOrAPairing() { + let none = HookFixture(checkout: false, installer: false) + #expect(describe(none.hook.runOnce()) == "idle") + let unpaired = HookFixture(paired: false) + #expect(describe(unpaired.hook.runOnce()) == "idle") + #expect(none.calls.isEmpty && unpaired.calls.isEmpty) + } + + @Test func aCheckoutFromBeforeTheInstallerIsBlockedWithWhatToDo() { + let f = HookFixture(installer: false) + let said = describe(f.hook.runOnce()) + #expect(said.hasPrefix("blocked: the learner-server checkout") && said.hasSuffix("update it with git pull")) + #expect(f.calls.isEmpty) + } + + @Test func aFailedInstallIsRetriedAndSaysWhy() { + let f = HookFixture(installExit: 1) + #expect(describe(f.hook.runOnce()) == "failed: the hook installer failed: learner hook install failed: settings are not a JSON object") + #expect(f.calls.count == 1, "no check after a failed install") + } + + @Test func aRefusedKeyBlocksAndAnUnreachableServerIsRetried() { + let refused = HookFixture(checks: [#"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"refused (HTTP 403)","catalogParts":5}"#]) + #expect(describe(refused.hook.runOnce()).hasPrefix("blocked: learner-server refused the device key")) + let down = HookFixture(checks: [#"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"unreachable","catalogParts":5}"#]) + #expect(describe(down.hook.runOnce()).hasPrefix("failed: the Claude Code hook cannot reach learner-server")) + } + + @Test func aBiggerCatalogGetsAsManyCompanionsAsItNeeds() { + let f = HookFixture(checks: [ + #"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":5,"catalogPartsNeeded":7}"#, + #"{"ok":true,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":7,"catalogPartsNeeded":7}"#, + ]) + #expect(describe(f.hook.runOnce()) == "ok: wired into Claude Code (7 catalog parts)") + #expect(f.calls.count == 4) + #expect(f.calls[2].hasSuffix(" --catalog-parts 7")) + } + + @Test func theInstallerNeverGetsTheKeyInItsEnvironment() { + let f = HookFixture() + _ = f.hook.runOnce() + // Unless the test process itself was started with one (it is not, in any lane). + let leaked = f.dir.read("key-in-env").split(separator: "\n").contains { $0 != "0" } + #expect(leaked == (ProcessInfo.processInfo.environment["LEARNER_API_KEY"] != nil)) + } +} diff --git a/config/learner-server.ref b/config/learner-server.ref index 7605356..c886806 100644 --- a/config/learner-server.ref +++ b/config/learner-server.ref @@ -1 +1 @@ -84fb766b51611fd54d0b3d8c22d0372cc18109d9 +6eb8c4674c7ce2182e6ac5b234821cdf8bb1d9f3 diff --git a/menu-bar-app/ClaudeHook.swift b/menu-bar-app/ClaudeHook.swift new file mode 100644 index 0000000..7426489 --- /dev/null +++ b/menu-bar-app/ClaudeHook.swift @@ -0,0 +1,162 @@ +import Foundation + +// MARK: - Claude Code hook + +/// Learner's live hook in every Claude Code session on this Mac. +/// +/// Claude Code reads its hooks from ~/.claude/settings.json, and so does the Code tab of the +/// Claude desktop app (it runs the same Claude Code), so one user-level install covers both. +/// A chat in the Claude desktop app or on claude.ai runs no hooks at all: those reach +/// learner-server afterwards, through the chat archive (Vault, Archive). +/// +/// The hook and its installer are learner-server's own code (`clients/hook`), run with bun +/// from the same checkout as the uploader. This job runs the installer, pointed at the +/// paired server and at the Keychain lookup for the device key (the key itself is never +/// passed, written or logged), and then the installer's `--check`, which asks the server +/// with that key. It runs at launch and every few hours, so a settings file that lost the +/// hook, or a server that moved, is put right without anyone noticing. +final class ClaudeHook: Sendable { + struct Config: Sendable { + var jobName = "ClaudeHook" + var period: TimeInterval = 6 * 3600 + var firstRun: TimeInterval = 20 + /// The learner-server checkout (the uploader's). + var repo = CLISessions.repo + var bun = NSHomeDirectory() + "/.bun/bin/bun" + var git = "/usr/bin/git" + var serverURL: @Sendable () -> String = { LearnerAPI.baseURL } + var clientId: @Sendable () -> String = { LearnerAPI.clientId } + /// Whether this Mac holds a device key; unpaired, there is nothing to wire yet. + var paired: @Sendable () -> Bool = { LearnerRPC.shared.key() != nil } + /// Added to the installer's environment (tests: a scratch ~/.claude). + var environment: [String: String] = [:] + var timeout: TimeInterval = 60 + /// A checkout from before the installer existed is brought up to date once + /// (fast-forward only, and only when it has no local changes). + var updateCheckout = true + } + + /// The installer's `--check` report. + struct Check: Equatable { + var ok = false + var installed = false + var permissions = false + var config = "missing" + var server = "unreachable" + var catalogParts = 0 + var catalogPartsNeeded: Int? + } + + static let shared = ClaudeHook() + /// The most catalog companions the installer accepts. + static let maxCatalogParts = 12 + + let config: Config + // nonisolated(unsafe): assigned once at the end of init (its body needs `self`); only read after. + nonisolated(unsafe) private(set) var job: Job! + private let log = Log("ClaudeHook") + + init(config: Config = Config()) { + self.config = config + job = Job(config.jobName, period: config.period, firstRun: config.firstRun, backoff: Backoff(base: 300, max: 3600), + problemGrace: 900) { [weak self] _ in self?.runOnce() ?? .idle } + } + + var installer: String { config.repo + "/clients/hook/src/install.ts" } + + /// How the hook reads the device key: the same Keychain lookup the app uses. + static func keyCommand(clientId: String) -> [String] { + ["/usr/bin/security", "find-generic-password", "-s", Pairing.keychainService, "-a", clientId, "-w"] + } + + /// The installer's arguments. They name how to read the key, never the key. + static func installArguments(installer: String, bun: String, serverURL: String, clientId: String, catalogParts: Int? = nil) -> [String] { + let command = (try? JSONSerialization.data(withJSONObject: keyCommand(clientId: clientId), options: [.withoutEscapingSlashes])).map { String(decoding: $0, as: UTF8.self) } ?? "[]" + return [installer, "--bun", bun, "--server-url", serverURL, "--key-command-json", command] + + (catalogParts.map { ["--catalog-parts", String($0)] } ?? []) + } + + /// The report: the last line of output that is a JSON object (bun may print before it). + static func parseCheck(_ output: String) -> Check? { + for line in output.split(separator: "\n").reversed() { + guard let j = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? [String: Any], j["ok"] is Bool else { continue } + return Check(ok: j["ok"] as? Bool ?? false, installed: j["installed"] as? Bool ?? false, + permissions: j["permissions"] as? Bool ?? false, config: j["config"] as? String ?? "missing", + server: j["server"] as? String ?? "unreachable", catalogParts: j["catalogParts"] as? Int ?? 0, + catalogPartsNeeded: j["catalogPartsNeeded"] as? Int) + } + return nil + } + + /// What a check means for the tray. Refused or keyless needs the owner (blocked); the + /// rest is retried. + static func outcome(_ check: Check?) -> Job.Outcome { + guard let c = check else { return .failed("the hook check printed no report") } + if c.ok { return .ok("wired into Claude Code (\(c.catalogParts) catalog parts)") } + if c.server == "no credential" { return .blocked("the Claude Code hook cannot read the device key (Keychain \(Pairing.keychainService))") } + if c.server.hasPrefix("refused") { + return .blocked("learner-server refused the device key for the Claude Code hook (\(c.server)); the server may be older than this app") + } + if c.server != "ok" { return .failed("the Claude Code hook cannot reach learner-server (\(c.server))") } + if !c.installed || !c.permissions { return .failed("the hook is not fully wired in ~/.claude/settings.json") } + if c.config != "ok" { return .failed("the hook's config (~/.claude/learning-hook.json) is \(c.config)") } + return .failed("the hook carries \(c.catalogParts) catalog parts; the server needs \(c.catalogPartsNeeded.map(String.init) ?? "more")") + } + + /// The last line a program printed, short enough for a tray tooltip. + static func lastLine(_ r: ChildProcess.Result) -> String { + if let why = r.stopped { return why } + let line = r.output.split(separator: "\n").last.map(String.init) ?? "exit \(r.status.map(String.init) ?? "?")" + return String(line.prefix(200)) + } + + private var environment: [String: String] { ChildProcess.toolEnvironment.merging(config.environment) { _, new in new } } + + private func install(catalogParts: Int? = nil) -> ChildProcess.Result { + ChildProcess.run(config.bun, Self.installArguments(installer: installer, bun: config.bun, serverURL: config.serverURL(), + clientId: config.clientId(), catalogParts: catalogParts), + timeout: config.timeout, env: environment, stderr: true) + } + + private func check() -> Check? { + Self.parseCheck(ChildProcess.run(config.bun, [installer, "--check"], timeout: config.timeout, env: environment).output) + } + + /// Brings a checkout without the installer up to date. nil when the installer is there + /// afterwards, else why not. + private func update() -> String? { + let status = ChildProcess.run(config.git, ["-C", config.repo, "status", "--porcelain", "--untracked-files=no"], timeout: 30, env: environment) + guard status.ok else { return "git status failed" } + guard status.output.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return "it has local changes" } + let pull = ChildProcess.run(config.git, ["-C", config.repo, "pull", "--ff-only"], timeout: 180, env: environment, stderr: true) + guard pull.ok else { return "git pull --ff-only failed: \(Self.lastLine(pull))" } + let deps = ChildProcess.run(config.bun, ["install", "--cwd", config.repo, "--frozen-lockfile"], timeout: 600, env: environment, stderr: true) + guard deps.ok else { return "bun install failed: \(Self.lastLine(deps))" } + guard FileManager.default.fileExists(atPath: installer) else { return "its newest commit has no installer" } + log.info("updated the learner-server checkout to get the hook installer") + return nil + } + + func runOnce() -> Job.Outcome { + let fm = FileManager.default + // No checkout or no bun: the uploader already says so; nothing to add here. + guard fm.fileExists(atPath: config.repo + "/clients"), fm.isExecutableFile(atPath: config.bun) else { + return idleOrRecovered(job, "no learner-server checkout on this Mac") + } + guard config.paired() else { return idleOrRecovered(job, "not paired yet") } + if !fm.fileExists(atPath: installer) { + guard config.updateCheckout else { return .blocked("the learner-server checkout (\(config.repo)) has no hook installer; update it with git pull") } + if let why = update() { return .blocked("the learner-server checkout (\(config.repo)) has no hook installer and was not updated: \(why)") } + } + let first = install() + guard first.ok else { return .failed("the hook installer failed: \(Self.lastLine(first))") } + var report = check() + // The server's catalog outgrew the companions that carry it: install as many as it needs. + if let c = report, !c.ok, c.server == "ok", let needed = c.catalogPartsNeeded, needed > c.catalogParts, needed <= Self.maxCatalogParts { + let again = install(catalogParts: needed) + guard again.ok else { return .failed("the hook installer failed: \(Self.lastLine(again))") } + report = check() + } + return Self.outcome(report) + } +} diff --git a/menu-bar-app/LearnerRPC.swift b/menu-bar-app/LearnerRPC.swift index ef743ed..adb5211 100644 --- a/menu-bar-app/LearnerRPC.swift +++ b/menu-bar-app/LearnerRPC.swift @@ -210,12 +210,14 @@ enum LearnerAPI { /// registers them with the Scheduler, whose ticks run them) before `Scheduler.start()`. enum ChatAndOutboxJobs { /// Export (hourly), Archive (launch, after each export, hourly), Outbox (8 s), Heartbeat - /// (5 min, `heartbeat` builds its input only when one is due), UpdateCheck (1 min). + /// (5 min, `heartbeat` builds its input only when one is due), UpdateCheck (1 min), + /// ClaudeHook (launch, then every 6 h). static func install(heartbeat: @escaping @Sendable () -> [String: Any]) { _ = VaultExport.shared _ = Archive.shared OutboxSender.shared.setHeartbeatInput(heartbeat) _ = ScreenpipeUpdateCheck.shared + _ = ClaudeHook.shared } /// At quit, after the outbox drain: stop child programs that would outlive the app. From cb636b877f7a3d072999c6df0afdc407394c1fc1 Mon Sep 17 00:00:00 2001 From: onthegonow <118165318+onthegonow@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:35:54 +0000 Subject: [PATCH 2/3] Heavy hook test: one #require per statement (a nested one does not expand) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SPMjtan22onKA34S16vwNd --- Tests/HeavyTests/PairingE2ETests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/HeavyTests/PairingE2ETests.swift b/Tests/HeavyTests/PairingE2ETests.swift index 73fe6e4..32a755b 100644 --- a/Tests/HeavyTests/PairingE2ETests.swift +++ b/Tests/HeavyTests/PairingE2ETests.swift @@ -243,7 +243,8 @@ struct PairingE2ETests { let harness = try Harness(["--topology", "same-machine"]) defer { harness.stop() } let ready = try #require(harness.ready(), "the harness did not start: \(harness.output.suffix(1500))") - let data = try #require(harness.pairingFile(try #require(ready["pairingFile"] as? String))) + let pairingPath = try #require(ready["pairingFile"] as? String) + let data = try #require(harness.pairingFile(pairingPath)) guard case .success(let p) = Pairing.parse(data) else { Issue.record("the harness's payload does not parse"); return } // The key reaches the hook from a mode-600 file in the scratch folder (the Keychain's From c0a27a025157e1eddcffbad490c52097939f4798 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 17 Nov 2026 23:28:24 +0000 Subject: [PATCH 3/3] Heavy hook test: send a bare UUID session id (the hook rejects anything else and fails open) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01SPMjtan22onKA34S16vwNd --- Tests/HeavyTests/PairingE2ETests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/HeavyTests/PairingE2ETests.swift b/Tests/HeavyTests/PairingE2ETests.swift index 32a755b..daa1297 100644 --- a/Tests/HeavyTests/PairingE2ETests.swift +++ b/Tests/HeavyTests/PairingE2ETests.swift @@ -280,7 +280,8 @@ struct PairingE2ETests { // One prompt, through the command Claude Code would run. let command = try #require(((hooks["UserPromptSubmit"]?.first?["hooks"] as? [[String: Any]])?.first)?["command"] as? String) - let session = "e2e-\(UUID().uuidString.lowercased())" + // A bare UUID: the hook validates session_id as one and stays silent (fails open) otherwise. + let session = UUID().uuidString.lowercased() let prompt = try JSONSerialization.data(withJSONObject: ["hook_event_name": "UserPromptSubmit", "session_id": session, "prompt": "Explain why a B-tree index speeds up this lookup."]) let turn = ChildProcess.run("/bin/sh", ["-c", command], timeout: 30,