From 38ce3c86e1eb822d7b2d3f7e5da96211ce43308a Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Date: Thu, 29 Oct 2026 19:47:32 -0400 Subject: [PATCH 1/3] feat(context): add explicit shadow forks, return, and promotion --- README.md | 32 ++++ Sources/SynapseCore/ShadowContextStore.swift | 151 ++++++++++++++++++ .../contextsynapse/ShadowContextCommand.swift | 39 +++++ Sources/contextsynapse/main.swift | 68 +++++--- Tests/ShadowContextTests.swift | 120 ++++++++++++++ docs/journal/DECISIONS.md | 4 + 6 files changed, 388 insertions(+), 26 deletions(-) create mode 100644 Sources/SynapseCore/ShadowContextStore.swift create mode 100644 Sources/contextsynapse/ShadowContextCommand.swift create mode 100644 Tests/ShadowContextTests.swift diff --git a/README.md b/README.md index 8c49518..f8d496a 100644 --- a/README.md +++ b/README.md @@ -277,3 +277,35 @@ log, and v0.4–v1.0 milestones. MIT — see [LICENSE](LICENSE). --- + +### Explicit Shadow Contexts (CLI) + +```bash +contextsynapse --lighthouse "Primary goal" +contextsynapse --fork-shadow "Side quest goal" +contextsynapse "work on the side quest" +contextsynapse --rsa +contextsynapse --return-primary +# Alternatively, while a shadow is active: +contextsynapse --promote-shadow +``` + +Each fork starts a new, explicitly chosen lighthouse and a separate session/RSA +history. Returning restores the primary selection without modifying its session. +Promotion changes the primary pointer while retaining previous primary files and +their IDs in `contexts.json`. Run logs include `contextID` and `shadowContext`; +shadow queries print a return breadcrumb. Weights and referee settings are shared. + +This first increment supports one active shadow, explicit return, and explicit +promotion. Nested forks are rejected. Returned shadows are retained on disk; +there is no resume/list UI yet. The SwiftUI app still uses the original primary +store; context selection is currently a CLI feature. A corrupt index fails closed. +A failed switch leaves the previous selection intact; an unselected new directory +may remain for recovery. The existing single-writer assumption still applies. + +All files stay under the existing per-user directory: `contexts.json` selects +`contexts//lighthouse.json` and `session.json`, or the original primary +files. Back up the index and context files together. To reverse a promotion, +stop writers and restore the prior index from backup (or use its retained +`priorPrimaries` ID); do not delete context directories as a rollback mechanism. +No webcam, cursor, scroll, affect, or operator-state inference is involved. diff --git a/Sources/SynapseCore/ShadowContextStore.swift b/Sources/SynapseCore/ShadowContextStore.swift new file mode 100644 index 0000000..1974e98 --- /dev/null +++ b/Sources/SynapseCore/ShadowContextStore.swift @@ -0,0 +1,151 @@ +import Foundation + +/// CLI context selection. Weights/referee configuration remain shared; each +/// explicit anchor has a separate lighthouse and session history. A single +/// atomic index write switches selection; original primary files stay intact. +public final class ShadowContextStore { + private struct Index: Codable { + var primary = "primary" + var shadow: String? + var contexts: [String] = [] + var priorPrimaries: [String] = [] + var cleared: [String] = [] + } + public enum ContextError: LocalizedError { + case corruptIndex, missingAnchor, alreadyShadow, notShadow, invalidLabel, shadowAnchorRequired + public var errorDescription: String? { + switch self { + case .corruptIndex: return "Context index is invalid; restore it from backup before continuing." + case .missingAnchor: return "Set an explicit primary lighthouse before forking." + case .alreadyShadow: return "Return to the primary before starting another shadow context." + case .notShadow: return "No shadow context is active." + case .shadowAnchorRequired: return "Return to the primary before clearing a shadow anchor." + case .invalidLabel: return "A shadow goal must contain 1–500 non-control characters." + } + } + } + private let core: SynapseCore + private let root: URL + private let indexURL: URL + private var index: Index + public var activeID: String { index.shadow ?? index.primary } + public var isShadow: Bool { index.shadow != nil } + public var priorPrimaryIDs: [String] { index.priorPrimaries } + + public init(core: SynapseCore) throws { + self.core = core + root = core.configURL.deletingLastPathComponent() + indexURL = root.appendingPathComponent("contexts.json") + if FileManager.default.fileExists(atPath: indexURL.path) { + do { + index = try JSONDecoder().decode(Index.self, from: Data(contentsOf: indexURL)) + } catch { throw ContextError.corruptIndex } + func valid(_ id: String) -> Bool { id == "primary" || UUID(uuidString: id) != nil } + guard valid(index.primary), index.shadow.map(valid) ?? true, + index.contexts.allSatisfy({ UUID(uuidString: $0) != nil }), + index.priorPrimaries.allSatisfy(valid), + index.cleared.allSatisfy({ index.contexts.contains($0) }), + index.primary == "primary" || index.contexts.contains(index.primary), + index.shadow.map({ index.contexts.contains($0) && $0 != index.primary }) ?? true else { + throw ContextError.corruptIndex + } + } else { index = Index() } + // Fail closed rather than quietly switching anchors when selected data + // is missing or malformed. Original primary may legitimately have none. + if activeID != "primary" { + _ = try loadLighthouse() + if FileManager.default.fileExists(atPath: sessionURL.path) { + _ = try JSONDecoder().decode(SessionState.self, from: Data(contentsOf: sessionURL)) + } + } + } + + private func directory(_ id: String) -> URL { + id == "primary" ? root : root.appendingPathComponent("contexts").appendingPathComponent(id) + } + public var sessionURL: URL { directory(activeID).appendingPathComponent("session.json") } + + public func loadLighthouse() throws -> LighthouseRecord? { + if index.cleared.contains(activeID) { return nil } + if activeID == "primary" { return core.loadLighthouseRecord() } + let url = directory(activeID).appendingPathComponent("lighthouse.json") + return try JSONDecoder().decode(LighthouseRecord.self, from: Data(contentsOf: url)) + } + + public func saveLighthouse(_ content: SynapseContent, at now: Date = Date()) throws { + if activeID == "primary" { + guard core.saveLighthouse(content, at: now) else { throw CocoaError(.fileWriteUnknown) } + } else { + let record = LighthouseRecord(id: content.id, text: content.text, + fileReferences: content.fileReferences, functionNames: content.functionNames, + setAt: ISO8601DateFormatter().string(from: now)) + try JSONEncoder().encode(record).write(to: directory(activeID).appendingPathComponent("lighthouse.json"), options: .atomic) + if index.cleared.contains(activeID) { + var next = index; next.cleared.removeAll { $0 == activeID } + try commit(next) + } + } + } + + public func clearLighthouse() throws { + // An active shadow must retain a defined anchor. Returning first is an + // explicit action, and the primary clear follows existing CLI behavior. + guard !isShadow else { throw ContextError.shadowAnchorRequired } + if activeID == "primary" { core.clearLighthouse() } + else { + var next = index + if !next.cleared.contains(activeID) { next.cleared.append(activeID) } + try commit(next) // retain the old anchor file as recovery evidence + } + } + + @discardableResult + public func fork(goal: String, at now: Date = Date()) throws -> String { + guard !isShadow else { throw ContextError.alreadyShadow } + let label = goal.trimmingCharacters(in: .whitespacesAndNewlines) + guard !label.isEmpty, label.count <= 500, + label.rangeOfCharacter(from: .controlCharacters) == nil else { throw ContextError.invalidLabel } + guard try loadLighthouse() != nil else { throw ContextError.missingAnchor } + let id = UUID().uuidString + let folder = directory(id) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + let anchor = LighthouseRecord(id: UUID().uuidString, text: label, + setAt: ISO8601DateFormatter().string(from: now)) + try JSONEncoder().encode(anchor).write(to: folder.appendingPathComponent("lighthouse.json"), options: .atomic) + let session = SessionState(startedAt: now, lighthouseID: anchor.id) + try JSONEncoder().encode(session).write(to: folder.appendingPathComponent("session.json"), options: .atomic) + var next = index + next.contexts.append(id) + next.shadow = id + try commit(next) + return id + } + + public func returnToPrimary() throws { + guard isShadow else { throw ContextError.notShadow } + // Verify the destination before selecting it. + if index.primary != "primary" { + _ = try JSONDecoder().decode(LighthouseRecord.self, from: Data(contentsOf: + directory(index.primary).appendingPathComponent("lighthouse.json"))) + } + var next = index; next.shadow = nil + try commit(next) + } + + public func promoteShadow() throws { + guard let shadow = index.shadow else { throw ContextError.notShadow } + _ = try loadLighthouse() + var next = index + next.priorPrimaries.append(index.primary) + next.primary = shadow + next.shadow = nil + try commit(next) + } + + private func commit(_ next: Index) throws { + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + try encoder.encode(next).write(to: indexURL, options: .atomic) + index = next + } +} diff --git a/Sources/contextsynapse/ShadowContextCommand.swift b/Sources/contextsynapse/ShadowContextCommand.swift new file mode 100644 index 0000000..02ce155 --- /dev/null +++ b/Sources/contextsynapse/ShadowContextCommand.swift @@ -0,0 +1,39 @@ +import Foundation +import SynapseCore + +enum ShadowContextCommand { + static func prepare(args: [String], core: SynapseCore) throws -> ShadowContextStore { + let store = try ShadowContextStore(core: core) + let commands = ["--fork-shadow", "--return-primary", "--promote-shadow"] + let supplied = commands.filter { args.contains($0) } + guard supplied.count <= 1 else { throw CommandError.usage } + if let command = supplied.first { + // Management commands accept only their value and an optional user. + var remaining = Array(args.dropFirst()) + if let user = remaining.firstIndex(of: "--user"), user + 1 < remaining.count { + remaining.removeSubrange(user...user + 1) + } + if command == "--fork-shadow" { + guard remaining.count == 2, remaining[0] == command, + !remaining[1].hasPrefix("--") else { throw CommandError.usage } + let id = try store.fork(goal: remaining[1]) + print("Shadow context: \(id). Primary retained; return with --return-primary.") + } else { + guard remaining == [command] else { throw CommandError.usage } + if command == "--return-primary" { + try store.returnToPrimary(); print("Returned to primary; shadow history retained.") + } else { + try store.promoteShadow(); print("Shadow promoted to primary; previous primary files retained.") + } + } + exit(0) + } + return store + } + enum CommandError: LocalizedError { + case usage + var errorDescription: String? { + "Use one of --fork-shadow , --return-primary, or --promote-shadow, optionally with --user ." + } + } +} diff --git a/Sources/contextsynapse/main.swift b/Sources/contextsynapse/main.swift index 950d229..46b85be 100644 --- a/Sources/contextsynapse/main.swift +++ b/Sources/contextsynapse/main.swift @@ -20,6 +20,35 @@ while scanIndex < args.count { let core = SynapseCore(user: selectedUser) +// MARK: - Instrument verbs (record / export-events / events-summary) +// Terminal commands that append to or read the observation ledger, then exit. +// They never touch weights, priors, or circuit state — the ledger is an +// immutable log that circuit state is folded FROM. See docs/adr/ADR-006. +// ledgerDirectory resolves to the per-user dir (logDir is /logs). + +let ledgerDirectory = core.logDir.deletingLastPathComponent() + +if args.contains("--record") { + exit(RecordCommand.handleRecord(args: args, ledgerDirectory: ledgerDirectory).rawValue) +} + +if args.contains("--export-events") { + exit(RecordCommand.handleExportEvents(args: args, ledgerDirectory: ledgerDirectory).rawValue) +} + +if args.contains("--events-summary") { + exit(RecordCommand.handleEventsSummary(ledgerDirectory: ledgerDirectory).rawValue) +} + +// Explicit CLI context selection; corrupt indexes fail before any anchor use. +let contextStore: ShadowContextStore +do { + contextStore = try ShadowContextCommand.prepare(args: args, core: core) +} catch { + fputs("Context selection failed: \(error.localizedDescription)\n", stderr) + exit(2) +} + // MARK: - --lighthouse and --resync // Persistence lives in SynapseCore (LighthouseStore.swift) so the GUI and // tests reach the same store. Legacy /lighthouse.json files written by @@ -28,7 +57,8 @@ let core = SynapseCore(user: selectedUser) if let lighthouseIdx = args.firstIndex(of: "--lighthouse"), lighthouseIdx + 1 < args.count { let label = args[lighthouseIdx + 1] let content = SynapseContent(id: UUID().uuidString, text: label) - core.saveLighthouse(content) + do { try contextStore.saveLighthouse(content) } + catch { fputs("Cannot save lighthouse: \(error.localizedDescription)\n", stderr); exit(1) } RavenRenderer.render(state: .perched, frameIndex: 0, lighthouseLabel: label, rotScore: 0.0) print("") @@ -38,7 +68,8 @@ if let lighthouseIdx = args.firstIndex(of: "--lighthouse"), lighthouseIdx + 1 < } if args.contains("--resync") { - core.clearLighthouse() + do { try contextStore.clearLighthouse() } + catch { fputs("Cannot clear lighthouse: \(error.localizedDescription)\n", stderr); exit(1) } RavenRenderer.render(state: .resync, frameIndex: 0, lighthouseLabel: nil, rotScore: 0.0) print("") print("\u{001B}[38;5;51m⚓ Lighthouse cleared. Set a new one with --lighthouse \"description\"\u{001B}[0m") @@ -72,12 +103,12 @@ if let refereeIdx = args.firstIndex(of: "--referee"), refereeIdx + 1 < args.coun // epochs. This is the evidence layer — drift claims point here. if args.contains("--rsa") { - let manager = core.makeSynapseManager() + let manager = SynapseManager(sessionURL: contextStore.sessionURL, lighthouse: try contextStore.loadLighthouse()) let epochs = await manager.epochs if let latest = epochs.last { print(RSARenderer.heatmap(latest)) print(RSARenderer.saliencyStrip(epochs)) - } else if core.loadLighthouseRecord() == nil { + } else if try contextStore.loadLighthouse() == nil { print("No lighthouse set — RSA epochs are only meaningful relative to an anchor.") print("Set one: contextsynapse --lighthouse \"\"") } else { @@ -146,26 +177,6 @@ if let importIndex { exit(1) } -// MARK: - Instrument verbs (record / export-events / events-summary) -// Terminal commands that append to or read the observation ledger, then exit. -// They never touch weights, priors, or circuit state — the ledger is an -// immutable log that circuit state is folded FROM. See docs/adr/ADR-006. -// ledgerDirectory resolves to the per-user dir (logDir is /logs). - -let ledgerDirectory = core.logDir.deletingLastPathComponent() - -if args.contains("--record") { - exit(RecordCommand.handleRecord(args: args, ledgerDirectory: ledgerDirectory).rawValue) -} - -if args.contains("--export-events") { - exit(RecordCommand.handleExportEvents(args: args, ledgerDirectory: ledgerDirectory).rawValue) -} - -if args.contains("--events-summary") { - exit(RecordCommand.handleEventsSummary(ledgerDirectory: ledgerDirectory).rawValue) -} - // MARK: - Regular query processing var weights = core.loadOrCreateDefaultWeights() @@ -298,7 +309,7 @@ let currentContent = SynapseContent( functionNames: [] ) -let activeLighthouseRecord = core.loadLighthouseRecord() +let activeLighthouseRecord = try contextStore.loadLighthouse() let activeLighthouse = activeLighthouseRecord?.content let refereeMode = core.loadRefereeConfig().mode var rotScore: Double = 0.0 @@ -307,7 +318,7 @@ var edgarState: RavenState = .dormant // Reuse the record loaded above — loadLighthouseRecord() re-reads disk and // can re-run the legacy-path migration side effect if called twice. -let manager = SynapseManager(sessionURL: core.sessionURL, lighthouse: activeLighthouseRecord) +let manager = SynapseManager(sessionURL: contextStore.sessionURL, lighthouse: activeLighthouseRecord) if let epoch = await manager.observe(currentContent, event: .fileSave) { rotScore = max(0.0, min(1.0, 1.0 - epoch.lighthouseSaliency)) decayWeightNow = epoch.observedDecayWeight @@ -315,6 +326,9 @@ if let epoch = await manager.observe(currentContent, event: .fileSave) { } // MARK: - Breadcrumb +if contextStore.isShadow { + print("Shadow context: \(contextStore.activeID) — return with --return-primary") +} // Re-sync line before the prompt, also appended to logs/breadcrumb-.txt. if let record = activeLighthouseRecord { BreadcrumbWriter.emit(for: record, rotScore: rotScore, core: core) @@ -358,6 +372,8 @@ let decaySnapshot = SynapseCore.RunLog.DecaySnapshot( ) var runContext: [String: String] = [ "user": selectedUser, + "contextID": contextStore.activeID, + "shadowContext": contextStore.isShadow ? "true" : "false", "app": flagApp ?? "unknown", "focus": flagFocus ?? "unknown", "timeBucket": activeTriggers.joined(separator: ","), diff --git a/Tests/ShadowContextTests.swift b/Tests/ShadowContextTests.swift new file mode 100644 index 0000000..4cd8ad7 --- /dev/null +++ b/Tests/ShadowContextTests.swift @@ -0,0 +1,120 @@ +import XCTest +@testable import SynapseCore + +final class ShadowContextTests: XCTestCase { + private func withCore(_ body: (SynapseCore) async throws -> Void) async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let core = SynapseCore(baseOverride: root) + try await body(core) + } + + func testForkReturnAndPromotionPreserveIndependentHistories() async throws { + try await withCore { core in + XCTAssertTrue(core.saveLighthouse(SynapseContent(id: "primary-anchor", text: "primary goal"))) + let primary = core.makeSynapseManager() + await primary.observe(SynapseContent(id: "primary-work", text: "primary work"), event: .gitCommit) + let original = try Data(contentsOf: core.sessionURL) + let store = try ShadowContextStore(core: core) + let shadow = try store.fork(goal: "side quest") + XCTAssertNotEqual(store.sessionURL, core.sessionURL) + XCTAssertEqual(try store.loadLighthouse()?.text, "side quest") + let manager = SynapseManager(sessionURL: store.sessionURL, lighthouse: try store.loadLighthouse()) + await manager.observe(SynapseContent(id: "shadow-work", text: "shadow work"), event: .buildFailure) + let shadowURL = store.sessionURL + let shadowBytes = try Data(contentsOf: shadowURL) + XCTAssertEqual(try Data(contentsOf: core.sessionURL), original) + XCTAssertThrowsError(try store.fork(goal: "nested")) + let resumed = try ShadowContextStore(core: core) + XCTAssertEqual(resumed.activeID, shadow) + try resumed.promoteShadow() + XCTAssertFalse(resumed.isShadow) + XCTAssertEqual(resumed.activeID, shadow) + XCTAssertEqual(resumed.priorPrimaryIDs, ["primary"]) + XCTAssertEqual(try Data(contentsOf: resumed.sessionURL), shadowBytes) + XCTAssertEqual(try Data(contentsOf: core.sessionURL), original) + // Forking from a promoted primary must return to that context. + _ = try resumed.fork(goal: "second side quest") + try resumed.returnToPrimary() + XCTAssertEqual(resumed.activeID, shadow) + XCTAssertEqual(try Data(contentsOf: resumed.sessionURL), shadowBytes) + } + } + + func testPromotedPrimaryCanBeClearedAndExplicitlyReanchored() async throws { + try await withCore { core in + XCTAssertTrue(core.saveLighthouse(SynapseContent(id: "p", text: "original"))) + let store = try ShadowContextStore(core: core) + _ = try store.fork(goal: "promoted") + XCTAssertThrowsError(try store.clearLighthouse()) + try store.promoteShadow() + try store.clearLighthouse() + XCTAssertNil(try ShadowContextStore(core: core).loadLighthouse()) + XCTAssertEqual(core.loadLighthouseRecord()?.text, "original") + try store.saveLighthouse(SynapseContent(id: "replacement", text: "explicit replacement")) + XCTAssertEqual(try ShadowContextStore(core: core).loadLighthouse()?.id, "replacement") + } + } + + func testReturnRestoresOriginalPrimaryAndRetainsShadow() async throws { + try await withCore { core in + XCTAssertTrue(core.saveLighthouse(SynapseContent(id: "primary", text: "primary"))) + let store = try ShadowContextStore(core: core) + _ = try store.fork(goal: "shadow") + let shadowURL = store.sessionURL + try store.returnToPrimary() + XCTAssertEqual(store.activeID, "primary") + XCTAssertEqual(try store.loadLighthouse()?.id, "primary") + XCTAssertTrue(FileManager.default.fileExists(atPath: shadowURL.path)) + XCTAssertThrowsError(try store.returnToPrimary()) + XCTAssertThrowsError(try store.promoteShadow()) + } + } + + func testInvalidForkAndCorruptIndexFailBeforeSelectionChanges() async throws { + try await withCore { core in + let store = try ShadowContextStore(core: core) + XCTAssertThrowsError(try store.fork(goal: "no anchor")) + XCTAssertTrue(core.saveLighthouse(SynapseContent(id: "p", text: "primary"))) + XCTAssertThrowsError(try store.fork(goal: " \n ")) + let index = core.configURL.deletingLastPathComponent().appendingPathComponent("contexts.json") + try Data("broken".utf8).write(to: index) + XCTAssertThrowsError(try ShadowContextStore(core: core)) + try FileManager.default.removeItem(at: index) + // A directory at the index destination makes pointer persistence fail. + try FileManager.default.createDirectory(at: index, withIntermediateDirectories: false) + XCTAssertThrowsError(try store.fork(goal: "unselected orphan")) + XCTAssertEqual(store.activeID, "primary") + XCTAssertEqual(core.loadLighthouseRecord()?.id, "p") + } + } + + func testCLIExplicitForkQueryReturnAndPromotion() throws { + let user = "shadow-cli-" + UUID().uuidString + let root = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/ContextSynapse/users/" + user) + defer { try? FileManager.default.removeItem(at: root) } + let cli = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + .appendingPathComponent(".build/debug/contextsynapse") + func invoke(_ arguments: [String]) throws -> Int32 { + let task = Process(); task.executableURL = cli + task.arguments = arguments + ["--user", user] + task.standardOutput = FileHandle.nullDevice; task.standardError = FileHandle.nullDevice + try task.run(); task.waitUntilExit(); return task.terminationStatus + } + XCTAssertEqual(try invoke(["--lighthouse", "primary goal"]), 0) + XCTAssertEqual(try invoke(["primary work"]), 0) + let session = root.appendingPathComponent("session.json") + let original = try Data(contentsOf: session) + XCTAssertEqual(try invoke(["--fork-shadow", "explicit side goal"]), 0) + XCTAssertEqual(try invoke(["side work"]), 0) + XCTAssertEqual(try Data(contentsOf: session), original) + XCTAssertEqual(try invoke(["--return-primary"]), 0) + XCTAssertEqual(try invoke(["--rsa"]), 0) + XCTAssertEqual(try invoke(["--fork-shadow", "second goal"]), 0) + XCTAssertEqual(try invoke(["--promote-shadow"]), 0) + XCTAssertEqual(try invoke(["--rsa"]), 0) + XCTAssertEqual(try Data(contentsOf: session), original) + XCTAssertEqual(try invoke(["--return-primary", "--promote-shadow"]), 2) + } +} diff --git a/docs/journal/DECISIONS.md b/docs/journal/DECISIONS.md index afeb86d..d16d330 100644 --- a/docs/journal/DECISIONS.md +++ b/docs/journal/DECISIONS.md @@ -248,3 +248,7 @@ --uninstall .` removes the hook; the sign-off/date commits themselves are not reversed in place — a correction gets a new dated entry, not an edit to this one. + +## 2026-10-29 — Explicit Shadow Context CLI increment + +- 2026-10-29 · Implement explicit `--fork-shadow `, `--return-primary`, and `--promote-shadow` commands. Each fork gets a separate UUID-addressed lighthouse/session directory; a single atomic contexts.json index write selects the active context. Primary files are retained across return and promotion, prior primary IDs remain in the index, and failed pointer writes preserve the old selection. No nested forks or inferred anchors; weights/referee remain shared. CLI run logs carry context IDs and shadow queries emit a return breadcrumb. SwiftUI selection and a retained-shadow resume/list UI remain deferred. Reverse: stop writers and restore the previous index from backup/retained priorPrimaries IDs; preserve all context data. From e96c019d85ca3c31324e8ed0fe1f65e067b4db0f Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Date: Thu, 29 Oct 2026 20:00:14 -0400 Subject: [PATCH 2/3] fix(context): handle load errors and verify shadow persistence Signed-off-by: Mazze LeCzzare Frazer --- CLAUDE.md | 12 ++++++++++++ Sources/contextsynapse/main.swift | 20 +++++++++++++++++--- Tests/ShadowContextTests.swift | 5 +++++ docs/journal/DECISIONS.md | 2 ++ 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 17a05a0..8ea1bd2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -215,6 +215,18 @@ let lambda = lambdaBase - `EdgarIntervention.render(intervention:)` — 4-choice context rot UI: return / promote / continue / dismiss - `ANSI` color constants: purple=dormant, cyan=perched, yellow=stirring, orange=alarmed, red/white=cauterize +### CLI context selection and command precedence (Shadow Context increment) + +The CLI initializes the selected user, then handles `--record`, `--export-events`, +and `--events-summary` before loading the context index. This precedence changed +explicitly so a corrupt context index cannot disable collection. Mixed instrument and context/state commands are rejected before initialization; +there is no silent precedence between these command families. +Context management then handles explicit fork/return/promotion. Lighthouse writes +and reads use the selected context; loads fail with an error instead of an +uncaught top-level throw. RSA and query observations use its separate session URL. +Run logs carry context IDs. The SwiftUI app still uses the original primary store. +The historical flow below predates this selection layer. + ### CLI (`main.swift`) — Complete Flow ``` diff --git a/Sources/contextsynapse/main.swift b/Sources/contextsynapse/main.swift index 46b85be..4564eee 100644 --- a/Sources/contextsynapse/main.swift +++ b/Sources/contextsynapse/main.swift @@ -6,6 +6,12 @@ import SynapseCore // He renders on every query. His state IS the system's state. let args = CommandLine.arguments +let instrumentFlags = ["--record", "--export-events", "--events-summary"] +let stateFlags = ["--fork-shadow", "--return-primary", "--promote-shadow", "--lighthouse", "--resync", "--rsa", "--referee", "--export", "--import"] +if instrumentFlags.contains(where: args.contains) && stateFlags.contains(where: args.contains) { + fputs("Instrument and context/state commands cannot be combined\n", stderr) + exit(2) +} // MARK: - Global flag scan (pre-init) var selectedUser = "default" @@ -97,18 +103,26 @@ if let refereeIdx = args.firstIndex(of: "--referee"), refereeIdx + 1 < args.coun exit(0) } +// Resolve once with a recoverable error; top-level throwing loads can abort. +let selectedLighthouseRecord: LighthouseRecord? +do { selectedLighthouseRecord = try contextStore.loadLighthouse() } +catch { + fputs("Cannot load selected lighthouse: \(error.localizedDescription)\n", stderr) + exit(1) +} + // MARK: - --rsa // Render the session's RSA state: latest similarity heatmap over // [lighthouse + tracked synapses] and the anchor-saliency sparkline across // epochs. This is the evidence layer — drift claims point here. if args.contains("--rsa") { - let manager = SynapseManager(sessionURL: contextStore.sessionURL, lighthouse: try contextStore.loadLighthouse()) + let manager = SynapseManager(sessionURL: contextStore.sessionURL, lighthouse: selectedLighthouseRecord) let epochs = await manager.epochs if let latest = epochs.last { print(RSARenderer.heatmap(latest)) print(RSARenderer.saliencyStrip(epochs)) - } else if try contextStore.loadLighthouse() == nil { + } else if selectedLighthouseRecord == nil { print("No lighthouse set — RSA epochs are only meaningful relative to an anchor.") print("Set one: contextsynapse --lighthouse \"\"") } else { @@ -309,7 +323,7 @@ let currentContent = SynapseContent( functionNames: [] ) -let activeLighthouseRecord = try contextStore.loadLighthouse() +let activeLighthouseRecord = selectedLighthouseRecord let activeLighthouse = activeLighthouseRecord?.content let refereeMode = core.loadRefereeConfig().mode var rotScore: Double = 0.0 diff --git a/Tests/ShadowContextTests.swift b/Tests/ShadowContextTests.swift index 4cd8ad7..63a1704 100644 --- a/Tests/ShadowContextTests.swift +++ b/Tests/ShadowContextTests.swift @@ -23,6 +23,9 @@ final class ShadowContextTests: XCTestCase { await manager.observe(SynapseContent(id: "shadow-work", text: "shadow work"), event: .buildFailure) let shadowURL = store.sessionURL let shadowBytes = try Data(contentsOf: shadowURL) + let savedShadow = try JSONDecoder().decode(SessionState.self, from: shadowBytes) + XCTAssertEqual(savedShadow.epochs.count, 1) + XCTAssertTrue(savedShadow.synapses.contains { $0.id == "shadow-work" }) XCTAssertEqual(try Data(contentsOf: core.sessionURL), original) XCTAssertThrowsError(try store.fork(goal: "nested")) let resumed = try ShadowContextStore(core: core) @@ -102,6 +105,8 @@ final class ShadowContextTests: XCTestCase { task.standardOutput = FileHandle.nullDevice; task.standardError = FileHandle.nullDevice try task.run(); task.waitUntilExit(); return task.terminationStatus } + XCTAssertEqual(try invoke(["--record", "git.commit", "--fork-shadow", "mixed"]), 2) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) XCTAssertEqual(try invoke(["--lighthouse", "primary goal"]), 0) XCTAssertEqual(try invoke(["primary work"]), 0) let session = root.appendingPathComponent("session.json") diff --git a/docs/journal/DECISIONS.md b/docs/journal/DECISIONS.md index d16d330..c5a90eb 100644 --- a/docs/journal/DECISIONS.md +++ b/docs/journal/DECISIONS.md @@ -252,3 +252,5 @@ ## 2026-10-29 — Explicit Shadow Context CLI increment - 2026-10-29 · Implement explicit `--fork-shadow `, `--return-primary`, and `--promote-shadow` commands. Each fork gets a separate UUID-addressed lighthouse/session directory; a single atomic contexts.json index write selects the active context. Primary files are retained across return and promotion, prior primary IDs remain in the index, and failed pointer writes preserve the old selection. No nested forks or inferred anchors; weights/referee remain shared. CLI run logs carry context IDs and shadow queries emit a return breadcrumb. SwiftUI selection and a retained-shadow resume/list UI remain deferred. Reverse: stop writers and restore the previous index from backup/retained priorPrimaries IDs; preserve all context data. + +- 2026-10-29 · Address Shadow Context review gaps: selected lighthouse reads use a caught error path; tests assert a persisted shadow epoch and synapse, not merely file existence. Mixed instrument/context-state commands now fail before initialization, and CLAUDE.md documents why standalone instrument commands precede context loading. Verified release-independent debug build and five focused tests. Reverse: revert this focused patch only with equivalent persistence and error-path coverage. From 0d383c80bd347d8aefc281f0ed4d9fff9dfd4db6 Mon Sep 17 00:00:00 2001 From: Mazze LeCzzare Frazer Date: Mon, 9 Nov 2026 20:42:14 +0000 Subject: [PATCH 3/3] fix(shadow): let --return-primary leave a damaged shadow ShadowContextStore probed the active shadow's lighthouse and session in init, and the CLI built the store before dispatching --return-primary, so a missing or malformed shadow file blocked the documented way out. The return path now skips that probe; the index is still validated and every other path still fails closed. Regression tests cover a missing anchor, a malformed session and a corrupt index. Co-Authored-By: Claude Opus 5.5 --- Sources/SynapseCore/ShadowContextStore.swift | 7 ++- .../contextsynapse/ShadowContextCommand.swift | 5 +- Tests/ShadowContextRecoveryTests.swift | 48 +++++++++++++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 Tests/ShadowContextRecoveryTests.swift diff --git a/Sources/SynapseCore/ShadowContextStore.swift b/Sources/SynapseCore/ShadowContextStore.swift index 1974e98..59e88ce 100644 --- a/Sources/SynapseCore/ShadowContextStore.swift +++ b/Sources/SynapseCore/ShadowContextStore.swift @@ -32,7 +32,10 @@ public final class ShadowContextStore { public var isShadow: Bool { index.shadow != nil } public var priorPrimaryIDs: [String] { index.priorPrimaries } - public init(core: SynapseCore) throws { + /// - Parameter verifyActiveContext: probe the selected shadow's anchor and + /// session before use. Pass `false` only for the explicit return path, so a + /// damaged shadow can still be left; the index itself is always validated. + public init(core: SynapseCore, verifyActiveContext: Bool = true) throws { self.core = core root = core.configURL.deletingLastPathComponent() indexURL = root.appendingPathComponent("contexts.json") @@ -52,7 +55,7 @@ public final class ShadowContextStore { } else { index = Index() } // Fail closed rather than quietly switching anchors when selected data // is missing or malformed. Original primary may legitimately have none. - if activeID != "primary" { + if verifyActiveContext, activeID != "primary" { _ = try loadLighthouse() if FileManager.default.fileExists(atPath: sessionURL.path) { _ = try JSONDecoder().decode(SessionState.self, from: Data(contentsOf: sessionURL)) diff --git a/Sources/contextsynapse/ShadowContextCommand.swift b/Sources/contextsynapse/ShadowContextCommand.swift index 02ce155..d9afb41 100644 --- a/Sources/contextsynapse/ShadowContextCommand.swift +++ b/Sources/contextsynapse/ShadowContextCommand.swift @@ -3,7 +3,10 @@ import SynapseCore enum ShadowContextCommand { static func prepare(args: [String], core: SynapseCore) throws -> ShadowContextStore { - let store = try ShadowContextStore(core: core) + // --return-primary is the documented way out of a damaged shadow, so it + // must not depend on the shadow's own files being readable. + let store = try ShadowContextStore(core: core, + verifyActiveContext: !args.contains("--return-primary")) let commands = ["--fork-shadow", "--return-primary", "--promote-shadow"] let supplied = commands.filter { args.contains($0) } guard supplied.count <= 1 else { throw CommandError.usage } diff --git a/Tests/ShadowContextRecoveryTests.swift b/Tests/ShadowContextRecoveryTests.swift new file mode 100644 index 0000000..1025331 --- /dev/null +++ b/Tests/ShadowContextRecoveryTests.swift @@ -0,0 +1,48 @@ +import XCTest +@testable import SynapseCore + +/// Regression: a missing or malformed shadow must not block the explicit +/// return. Normal construction still fails closed on damaged shadow data. +final class ShadowContextRecoveryTests: XCTestCase { + private func withShadow(_ body: (SynapseCore, URL) throws -> Void) throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let core = SynapseCore(baseOverride: root) + XCTAssertTrue(core.saveLighthouse(SynapseContent(id: "primary", text: "primary"))) + let store = try ShadowContextStore(core: core) + _ = try store.fork(goal: "shadow") + try body(core, store.sessionURL.deletingLastPathComponent()) + } + + private func assertReturnRecovers(_ core: SynapseCore) throws { + XCTAssertThrowsError(try ShadowContextStore(core: core)) + let recovery = try ShadowContextStore(core: core, verifyActiveContext: false) + XCTAssertTrue(recovery.isShadow) + try recovery.returnToPrimary() + let resumed = try ShadowContextStore(core: core) + XCTAssertEqual(resumed.activeID, "primary") + XCTAssertEqual(try resumed.loadLighthouse()?.id, "primary") + } + + func testReturnSucceedsWhenShadowAnchorIsMissing() throws { + try withShadow { core, folder in + try FileManager.default.removeItem(at: folder.appendingPathComponent("lighthouse.json")) + try assertReturnRecovers(core) + } + } + + func testReturnSucceedsWhenShadowSessionIsMalformed() throws { + try withShadow { core, folder in + try Data("broken".utf8).write(to: folder.appendingPathComponent("session.json")) + try assertReturnRecovers(core) + } + } + + func testRecoveryConstructionStillRejectsCorruptIndex() throws { + try withShadow { core, _ in + let index = core.configURL.deletingLastPathComponent().appendingPathComponent("contexts.json") + try Data("broken".utf8).write(to: index) + XCTAssertThrowsError(try ShadowContextStore(core: core, verifyActiveContext: false)) + } + } +}