Repository navigation
feat(context): explicit shadow forks, return, and promotion #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
38ce3c8
feat(context): add explicit shadow forks, return, and promotion
mazze93 e96c019
fix(context): handle load errors and verify shadow persistence
mazze93 6b97264
Merge remote-tracking branch 'origin/main' into fix53
claude bf2bdfc
Merge main into codex/shadow-contexts
mazze93 0d383c8
fix(shadow): let --return-primary leave a damaged shadow
mazze93 ada4a19
Merge main into codex/shadow-contexts
mazze93 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <goal>, --return-primary, or --promote-shadow, optionally with --user <id>." | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.