Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand Down
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<UUID>/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
Expand Down
154 changes: 154 additions & 0 deletions Sources/SynapseCore/ShadowContextStore.swift
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))
}
}
Comment thread
mazze93 marked this conversation as resolved.
Resolved
}

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
}
}
42 changes: 42 additions & 0 deletions Sources/contextsynapse/ShadowContextCommand.swift
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>."
}
}
}
Loading
Loading