File size: 16,626 Bytes
9425aed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | -- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- SpacetimeAgent.hs β Agent Position & Decision Framework
-- bridges/haskell/SpacetimeAgent.hs
--
-- PHASE 7 AGENT EXPLORATION. OBSERVABLE-ONLY. WORM-SEALED HISTORY.
--
-- Agents operate in simulated manifolds with:
-- - Position/state representation in spacetime coordinates
-- - Memory of previous observations (WORM-sealed)
-- - Goal system (Explore, Map, Detect, Collaborate)
-- - Frame detection (Unknown, Gravity, Relativity, Quantum, Wormhole, Horizon)
-- - Resource tracking (movement, observation, message budgets)
--
-- Decision policy frames detection for "what kind of region am I in?"
-- All observations are immutable; agents measure, never mutate reality.
--
-- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
{-# LANGUAGE DeriveGeneric #-}
module SpacetimeAgent where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (intercalate)
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map.Strict as Map
import GHC.Generics (Generic)
import Data.Hashable (hash)
-- ββ Observable Spacetime Frame ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- Agents detect which frame they are observing from.
data Frame
= Unknown -- No frame detected yet
| Gravity -- Curvature/gravitational effects
| Relativity -- Time scaling/relative effects
| Quantum -- Probabilistic/superposition state
| Wormhole -- Multiple paths / topology shortcuts
| Horizon -- Event boundary / information barrier
deriving (Show, Eq, Ord, Generic)
-- ββ Agent Goal Types ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
data Goal
= Explore Subgoal
| Map RegionOfInterest
| Detect AnomalyType
| Collaborate AgentId
deriving (Show, Eq, Generic)
data Subgoal
= ExpandBoundary
| SampleRegion
| TraceTopology
| FindConnections
deriving (Show, Eq, Generic)
data RegionOfInterest
= LocalRegion Double -- Radius of interest
| SpecificCoordinates [Double]
deriving (Show, Eq, Generic)
data AnomalyType
= CurvatureSpike
| TemporalAnomaly
| SuperpositionCollapse
| TopologyChange
deriving (Show, Eq, Generic)
type AgentId = String
-- ββ Resource Budget (enforced, non-negative) ββββββββββββββββββββββββββββββββββββββ
data ResourceBudget = ResourceBudget
{ movementBudget :: Int -- Steps agent can move
, observationBudget :: Int -- Observations it can record
, messageBudget :: Int -- Messages it can send to swarm
, currentUsage :: ResourceUsage
} deriving (Show, Eq, Generic)
data ResourceUsage = ResourceUsage
{ movementUsed :: Int
, observationUsed :: Int
, messageUsed :: Int
} deriving (Show, Eq, Generic)
-- Resource checking predicates
canMove :: ResourceBudget -> Bool
canMove b = movementUsed (currentUsage b) < movementBudget b
canObserve :: ResourceBudget -> Bool
canObserve b = observationUsed (currentUsage b) < observationBudget b
canMessage :: ResourceBudget -> Bool
canMessage b = messageUsed (currentUsage b) < messageBudget b
-- Remaining budget (observable, non-negative)
remainingMovement :: ResourceBudget -> Int
remainingMovement b = max 0 (movementBudget b - movementUsed (currentUsage b))
remainingObservation :: ResourceBudget -> Int
remainingObservation b = max 0 (observationBudget b - observationUsed (currentUsage b))
remainingMessage :: ResourceBudget -> Int
remainingMessage b = max 0 (messageBudget b - messageUsed (currentUsage b))
-- ββ Observation (immutable, WORM-sealed) ββββββββββββββββββββββββββββββββββββββββββ
data Observation = Observation
{ obsTimestamp :: Int
, obsPosition :: [Double]
, obsMeasurements :: Map.Map String Double
, obsFrameDetected :: Frame
, obsHash :: ByteString -- WORM hash: blake3(thisObs ++ priorHash)
} deriving (Show, Eq, Generic)
-- Encode observation to ByteString for hashing
encodeObservation :: Observation -> ByteString
encodeObservation obs =
let coordStr = intercalate "," (map show (obsPosition obs))
measStr = intercalate ";" (map (\(k,v) -> k ++ "=" ++ show v) (Map.toList (obsMeasurements obs)))
frameStr = show (obsFrameDetected obs)
parts = [show (obsTimestamp obs), coordStr, measStr, frameStr]
in BSC.pack (intercalate "|" parts)
-- Simple hash for WORM chaining (in production: blake3)
simpleHash :: ByteString -> ByteString
simpleHash bs = BSC.pack $ "h" ++ show (hash bs)
-- ββ Agent Position & State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
data AgentPosition = AgentPosition
{ coordinates :: [Double] -- n-dimensional position
, observerFrame :: Frame -- Current frame
, lastObservation :: Maybe Observation
, memoryLog :: [Observation] -- WORM-sealed history
} deriving (Show, Eq, Generic)
-- ββ Agent Decision State (at decision point) ββββββββββββββββββββββββββββββββββββββ
data AgentDecision = AgentDecision
{ agentId :: AgentId
, agentGoal :: Goal
, resourceBudget :: ResourceBudget
, confidenceLevel :: Double -- 0-1 confidence in current frame
, explorationPath :: [AgentPosition]
, decisionCount :: Int
} deriving (Show, Eq, Generic)
-- ββ Actions agents can take βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
data Action
= MoveRandom Int -- Random walk, steps limit
| MoveAlongGradient [Double] -- Move in direction
| RecordObservation [Double] -- Take measurement at position
| SampleSuperposition -- Probe quantum region
| SendMessageToSwarm AgentId String -- Send message to peer
| Wait -- No action (conserve resources)
deriving (Show, Eq, Generic)
-- ββ Frame Detection (Ahmad's reframing logic) βββββββββββββββββββββββββββββββββββββ
-- Given observations, infer which frame we're in.
detectFrame :: Observation -> Frame
detectFrame obs
| curvatureDetected obs = Gravity
| timeScalingDetected obs = Relativity
| probabilisticState obs = Quantum
| alternatePathsDetected obs = Wormhole
| eventHorizonNear obs = Horizon
| otherwise = Unknown
-- Helper predicates for frame detection
curvatureDetected :: Observation -> Bool
curvatureDetected obs =
case Map.lookup "curvature" (obsMeasurements obs) of
Just v -> v > 0.1
Nothing -> False
timeScalingDetected :: Observation -> Bool
timeScalingDetected obs =
case Map.lookup "time_scale" (obsMeasurements obs) of
Just v -> v /= 1.0
Nothing -> False
probabilisticState :: Observation -> Bool
probabilisticState obs =
case Map.lookup "entropy" (obsMeasurements obs) of
Just v -> v > 0.3
Nothing -> False
alternatePathsDetected :: Observation -> Bool
alternatePathsDetected obs =
case Map.lookup "paths" (obsMeasurements obs) of
Just v -> v > 1.0
Nothing -> False
eventHorizonNear :: Observation -> Bool
eventHorizonNear obs =
case Map.lookup "horizon_distance" (obsMeasurements obs) of
Just v -> v < 1.0
Nothing -> False
-- ββ Decision Policy (frame + goal β action) βββββββββββββββββββββββββββββββββββββββ
-- Observable-only: agents read state, never mutate.
decideNextAction :: AgentDecision -> Observation -> Maybe Action
decideNextAction decision obs
| not (canMove (resourceBudget decision)) && not (canObserve (resourceBudget decision)) = Just Wait
| otherwise = case (agentGoal decision, detectFrame obs) of
-- Explore: expand knowledge of manifold
(Explore ExpandBoundary, Unknown) | canMove (resourceBudget decision) ->
Just (MoveRandom (remainingMovement (resourceBudget decision)))
(Explore ExpandBoundary, Gravity) | canMove (resourceBudget decision) ->
Just (MoveAlongGradient (computeGradient obs))
(Explore TraceTopology, Wormhole) | canObserve (resourceBudget decision) ->
Just (RecordObservation (obsPosition obs))
-- Map: record detailed topology
(Map _, _) | canObserve (resourceBudget decision) ->
Just (RecordObservation (obsPosition obs))
-- Detect: sample for anomalies
(Detect _, Quantum) | canObserve (resourceBudget decision) ->
Just SampleSuperposition
(Detect _, Horizon) | canObserve (resourceBudget decision) ->
Just (RecordObservation (obsPosition obs))
-- Collaborate: advertise to swarm
(Collaborate peerId, _) | canMessage (resourceBudget decision) ->
Just (SendMessageToSwarm peerId ("position:" ++ show (obsPosition obs)))
-- Default: wait
_ -> Just Wait
-- Compute gradient direction from measurements (stub)
computeGradient :: Observation -> [Double]
computeGradient obs =
let curvature = fromMaybe 0.0 (Map.lookup "curvature" (obsMeasurements obs))
in replicate (length (obsPosition obs)) (curvature * 0.01)
-- ββ Confidence update (based on consistent frame) βββββββββββββββββββββββββββββββββ
updateConfidence :: AgentPosition -> Observation -> Double
updateConfidence pos obs =
let detectedFrame = detectFrame obs
lastFrame = observerFrame pos
matches = detectedFrame == lastFrame
increment = if matches then 0.1 else -0.05
in min 1.0 (max 0.0 (0.5 + increment)) -- Bounded [0,1]
-- ββ Goal Updates (based on observations) βββββββββββββββββββββββββββββββββββββββββββ
updateGoal :: Agent -> Observation -> Goal
updateGoal agent obs =
let frame = detectFrame obs
oldGoal = agentGoal (decision agent)
in case frame of
Horizon -> Detect AnomalyType.Anomaly -- Near horizon: detect anomalies
Wormhole -> Explore Connections -- Wormhole: explore shortcuts
Quantum -> Detect AnomalyType.Superposition -- Quantum: sample states
_ -> Map (LocalRegion 1.0) -- Default: map region
-- Workaround for pattern matching (AnomalyType constructor)
-- Note: adjust based on actual AnomalyType variants
-- updateGoal uses Map as safe default for most frames
-- ββ Full Agent State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
data Agent = Agent
{ agentIdentity :: AgentId
, position :: AgentPosition
, decision :: AgentDecision
, createdAt :: Int -- Timestamp
, observationCount :: Int
} deriving (Show, Eq, Generic)
-- ββ Create new agent at position βββββββββββββββββββββββββββββββββββββββββββββββββββ
createAgent :: AgentId -> [Double] -> Int -> Agent
createAgent aid coords timestamp =
Agent
{ agentIdentity = aid
, position = AgentPosition
{ coordinates = coords
, observerFrame = Unknown
, lastObservation = Nothing
, memoryLog = []
}
, decision = AgentDecision
{ agentId = aid
, agentGoal = Explore SampleRegion
, resourceBudget = ResourceBudget
{ movementBudget = 100
, observationBudget = 50
, messageBudget = 20
, currentUsage = ResourceUsage 0 0 0
}
, confidenceLevel = 0.0
, explorationPath = []
, decisionCount = 0
}
, createdAt = timestamp
, observationCount = 0
}
-- ββ Record observation (immutable append) ββββββββββββββββββββββββββββββββββββββββββ
recordObservation :: Agent -> Observation -> Agent
recordObservation agent obs =
let priorHash = case lastObservation (position agent) of
Just lastObs -> obsHash lastObs
Nothing -> BS.empty
newObs = obs { obsHash = simpleHash (encodeObservation obs <> priorHash) }
newPos = (position agent)
{ lastObservation = Just newObs
, memoryLog = memoryLog (position agent) ++ [newObs]
}
newBudget = (resourceBudget (decision agent))
{ currentUsage = let u = currentUsage (resourceBudget (decision agent))
in u { observationUsed = observationUsed u + 1 }
}
newDecision = (decision agent)
{ resourceBudget = newBudget
, decisionCount = decisionCount (decision agent) + 1
}
in agent
{ position = newPos
, decision = newDecision
, observationCount = observationCount agent + 1
}
-- ββ Move agent (update position, consume resource) ββββββββββββββββββββββββββββββββ
moveAgent :: Agent -> [Double] -> Agent
moveAgent agent newCoords
| not (canMove (resourceBudget (decision agent))) = agent -- No budget: no move
| otherwise =
let newPos = (position agent) { coordinates = newCoords }
newBudget = (resourceBudget (decision agent))
{ currentUsage = let u = currentUsage (resourceBudget (decision agent))
in u { movementUsed = movementUsed u + 1 }
}
newDecision = (decision agent)
{ resourceBudget = newBudget
, explorationPath = explorationPath (decision agent) ++ [position agent]
, decisionCount = decisionCount (decision agent) + 1
}
in agent
{ position = newPos
, decision = newDecision
}
-- ββ Send message (consume resource) ββββββββββββββββββββββββββββββββββββββββββββββββ
sendMessage :: Agent -> AgentId -> String -> Agent
sendMessage agent targetId msg
| not (canMessage (resourceBudget (decision agent))) = agent -- No budget: no message
| otherwise =
let newBudget = (resourceBudget (decision agent))
{ currentUsage = let u = currentUsage (resourceBudget (decision agent))
in u { messageUsed = messageUsed u + 1 }
}
newDecision = (decision agent)
{ resourceBudget = newBudget
, decisionCount = decisionCount (decision agent) + 1
}
in agent
{ decision = newDecision
}
-- ββ Agent status summary (for logging) ββββββββββββββββββββββββββββββββββββββββββββ
agentStatus :: Agent -> String
agentStatus agent =
let pos = position agent
dec = decision agent
budget = resourceBudget dec
usage = currentUsage budget
movedCells = explorationPath dec
in intercalate " | "
[ "Agent:" ++ agentIdentity agent
, "Pos:" ++ show (coordinates pos)
, "Frame:" ++ show (observerFrame pos)
, "Goal:" ++ show (agentGoal dec)
, "Confidence:" ++ printf "%.2f" (confidenceLevel dec)
, "Movement:" ++ show (movementUsed usage) ++ "/" ++ show (movementBudget budget)
, "Observations:" ++ show (observationUsed usage) ++ "/" ++ show (observationBudget budget)
, "Messages:" ++ show (messageUsed usage) ++ "/" ++ show (messageBudget budget)
, "MemorySize:" ++ show (length (memoryLog pos))
]
-- Printf-like helper for formatting
printf :: String -> Double -> String
printf fmt val = show val -- Simplified; use Text.Printf in production
|