diff --git a/CLAUDE.md b/CLAUDE.md index ef2c58f..fba72f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -216,6 +216,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/README.md b/README.md index 3837ac5..31a5a3a 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,37 @@ 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. ### Compare two saved runs ```bash diff --git a/Sources/SynapseCore/ShadowContextStore.swift b/Sources/SynapseCore/ShadowContextStore.swift new file mode 100644 index 0000000..59e88ce --- /dev/null +++ b/Sources/SynapseCore/ShadowContextStore.swift @@ -0,0 +1,154 @@ +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 } + + /// - 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") + 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 verifyActiveContext, 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..d9afb41 --- /dev/null +++ b/Sources/contextsynapse/ShadowContextCommand.swift @@ -0,0 +1,42 @@ +import Foundation +import SynapseCore + +enum ShadowContextCommand { + static func prepare(args: [String], core: SynapseCore) throws -> ShadowContextStore { + // --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 } + 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 4e89689..367cb02 100644 --- a/Sources/contextsynapse/main.swift +++ b/Sources/contextsynapse/main.swift @@ -9,6 +9,12 @@ let args = CommandLine.arguments if args.contains("--session-diff") { exit(SessionDiffCommand.run(args)) } +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" @@ -23,6 +29,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 @@ -31,7 +66,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("") @@ -41,7 +77,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") @@ -69,18 +106,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 = core.makeSynapseManager() + 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 core.loadLighthouseRecord() == nil { + } else if selectedLighthouseRecord == nil { print("No lighthouse set — RSA epochs are only meaningful relative to an anchor.") print("Set one: contextsynapse --lighthouse \"\"") } else { @@ -149,26 +194,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() @@ -301,7 +326,7 @@ let currentContent = SynapseContent( functionNames: [] ) -let activeLighthouseRecord = core.loadLighthouseRecord() +let activeLighthouseRecord = selectedLighthouseRecord let activeLighthouse = activeLighthouseRecord?.content let refereeMode = core.loadRefereeConfig().mode var rotScore: Double = 0.0 @@ -310,7 +335,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 @@ -318,6 +343,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) @@ -361,6 +389,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/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)) + } + } +} diff --git a/Tests/ShadowContextTests.swift b/Tests/ShadowContextTests.swift new file mode 100644 index 0000000..63a1704 --- /dev/null +++ b/Tests/ShadowContextTests.swift @@ -0,0 +1,125 @@ +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) + 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) + 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(["--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") + 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 19c5085..64c920e 100644 --- a/docs/journal/DECISIONS.md +++ b/docs/journal/DECISIONS.md @@ -289,3 +289,9 @@ - 2026-10-29 · Record the 2026-10-21 closure of PR #44 as superseded by main and duplicate of closed #27. The closure note records `git diff --diff-filter=A --name-only origin/main origin/rescue/ci-repair-p1-2026-09-16` returning zero files against main `51894f4`, with the branch missing driftReference and six test files. This establishes absence of branch-only files, not semantic equivalence; the accompanying commit-by-commit review is the justification for closure. No branch deleted. Reverse: reopen #44 for any newly demonstrated unique work, without merging the stale branch wholesale. - 2026-10-29 · Remove affect/biometric inference from the version backlog. Track A ADR-002 permanently excludes surveillance or inference of operator state; Track A ADR-001 requires explicit user confirmation for anchors and does not exempt opt-in webcam, cursor, or scroll inference from ADR-002. Explicit manual context choices remain permitted. Reverse: only a new explicit architecture decision can revisit the permanent boundary; an unchecked roadmap item is not authority. + +## 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.