@myclaw163/clawclaw-cli 0.10.11 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/bin/clawclaw-cli.mjs +15 -6
  2. package/bin/startup-trace.d.mts +9 -0
  3. package/bin/startup-trace.mjs +100 -0
  4. package/cli-runtime/assets/clawclaw-map.json +1782 -0
  5. package/cli-runtime/assets/clawclaw-spatial-facts.json +1383 -0
  6. package/cli-runtime/assets/clawclaw-spatial-model.txt +142 -0
  7. package/cli-runtime/channel/claude-channel-ipc-server.js +220 -0
  8. package/cli-runtime/channel/claude-channel-ipc.js +135 -0
  9. package/cli-runtime/channel/claude-channel-server.js +209 -0
  10. package/cli-runtime/cli.js +81 -0
  11. package/cli-runtime/commands/_schema.js +60 -0
  12. package/cli-runtime/commands/account.js +577 -0
  13. package/cli-runtime/commands/auth.js +140 -0
  14. package/cli-runtime/commands/behavior.js +422 -0
  15. package/cli-runtime/commands/capability.js +327 -0
  16. package/cli-runtime/commands/communication.js +339 -0
  17. package/cli-runtime/commands/competition.js +55 -0
  18. package/cli-runtime/commands/config.js +28 -0
  19. package/cli-runtime/commands/data.js +78 -0
  20. package/cli-runtime/commands/events.js +339 -0
  21. package/cli-runtime/commands/game/index.js +646 -0
  22. package/cli-runtime/commands/hub.js +152 -0
  23. package/cli-runtime/commands/load.js +22 -0
  24. package/cli-runtime/commands/memory.js +30 -0
  25. package/cli-runtime/commands/module-runtime-control.js +110 -0
  26. package/cli-runtime/commands/peek.js +38 -0
  27. package/cli-runtime/commands/perception.js +146 -0
  28. package/cli-runtime/commands/persona.js +165 -0
  29. package/cli-runtime/commands/prepare.js +878 -0
  30. package/cli-runtime/commands/setup/codex.js +244 -0
  31. package/cli-runtime/commands/setup/hermes.js +55 -0
  32. package/cli-runtime/commands/setup/index.js +15 -0
  33. package/cli-runtime/commands/setup/openclaw.js +103 -0
  34. package/cli-runtime/commands/skill.js +76 -0
  35. package/cli-runtime/commands/strategy.js +4 -0
  36. package/cli-runtime/commands/trigger.js +271 -0
  37. package/cli-runtime/commands/upgrade.js +112 -0
  38. package/cli-runtime/lib/account-guidance.js +97 -0
  39. package/cli-runtime/lib/agent-workspace-client.js +66 -0
  40. package/cli-runtime/lib/agent-workspace-runtime.js +174 -0
  41. package/cli-runtime/lib/agent-workspace-skills.js +453 -0
  42. package/cli-runtime/lib/agent-workspace-sync.js +812 -0
  43. package/cli-runtime/lib/auth.js +210 -0
  44. package/cli-runtime/lib/capability-cloud-presence.js +134 -0
  45. package/cli-runtime/lib/capability-cloud-refresh.js +263 -0
  46. package/cli-runtime/lib/capability-cloud-sync.js +385 -0
  47. package/cli-runtime/lib/capability-discovery.js +94 -0
  48. package/cli-runtime/lib/capability-load-diagnostics.js +121 -0
  49. package/cli-runtime/lib/capability-operation-name.js +24 -0
  50. package/cli-runtime/lib/capability-operation-rename.js +120 -0
  51. package/cli-runtime/lib/capability-selection.js +69 -0
  52. package/cli-runtime/lib/capability-workspace.js +214 -0
  53. package/cli-runtime/lib/command-error.js +25 -0
  54. package/cli-runtime/lib/command-meta.js +13 -0
  55. package/cli-runtime/lib/competition.js +77 -0
  56. package/cli-runtime/lib/custom-tts.js +363 -0
  57. package/cli-runtime/lib/desktop-auth.js +44 -0
  58. package/cli-runtime/lib/desktop-mode.js +12 -0
  59. package/cli-runtime/lib/diagnostics-config.js +82 -0
  60. package/cli-runtime/lib/game-client.js +602 -0
  61. package/cli-runtime/lib/game-context.js +117 -0
  62. package/cli-runtime/lib/gameplay-config.js +232 -0
  63. package/cli-runtime/lib/host-config-patcher.js +101 -0
  64. package/cli-runtime/lib/http-keepalive.js +15 -0
  65. package/cli-runtime/lib/http-transport.js +163 -0
  66. package/cli-runtime/lib/hub-client.js +292 -0
  67. package/cli-runtime/lib/hub-errors.js +51 -0
  68. package/cli-runtime/lib/hub-reminder.js +65 -0
  69. package/cli-runtime/lib/hub-unzip.js +52 -0
  70. package/cli-runtime/lib/init-command.js +160 -0
  71. package/cli-runtime/lib/load-context.js +97 -0
  72. package/cli-runtime/lib/load-startup-context.js +59 -0
  73. package/cli-runtime/lib/load-startup.js +23 -0
  74. package/cli-runtime/lib/lobby-host-context.js +70 -0
  75. package/cli-runtime/lib/match-state.js +61 -0
  76. package/cli-runtime/lib/normalize.js +28 -0
  77. package/cli-runtime/lib/package-skills.js +15 -0
  78. package/cli-runtime/lib/participation-leave.js +54 -0
  79. package/cli-runtime/lib/participation-status.js +73 -0
  80. package/cli-runtime/lib/perception-config.js +85 -0
  81. package/cli-runtime/lib/persona.js +157 -0
  82. package/cli-runtime/lib/room.js +108 -0
  83. package/cli-runtime/lib/runtime-cadence-config.js +18 -0
  84. package/cli-runtime/lib/server-registry.js +155 -0
  85. package/cli-runtime/lib/server-status.js +44 -0
  86. package/cli-runtime/lib/service-status.js +88 -0
  87. package/cli-runtime/lib/skill-host.js +246 -0
  88. package/cli-runtime/lib/skill-name-conflicts.js +89 -0
  89. package/cli-runtime/lib/skill-version.js +20 -0
  90. package/cli-runtime/lib/training-role.js +23 -0
  91. package/cli-runtime/lib/trigger-config.js +138 -0
  92. package/cli-runtime/lib/user-data.js +336 -0
  93. package/cli-runtime/lib/workspace-argv.js +35 -0
  94. package/cli-runtime/lib/workspace-runtime-lock.js +6 -0
  95. package/cli-runtime/lib/zip-store.js +78 -0
  96. package/cli-runtime/pipeline/canonical-event-presentation.js +32 -0
  97. package/cli-runtime/pipeline/event-format.js +921 -0
  98. package/cli-runtime/pipeline/event-hints.js +235 -0
  99. package/cli-runtime/pipeline/game-sync-event-normalization.js +228 -0
  100. package/cli-runtime/pipeline/player-projection.js +272 -0
  101. package/cli-runtime/pipeline/role-display.js +22 -0
  102. package/cli-runtime/runtime/auto-upgrade.js +30 -0
  103. package/cli-runtime/runtime/canonical-event-emitter.js +58 -0
  104. package/cli-runtime/runtime/canonical-monitor.js +332 -0
  105. package/cli-runtime/runtime/clawclaw/agent-ability-state.js +41 -0
  106. package/cli-runtime/runtime/clawclaw/agent-event-policy.js +58 -0
  107. package/cli-runtime/runtime/clawclaw/behavior-decision.js +84 -0
  108. package/cli-runtime/runtime/clawclaw/behavior-input-fields.js +212 -0
  109. package/cli-runtime/runtime/clawclaw/behavior-input.js +54 -0
  110. package/cli-runtime/runtime/clawclaw/behavior-observation-memory.js +106 -0
  111. package/cli-runtime/runtime/clawclaw/behavior-read-api.js +110 -0
  112. package/cli-runtime/runtime/clawclaw/behavior-reflex-control.js +97 -0
  113. package/cli-runtime/runtime/clawclaw/behavior-start-control.js +159 -0
  114. package/cli-runtime/runtime/clawclaw/index.js +3 -0
  115. package/cli-runtime/runtime/clawclaw/navigation/astar-path.js +244 -0
  116. package/cli-runtime/runtime/clawclaw/navigation/clawclaw-walkable.bin +0 -0
  117. package/cli-runtime/runtime/clawclaw/navigation/distance-field.js +136 -0
  118. package/cli-runtime/runtime/clawclaw/navigation/escape-planner.js +273 -0
  119. package/cli-runtime/runtime/clawclaw/navigation/hide-spots.js +31 -0
  120. package/cli-runtime/runtime/clawclaw/navigation/off-route-points.js +64 -0
  121. package/cli-runtime/runtime/clawclaw/navigation/walkable-grid.js +85 -0
  122. package/cli-runtime/runtime/clawclaw/notification-policy.js +59 -0
  123. package/cli-runtime/runtime/clawclaw/notification-turn.js +28 -0
  124. package/cli-runtime/runtime/clawclaw/notifications.js +65 -0
  125. package/cli-runtime/runtime/clawclaw/observation-frame-projector.js +94 -0
  126. package/cli-runtime/runtime/clawclaw/owner-lock-error.js +17 -0
  127. package/cli-runtime/runtime/clawclaw/owner-lock.js +219 -0
  128. package/cli-runtime/runtime/clawclaw/owner.js +1257 -0
  129. package/cli-runtime/runtime/clawclaw/perception-module-manifest.js +67 -0
  130. package/cli-runtime/runtime/clawclaw/perception-strategy-names.js +12 -0
  131. package/cli-runtime/runtime/clawclaw/persistence-compatibility.js +38 -0
  132. package/cli-runtime/runtime/clawclaw/plugins/action/action-plugin.js +604 -0
  133. package/cli-runtime/runtime/clawclaw/plugins/action/automated-action-normalization.js +67 -0
  134. package/cli-runtime/runtime/clawclaw/plugins/action/index.js +1 -0
  135. package/cli-runtime/runtime/clawclaw/plugins/assembly.js +134 -0
  136. package/cli-runtime/runtime/clawclaw/plugins/behavior/activation-manager.js +1 -0
  137. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-action.js +26 -0
  138. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.js +21 -0
  139. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +25 -0
  140. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-catalog.js +90 -0
  141. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-decision-history.js +60 -0
  142. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.js +1 -0
  143. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-manifest.js +136 -0
  144. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-module-loader.js +230 -0
  145. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-normalization.js +92 -0
  146. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-plugin.js +162 -0
  147. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-runner.js +20 -0
  148. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-source.js +493 -0
  149. package/cli-runtime/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.js +28 -0
  150. package/cli-runtime/runtime/clawclaw/plugins/behavior/control-driver.js +5 -0
  151. package/cli-runtime/runtime/clawclaw/plugins/behavior/index.js +11 -0
  152. package/cli-runtime/runtime/clawclaw/plugins/behavior/thread-behavior-executor.js +18 -0
  153. package/cli-runtime/runtime/clawclaw/plugins/behavior-input-source.js +233 -0
  154. package/cli-runtime/runtime/clawclaw/plugins/derived-event/derived-event-plugin.js +25 -0
  155. package/cli-runtime/runtime/clawclaw/plugins/derived-event/derived-event-rules.js +289 -0
  156. package/cli-runtime/runtime/clawclaw/plugins/derived-event/index.js +2 -0
  157. package/cli-runtime/runtime/clawclaw/plugins/derived-event/player-change-tracker.js +162 -0
  158. package/cli-runtime/runtime/clawclaw/plugins/derived-event/reminder-plugin.js +182 -0
  159. package/cli-runtime/runtime/clawclaw/plugins/derived-event/reminder-rules.js +1 -0
  160. package/cli-runtime/runtime/clawclaw/plugins/derived-event/reminder-runner.js +83 -0
  161. package/cli-runtime/runtime/clawclaw/plugins/derived-event/reminder-worker.js +35 -0
  162. package/cli-runtime/runtime/clawclaw/plugins/derived-event/reminder-worker.ts +33 -0
  163. package/cli-runtime/runtime/clawclaw/plugins/derived-event/state-change-rules.js +111 -0
  164. package/cli-runtime/runtime/clawclaw/plugins/derived-event/task-change-tracker.js +1 -0
  165. package/cli-runtime/runtime/clawclaw/plugins/game-query/context-capabilities.js +10 -0
  166. package/cli-runtime/runtime/clawclaw/plugins/game-query/game-query-plugin.js +196 -0
  167. package/cli-runtime/runtime/clawclaw/plugins/game-query/index.js +2 -0
  168. package/cli-runtime/runtime/clawclaw/plugins/index.js +9 -0
  169. package/cli-runtime/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.js +24 -0
  170. package/cli-runtime/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.js +21 -0
  171. package/cli-runtime/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.js +84 -0
  172. package/cli-runtime/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.js +54 -0
  173. package/cli-runtime/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.js +61 -0
  174. package/cli-runtime/runtime/clawclaw/plugins/mailbox/consumer-ids.js +10 -0
  175. package/cli-runtime/runtime/clawclaw/plugins/mailbox/desktop-event-socket.js +45 -0
  176. package/cli-runtime/runtime/clawclaw/plugins/mailbox/index.js +11 -0
  177. package/cli-runtime/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.js +1 -0
  178. package/cli-runtime/runtime/clawclaw/plugins/mailbox/mailbox-plugin.js +13 -0
  179. package/cli-runtime/runtime/clawclaw/plugins/mailbox/mailbox-presentation.js +99 -0
  180. package/cli-runtime/runtime/clawclaw/plugins/mailbox/mailbox-service.js +84 -0
  181. package/cli-runtime/runtime/clawclaw/plugins/perception/contracts.js +14 -0
  182. package/cli-runtime/runtime/clawclaw/plugins/perception/index.js +11 -0
  183. package/cli-runtime/runtime/clawclaw/plugins/perception/map-concurrent.js +1 -0
  184. package/cli-runtime/runtime/clawclaw/plugins/perception/module-input-boundary.js +64 -0
  185. package/cli-runtime/runtime/clawclaw/plugins/perception/module-runner.js +182 -0
  186. package/cli-runtime/runtime/clawclaw/plugins/perception/notification-content.js +47 -0
  187. package/cli-runtime/runtime/clawclaw/plugins/perception/official-module-ids.js +13 -0
  188. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.js +684 -0
  189. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.js +145 -0
  190. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +252 -0
  191. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-loader.js +78 -0
  192. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-output.js +15 -0
  193. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-plugin.js +144 -0
  194. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-runner.js +22 -0
  195. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.js +18 -0
  196. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-module-worker.ts +19 -0
  197. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-plugin.js +1343 -0
  198. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.js +522 -0
  199. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.js +161 -0
  200. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  201. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-source.js +489 -0
  202. package/cli-runtime/runtime/clawclaw/plugins/perception/perception-test-fixtures.js +31 -0
  203. package/cli-runtime/runtime/clawclaw/plugins/perception/replay.js +56 -0
  204. package/cli-runtime/runtime/clawclaw/plugins/perception/report-content.js +39 -0
  205. package/cli-runtime/runtime/clawclaw/plugins/perception/shared/math.js +1 -0
  206. package/cli-runtime/runtime/clawclaw/plugins/perception/spatial-facts.js +103 -0
  207. package/cli-runtime/runtime/clawclaw/plugins/perception/task-baseline.js +29 -0
  208. package/cli-runtime/runtime/clawclaw/plugins/plugin-api-version.js +89 -0
  209. package/cli-runtime/runtime/clawclaw/plugins/source/game-transport.js +204 -0
  210. package/cli-runtime/runtime/clawclaw/plugins/source/index.js +5 -0
  211. package/cli-runtime/runtime/clawclaw/plugins/source/room-transport.js +399 -0
  212. package/cli-runtime/runtime/clawclaw/plugins/source/source-plugin.js +2003 -0
  213. package/cli-runtime/runtime/clawclaw/plugins/source/source-transports.js +26 -0
  214. package/cli-runtime/runtime/clawclaw/plugins/source/types.js +0 -0
  215. package/cli-runtime/runtime/clawclaw/plugins/system-perception/rule-runner.js +90 -0
  216. package/cli-runtime/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.js +59 -0
  217. package/cli-runtime/runtime/clawclaw/plugins/system-perception/system-perceptions.js +241 -0
  218. package/cli-runtime/runtime/clawclaw/plugins/trigger/contracts.js +12 -0
  219. package/cli-runtime/runtime/clawclaw/plugins/trigger/index.js +4 -0
  220. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-module-loader.js +105 -0
  221. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-plugin.js +741 -0
  222. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-source.js +372 -0
  223. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-pool.js +378 -0
  224. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.js +118 -0
  225. package/cli-runtime/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +168 -0
  226. package/cli-runtime/runtime/clawclaw/reaction-behavior-resolution.js +1 -0
  227. package/cli-runtime/runtime/clawclaw/reaction-manifest.js +62 -0
  228. package/cli-runtime/runtime/clawclaw/reminder-manifest.js +39 -0
  229. package/cli-runtime/runtime/clawclaw/runtime-cadence.js +28 -0
  230. package/cli-runtime/runtime/clawclaw/runtime-data-export.js +321 -0
  231. package/cli-runtime/runtime/clawclaw/runtime-state.js +51 -0
  232. package/cli-runtime/runtime/clawclaw/runtime.js +132 -0
  233. package/cli-runtime/runtime/clawclaw/spatial-api.js +48 -0
  234. package/cli-runtime/runtime/clawclaw/starting-owner-control.js +24 -0
  235. package/cli-runtime/runtime/clawclaw/strategy-memory-rpc.js +1 -0
  236. package/cli-runtime/runtime/clawclaw/strategy-memory.js +6 -0
  237. package/cli-runtime/runtime/clawclaw/task-choice-projection.js +72 -0
  238. package/cli-runtime/runtime/clawclaw-event-catalog.js +284 -0
  239. package/cli-runtime/runtime/clawclaw-position.js +0 -0
  240. package/cli-runtime/runtime/clawclaw-room-state.js +38 -0
  241. package/cli-runtime/runtime/framework/action-diagnostics.js +69 -0
  242. package/cli-runtime/runtime/framework/capability-registry.js +1 -0
  243. package/cli-runtime/runtime/framework/contracts.js +1 -0
  244. package/cli-runtime/runtime/framework/control/control-scheduler.js +1 -0
  245. package/cli-runtime/runtime/framework/control/domain-set.js +1 -0
  246. package/cli-runtime/runtime/framework/control/index.js +1 -0
  247. package/cli-runtime/runtime/framework/control/types.js +1 -0
  248. package/cli-runtime/runtime/framework/control-coordinator.js +1 -0
  249. package/cli-runtime/runtime/framework/events/event-catalog.js +1 -0
  250. package/cli-runtime/runtime/framework/events/event-delivery-service.js +1 -0
  251. package/cli-runtime/runtime/framework/events/event-ingress.js +1 -0
  252. package/cli-runtime/runtime/framework/events/event-repository.js +1 -0
  253. package/cli-runtime/runtime/framework/events/index.js +5 -0
  254. package/cli-runtime/runtime/framework/events/memory-event-repository.js +1 -0
  255. package/cli-runtime/runtime/framework/events/runtime-resume.js +1 -0
  256. package/cli-runtime/runtime/framework/events/sqlite-event-repository.js +6 -0
  257. package/cli-runtime/runtime/framework/events/test-helpers.js +56 -0
  258. package/cli-runtime/runtime/framework/events/types.js +1 -0
  259. package/cli-runtime/runtime/framework/index.js +7 -0
  260. package/cli-runtime/runtime/framework/load-node-sqlite.js +1 -0
  261. package/cli-runtime/runtime/framework/mailbox/coalescer.js +1 -0
  262. package/cli-runtime/runtime/framework/mailbox/host-notification-sink.js +1 -0
  263. package/cli-runtime/runtime/framework/mailbox/identity.js +1 -0
  264. package/cli-runtime/runtime/framework/mailbox/index.js +1 -0
  265. package/cli-runtime/runtime/framework/mailbox/mailbox-dispatcher.js +1 -0
  266. package/cli-runtime/runtime/framework/mailbox/mailbox-repository.js +1 -0
  267. package/cli-runtime/runtime/framework/mailbox/notification-projector.js +1 -0
  268. package/cli-runtime/runtime/framework/mailbox/types.js +1 -0
  269. package/cli-runtime/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -0
  270. package/cli-runtime/runtime/framework/modules/runtime-module-loader.js +31 -0
  271. package/cli-runtime/runtime/framework/modules/runtime-module-output.js +1 -0
  272. package/cli-runtime/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -0
  273. package/cli-runtime/runtime/framework/participation-manager.js +1 -0
  274. package/cli-runtime/runtime/framework/persistence/async-sqlite-persistence-worker.js +1 -0
  275. package/cli-runtime/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -0
  276. package/cli-runtime/runtime/framework/persistence/memory-first-persistence.js +9 -0
  277. package/cli-runtime/runtime/framework/plugins/contracts.js +1 -0
  278. package/cli-runtime/runtime/framework/plugins/index.js +1 -0
  279. package/cli-runtime/runtime/framework/plugins/runtime-event-identity.js +1 -0
  280. package/cli-runtime/runtime/framework/plugins/runtime-input-journal.js +1 -0
  281. package/cli-runtime/runtime/framework/plugins/runtime-plugin-scheduler.js +1 -0
  282. package/cli-runtime/runtime/framework/runtime.js +12 -0
  283. package/cli-runtime/runtime/framework/serial-task-queue.js +1 -0
  284. package/cli-runtime/runtime/framework/state/contracts.js +1 -0
  285. package/cli-runtime/runtime/framework/state/current-state-store.js +1 -0
  286. package/cli-runtime/runtime/framework/state/durable-agent-state-snapshot.js +1 -0
  287. package/cli-runtime/runtime/framework/state/freshness.js +1 -0
  288. package/cli-runtime/runtime/framework/state/history/contracts.js +1 -0
  289. package/cli-runtime/runtime/framework/state/history/history-writer.js +1 -0
  290. package/cli-runtime/runtime/framework/state/history/memory-state-history-repository.js +1 -0
  291. package/cli-runtime/runtime/framework/state/history/sqlite-state-history-repository.js +1 -0
  292. package/cli-runtime/runtime/framework/state/history/trajectory-projector.js +1 -0
  293. package/cli-runtime/runtime/framework/state/index.js +1 -0
  294. package/cli-runtime/runtime/framework/state/state-ingress.js +1 -0
  295. package/cli-runtime/runtime/framework/state/state-provider.js +1 -0
  296. package/cli-runtime/runtime/framework/state/types.js +1 -0
  297. package/cli-runtime/runtime/game-sync-ingress-protocol.js +0 -0
  298. package/cli-runtime/runtime/game-sync-ingress-worker.js +310 -0
  299. package/cli-runtime/runtime/game-sync-ingress-worker.ts +274 -0
  300. package/cli-runtime/runtime/game-sync-protocol.js +278 -0
  301. package/cli-runtime/runtime/host-monitor-rate-gate.js +1 -0
  302. package/cli-runtime/runtime/mailbox-host-relay.js +1 -0
  303. package/cli-runtime/runtime/observability/detail-capture.js +35 -0
  304. package/cli-runtime/runtime/observability/factory.js +137 -0
  305. package/cli-runtime/runtime/observability/index.js +6 -0
  306. package/cli-runtime/runtime/observability/process-timing.js +1 -0
  307. package/cli-runtime/runtime/observability/recorder.js +1 -0
  308. package/cli-runtime/runtime/observability/redaction.js +1 -0
  309. package/cli-runtime/runtime/observability/reporter.js +1 -0
  310. package/cli-runtime/runtime/observability/sinks.js +1 -0
  311. package/cli-runtime/runtime/observability/types.js +1 -0
  312. package/cli-runtime/runtime/owner-control.js +59 -0
  313. package/cli-runtime/runtime/parent-process-watch.js +1 -0
  314. package/cli-runtime/runtime/pending-event-handoff.js +48 -0
  315. package/cli-runtime/runtime/process-identity.js +45 -0
  316. package/cli-runtime/runtime/raw-ws-log.js +181 -0
  317. package/cli-runtime/runtime/runtime-logger.js +79 -0
  318. package/cli-runtime/runtime/threaded-ws-client.js +263 -0
  319. package/cli-runtime/runtime/ws-client.js +563 -0
  320. package/cli-runtime/sdk/action.js +133 -0
  321. package/cli-runtime/sdk/action.ts +160 -0
  322. package/cli-runtime/sdk/behavior-plugin/index.js +23 -0
  323. package/cli-runtime/sdk/behavior-plugin/index.ts +341 -0
  324. package/cli-runtime/sdk/behavior-toolkit/corpse-search.js +56 -0
  325. package/cli-runtime/sdk/behavior-toolkit/corpse-search.ts +87 -0
  326. package/cli-runtime/sdk/behavior-toolkit/escape.js +25 -0
  327. package/cli-runtime/sdk/behavior-toolkit/escape.ts +40 -0
  328. package/cli-runtime/sdk/behavior-toolkit/index.js +7 -0
  329. package/cli-runtime/sdk/behavior-toolkit/index.ts +7 -0
  330. package/cli-runtime/sdk/behavior-toolkit/kill-flow.js +239 -0
  331. package/cli-runtime/sdk/behavior-toolkit/kill-flow.ts +299 -0
  332. package/cli-runtime/sdk/behavior-toolkit/model.js +183 -0
  333. package/cli-runtime/sdk/behavior-toolkit/model.ts +265 -0
  334. package/cli-runtime/sdk/behavior-toolkit/move-gate.js +30 -0
  335. package/cli-runtime/sdk/behavior-toolkit/move-gate.ts +52 -0
  336. package/cli-runtime/sdk/behavior-toolkit/patrol.js +39 -0
  337. package/cli-runtime/sdk/behavior-toolkit/patrol.ts +53 -0
  338. package/cli-runtime/sdk/behavior-toolkit/search.js +81 -0
  339. package/cli-runtime/sdk/behavior-toolkit/search.ts +102 -0
  340. package/cli-runtime/sdk/index.js +78 -0
  341. package/cli-runtime/sdk/index.ts +136 -0
  342. package/cli-runtime/sdk/module-input/index.js +0 -0
  343. package/cli-runtime/sdk/module-input/index.ts +310 -0
  344. package/cli-runtime/sdk/perception-plugin/index.js +79 -0
  345. package/cli-runtime/sdk/perception-plugin/index.ts +251 -0
  346. package/cli-runtime/sdk/perception-plugin/lifecycle.js +18 -0
  347. package/cli-runtime/sdk/perception-plugin/lifecycle.ts +15 -0
  348. package/cli-runtime/sdk/perception-plugin/math.js +99 -0
  349. package/cli-runtime/sdk/perception-plugin/math.ts +107 -0
  350. package/cli-runtime/sdk/perception-plugin/module.js +4 -0
  351. package/cli-runtime/sdk/perception-plugin/module.ts +80 -0
  352. package/cli-runtime/sdk/perception-plugin/reaction.js +6 -0
  353. package/cli-runtime/sdk/perception-plugin/reaction.ts +79 -0
  354. package/cli-runtime/sdk/perception-plugin/reminder-rules.js +131 -0
  355. package/cli-runtime/sdk/perception-plugin/reminder-rules.ts +89 -0
  356. package/cli-runtime/sdk/perception-plugin/reminder.js +8 -0
  357. package/cli-runtime/sdk/perception-plugin/reminder.ts +68 -0
  358. package/cli-runtime/sdk/perception-plugin/task-change-tracker.js +150 -0
  359. package/cli-runtime/sdk/perception-plugin/task-change-tracker.ts +258 -0
  360. package/cli-runtime/sdk/resource-metadata.js +27 -0
  361. package/cli-runtime/sdk/resource-metadata.ts +66 -0
  362. package/cli-runtime/sdk/strategy-memory.js +1 -0
  363. package/cli-runtime/sdk/strategy-memory.ts +1 -0
  364. package/cli-runtime/sdk/strategy-plugin/index.js +6 -0
  365. package/cli-runtime/sdk/strategy-plugin/index.ts +36 -0
  366. package/cli-runtime/sdk/task-availability.js +56 -0
  367. package/cli-runtime/sdk/task-availability.ts +70 -0
  368. package/cli-runtime/sdk/trigger-plugin/index.js +16 -0
  369. package/cli-runtime/sdk/trigger-plugin/index.ts +130 -0
  370. package/cli-runtime/sdk/types.js +25 -0
  371. package/cli-runtime/sdk/types.ts +165 -0
  372. package/cli-runtime/short-command/classifier.js +129 -0
  373. package/cli-runtime/short-command/index.js +7 -0
  374. package/cli-runtime/short-command/presenter.js +225 -0
  375. package/cli-runtime/short-command/process-io.js +13 -0
  376. package/cli-runtime/short-command/response-contract.js +24 -0
  377. package/cli-runtime/short-command/runner.js +94 -0
  378. package/cli-runtime/short-command/sensitive-data-filter.js +92 -0
  379. package/cli-runtime/short-command/transport-response.js +57 -0
  380. package/cli-runtime/short-command/types.js +0 -0
  381. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +21 -29
  382. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +76 -6
  383. package/docs/configuration.md +13 -0
  384. package/package.json +7 -4
  385. package/scripts/build-cli.mjs +34 -0
  386. package/skills/clawclaw/SKILL.md +1 -1
  387. package/skills/clawclaw/references/STREAM.md +1 -0
  388. package/skills/clawclaw-start/SKILL.md +1 -0
  389. package/skills/clawclaw-start/references/STARTUP.md +1 -0
  390. package/src/cli.ts +75 -77
  391. package/src/commands/auth.ts +3 -2
  392. package/src/commands/game/index.ts +33 -9
  393. package/src/commands/prepare.ts +34 -18
  394. package/src/lib/agent-workspace-client.ts +12 -9
  395. package/src/lib/game-client.ts +1 -1
  396. package/src/lib/http-transport.ts +17 -2
  397. package/src/lib/hub-client.ts +10 -7
  398. package/src/pipeline/event-format.ts +2 -0
  399. package/src/pipeline/event-hints.ts +6 -0
  400. package/src/runtime/clawclaw/notification-policy.ts +1 -1
  401. package/src/runtime/clawclaw/owner-lock.ts +3 -2
  402. package/src/runtime/clawclaw/owner.ts +36 -10
  403. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +1 -1
  404. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +19 -0
  405. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +1 -0
  406. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +33 -9
  407. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  408. package/src/runtime/framework/modules/runtime-module-loader.ts +24 -29
  409. package/src/runtime/process-identity.ts +44 -0
@@ -0,0 +1,812 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ rmSync,
9
+ statSync,
10
+ writeFileSync
11
+ } from "node:fs";
12
+ import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
13
+ import {
14
+ AgentWorkspaceClient,
15
+ downloadAgentWorkspaceFile
16
+ } from "./agent-workspace-client.js";
17
+ import { unzip } from "./hub-unzip.js";
18
+ import {
19
+ getUserDataAgentWorkspaceCurrentFile,
20
+ getUserDataAgentWorkspaceDir,
21
+ getUserDataAgentWorkspaceRevisionsDir,
22
+ getUserDataAccountDir,
23
+ getUserDataAccountHubBehaviorsDir,
24
+ getUserDataAccountHubPerceptionsDir,
25
+ getUserDataAccountHubPersonasDir
26
+ } from "./user-data.js";
27
+ import {
28
+ capabilityEntryForHubResource,
29
+ capabilityWorkspacePath,
30
+ readCapabilityWorkspaceRegistry,
31
+ registerDiscoveredCapability,
32
+ updateCapabilityHubIdentity,
33
+ writeCapabilityWorkspaceRegistry
34
+ } from "./capability-workspace.js";
35
+ import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from "../runtime/clawclaw/plugins/behavior/behavior-source.js";
36
+ import { listClawclawPerceptionSourcesInDirectory } from "../runtime/clawclaw/plugins/perception/perception-source.js";
37
+ import { BEHAVIOR_PLUGIN_API_VERSION } from "../sdk/behavior-plugin/index.js";
38
+ import { isSupportedPerceptionSource } from "../runtime/clawclaw/plugins/perception/perception-source.js";
39
+ import { updateGameplayConfig } from "./gameplay-config.js";
40
+ const RESOURCE_TYPES = ["skill", "strategy", "persona", "perception"];
41
+ const SHA256 = /^[0-9a-f]{64}$/;
42
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
43
+ function record(value) {
44
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
45
+ }
46
+ function safeSegment(value, field) {
47
+ if (!SAFE_SEGMENT.test(value) || value === "." || value === "..") {
48
+ throw new Error(`agent_workspace_${field}_invalid`);
49
+ }
50
+ return value;
51
+ }
52
+ function safeRelativePath(value) {
53
+ if (!value || value.includes("\\") || value.startsWith("/") || value.split("/").some((segment) => !segment || segment === "." || segment === "..")) throw new Error("agent_workspace_relative_path_invalid");
54
+ return value;
55
+ }
56
+ function pathInside(root, candidate) {
57
+ const child = relative(resolve(root), resolve(candidate));
58
+ return child === "" || !child.startsWith("..") && !isAbsolute(child);
59
+ }
60
+ function ensureInside(root, candidate) {
61
+ if (!pathInside(root, candidate)) throw new Error("agent_workspace_path_escape");
62
+ return candidate;
63
+ }
64
+ function sha256(buffer) {
65
+ return createHash("sha256").update(buffer).digest("hex");
66
+ }
67
+ function validateRemoteFile(file, source) {
68
+ if (!SAFE_SEGMENT.test(file.file_id) || !SHA256.test(file.sha256)) {
69
+ throw new Error("agent_workspace_file_metadata_invalid");
70
+ }
71
+ if (!Number.isSafeInteger(file.size_bytes) || file.size_bytes < 0 || file.size_bytes > 10 * 1024 * 1024) {
72
+ throw new Error("agent_workspace_file_size_invalid");
73
+ }
74
+ if (typeof file.url !== "string" || typeof file.content_type !== "string") {
75
+ throw new Error("agent_workspace_file_metadata_invalid");
76
+ }
77
+ if (source) safeRelativePath(file.relative_path ?? "");
78
+ }
79
+ function validateRemoteItem(item, expectedType) {
80
+ if (item.resource_type !== expectedType) throw new Error("agent_workspace_resource_type_mismatch");
81
+ safeSegment(item.workspace_item_id, "workspace_item_id");
82
+ safeSegment(item.resource_id, "resource_id");
83
+ if (item.forked_from_resource_id != null) safeSegment(item.forked_from_resource_id, "forked_from_resource_id");
84
+ safeSegment(item.version_id, "version_id");
85
+ if (!["owned", "installed"].includes(item.workspace_kind) || typeof item.is_created_by_me !== "boolean" || !record(item.owner) || typeof item.owner.id !== "string" || !SAFE_SEGMENT.test(item.owner.id) || item.owner.name !== null && typeof item.owner.name !== "string" || item.owner.avatar_url !== null && typeof item.owner.avatar_url !== "string" || typeof item.owner.is_official !== "boolean") {
86
+ throw new Error("agent_workspace_owner_metadata_invalid");
87
+ }
88
+ if (!SHA256.test(item.content_digest) || !Array.isArray(item.source_files)) {
89
+ throw new Error("agent_workspace_item_invalid");
90
+ }
91
+ for (const file of item.source_files) validateRemoteFile(file, true);
92
+ if (expectedType === "skill") {
93
+ if (!item.archive_file) throw new Error("agent_workspace_skill_archive_missing");
94
+ validateRemoteFile(item.archive_file, false);
95
+ } else if (item.archive_file !== void 0) {
96
+ throw new Error("agent_workspace_archive_unexpected");
97
+ }
98
+ if (expectedType !== "skill" && item.source_files.length !== 1) {
99
+ throw new Error(`agent_workspace_${expectedType}_source_count_invalid`);
100
+ }
101
+ if (expectedType === "strategy") {
102
+ const path = item.source_files[0]?.relative_path ?? "";
103
+ if (path.includes("/") || ![".ts", ".js"].includes(extname(path).toLowerCase())) {
104
+ throw new Error("agent_workspace_strategy_entry_invalid");
105
+ }
106
+ }
107
+ if (expectedType === "persona") {
108
+ const path = item.source_files[0]?.relative_path ?? "";
109
+ if (path.includes("/") || extname(path).toLowerCase() !== ".md") {
110
+ throw new Error("agent_workspace_persona_entry_invalid");
111
+ }
112
+ }
113
+ if (expectedType === "perception") {
114
+ const path = item.source_files[0]?.relative_path ?? "";
115
+ if (path.includes("/") || ![".ts", ".js"].includes(extname(path).toLowerCase())) {
116
+ throw new Error("agent_workspace_perception_entry_invalid");
117
+ }
118
+ }
119
+ }
120
+ function validateRemoteConfig(config) {
121
+ if (!Number.isSafeInteger(config.revision) || config.revision < 0 || !record(config.items)) {
122
+ throw new Error("agent_workspace_config_invalid");
123
+ }
124
+ for (const type of RESOURCE_TYPES) {
125
+ const items = config.items[type];
126
+ if (!Array.isArray(items)) throw new Error(`agent_workspace_${type}_items_invalid`);
127
+ for (const item of items) validateRemoteItem(item, type);
128
+ }
129
+ if (config.items.persona.length > 1) throw new Error("agent_workspace_persona_multiple");
130
+ }
131
+ function contentDigest(files) {
132
+ const canonical = [...files].sort((left, right) => left.relativePath < right.relativePath ? -1 : left.relativePath > right.relativePath ? 1 : 0).map((file) => ({
133
+ relative_path: file.relativePath,
134
+ sha256: file.sha256,
135
+ size_bytes: file.sizeBytes
136
+ }));
137
+ return createHash("sha256").update(JSON.stringify(canonical), "utf8").digest("hex");
138
+ }
139
+ async function writeVerifiedFile(root, relativePath, remote, download) {
140
+ const bytes = await download(remote.url);
141
+ if (bytes.length !== remote.size_bytes) throw new Error("agent_workspace_file_size_mismatch");
142
+ if (sha256(bytes) !== remote.sha256) throw new Error("agent_workspace_file_hash_mismatch");
143
+ const target = ensureInside(root, join(root, ...safeRelativePath(relativePath).split("/")));
144
+ mkdirSync(dirname(target), { recursive: true });
145
+ writeFileSync(target, bytes);
146
+ return {
147
+ relativePath,
148
+ path: relative(root, target).replaceAll("\\", "/"),
149
+ fileId: remote.file_id,
150
+ sha256: remote.sha256,
151
+ sizeBytes: remote.size_bytes,
152
+ contentType: remote.content_type
153
+ };
154
+ }
155
+ function skillRoot(packageRoot) {
156
+ if (existsSync(join(packageRoot, "SKILL.md"))) return packageRoot;
157
+ const directories = [...new Set(
158
+ unzipDirectories(packageRoot).filter((directory) => existsSync(join(directory, "SKILL.md")))
159
+ )];
160
+ if (directories.length !== 1) throw new Error("agent_workspace_skill_root_invalid");
161
+ return directories[0];
162
+ }
163
+ function unzipDirectories(root) {
164
+ const results = [];
165
+ const visit = (directory) => {
166
+ const entries = requireDirectoryEntries(directory);
167
+ for (const entry of entries) {
168
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
169
+ const child = join(directory, entry.name);
170
+ results.push(child);
171
+ visit(child);
172
+ }
173
+ };
174
+ visit(root);
175
+ return results;
176
+ }
177
+ function requireDirectoryEntries(directory) {
178
+ return readdirSync(directory, { withFileTypes: true });
179
+ }
180
+ async function materializeItem(stageRoot, item, download) {
181
+ const itemRoot = join(
182
+ stageRoot,
183
+ "resources",
184
+ item.resource_type,
185
+ safeSegment(item.resource_id, "resource_id"),
186
+ safeSegment(item.version_id, "version_id")
187
+ );
188
+ const sourceRoot = join(itemRoot, "source");
189
+ mkdirSync(sourceRoot, { recursive: true });
190
+ const sourceFiles = [];
191
+ for (const source of item.source_files) {
192
+ sourceFiles.push(await writeVerifiedFile(
193
+ sourceRoot,
194
+ source.relative_path,
195
+ source,
196
+ download
197
+ ));
198
+ }
199
+ if (contentDigest(sourceFiles) !== item.content_digest) {
200
+ throw new Error("agent_workspace_content_digest_mismatch");
201
+ }
202
+ let archiveFile;
203
+ let skillRootPath;
204
+ if (item.archive_file) {
205
+ const archive = await writeVerifiedFile(itemRoot, "package.zip", item.archive_file, download);
206
+ archiveFile = {
207
+ path: relative(stageRoot, join(itemRoot, archive.path)).replaceAll("\\", "/"),
208
+ fileId: archive.fileId,
209
+ sha256: archive.sha256,
210
+ sizeBytes: archive.sizeBytes,
211
+ contentType: archive.contentType
212
+ };
213
+ const packageRoot = join(itemRoot, "package");
214
+ mkdirSync(packageRoot, { recursive: true });
215
+ for (const entry of unzip(readFileSync(join(itemRoot, "package.zip")))) {
216
+ const relativePath = safeRelativePath(entry.path);
217
+ const target = ensureInside(packageRoot, join(packageRoot, ...relativePath.split("/")));
218
+ mkdirSync(dirname(target), { recursive: true });
219
+ writeFileSync(target, entry.content);
220
+ }
221
+ skillRootPath = relative(stageRoot, skillRoot(packageRoot)).replaceAll("\\", "/");
222
+ }
223
+ let runtimeEntryPath;
224
+ if (item.resource_type === "strategy" || item.resource_type === "perception" || item.resource_type === "persona") {
225
+ const source = sourceFiles[0];
226
+ const extension = extname(source.relativePath).toLowerCase();
227
+ const runtimeDir = item.resource_type === "strategy" ? "behaviors" : item.resource_type === "perception" ? "perceptions" : "personas";
228
+ const runtimePath = join(stageRoot, "runtime", runtimeDir, `${item.resource_id}${extension}`);
229
+ mkdirSync(dirname(runtimePath), { recursive: true });
230
+ writeFileSync(runtimePath, readFileSync(join(sourceRoot, ...source.path.split("/"))));
231
+ runtimeEntryPath = relative(stageRoot, runtimePath).replaceAll("\\", "/");
232
+ }
233
+ return {
234
+ workspaceItemId: item.workspace_item_id,
235
+ resourceId: item.resource_id,
236
+ forkedFromResourceId: item.forked_from_resource_id ?? void 0,
237
+ versionId: item.version_id,
238
+ title: item.title,
239
+ description: item.description,
240
+ versionNumber: item.version_number,
241
+ versionDescription: item.version_description,
242
+ resourceType: item.resource_type,
243
+ hub: {
244
+ workspaceKind: item.workspace_kind,
245
+ publisher: item.owner.is_official ? "official" : item.is_created_by_me ? "self" : "community",
246
+ ownerId: item.owner.id,
247
+ ownerName: item.owner.name,
248
+ ownerAvatarUrl: item.owner.avatar_url,
249
+ ownerIsOfficial: item.owner.is_official
250
+ },
251
+ contentDigest: item.content_digest,
252
+ sourceFiles: sourceFiles.map((file) => ({
253
+ ...file,
254
+ path: relative(stageRoot, join(sourceRoot, ...file.path.split("/"))).replaceAll("\\", "/")
255
+ })),
256
+ ...archiveFile ? { archiveFile } : {},
257
+ ...runtimeEntryPath ? { runtimeEntryPath } : {},
258
+ ...skillRootPath ? { skillRootPath } : {}
259
+ };
260
+ }
261
+ function emptyItems() {
262
+ return { skill: [], strategy: [], persona: [], perception: [] };
263
+ }
264
+ function localAgentWorkspaceSnapshotRoot(workspaceDir, profile, snapshot) {
265
+ return join(getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile), snapshot.relativeDir);
266
+ }
267
+ function resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot, relativePath) {
268
+ const root = localAgentWorkspaceSnapshotRoot(workspaceDir, profile, snapshot);
269
+ return ensureInside(root, join(root, ...safeRelativePath(relativePath).split("/")));
270
+ }
271
+ function singleFileContentDigest(relativePath, bytes) {
272
+ return createHash("sha256").update(JSON.stringify([{
273
+ relative_path: relativePath,
274
+ sha256: sha256(bytes),
275
+ size_bytes: bytes.length
276
+ }]), "utf8").digest("hex");
277
+ }
278
+ function knownVersions(item) {
279
+ const entries = [
280
+ ...item.knownVersions ?? [],
281
+ ...item.sourceFiles[0] ? [{
282
+ versionId: item.versionId,
283
+ contentDigest: item.contentDigest,
284
+ sourceSha256: item.sourceFiles[0].sha256
285
+ }] : []
286
+ ];
287
+ return [...new Map(entries.map((entry) => [entry.versionId, entry])).values()];
288
+ }
289
+ function hubWorkingRoot(workspaceDir, profile, type) {
290
+ if (type === "strategy") return getUserDataAccountHubBehaviorsDir(workspaceDir, profile);
291
+ if (type === "perception") return getUserDataAccountHubPerceptionsDir(workspaceDir, profile);
292
+ return getUserDataAccountHubPersonasDir(workspaceDir, profile);
293
+ }
294
+ function hubWorkingCopyPath(workspaceDir, profile, type, resourceId, relativePath) {
295
+ const root = hubWorkingRoot(workspaceDir, profile, type);
296
+ return ensureInside(
297
+ root,
298
+ join(root, safeSegment(resourceId, "resource_id"), ...safeRelativePath(relativePath).split("/"))
299
+ );
300
+ }
301
+ function accountRelativePath(workspaceDir, profile, path) {
302
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
303
+ return relative(accountRoot, ensureInside(accountRoot, path)).replaceAll("\\", "/");
304
+ }
305
+ function resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item) {
306
+ if (!item.workingCopyPath) return void 0;
307
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
308
+ return ensureInside(
309
+ accountRoot,
310
+ join(accountRoot, ...safeRelativePath(item.workingCopyPath).split("/"))
311
+ );
312
+ }
313
+ function writeFileAtomically(path, bytes) {
314
+ mkdirSync(dirname(path), { recursive: true });
315
+ const temporary = `${path}.${randomUUID()}.tmp`;
316
+ writeFileSync(temporary, bytes);
317
+ renameSync(temporary, path);
318
+ }
319
+ function workingCopyMetadataPath(workspaceDir, profile, type, resourceId) {
320
+ return join(
321
+ getUserDataAgentWorkspaceDir(workspaceDir, profile),
322
+ "working-copies",
323
+ type,
324
+ `${safeSegment(resourceId, "resource_id")}.json`
325
+ );
326
+ }
327
+ function readWorkingCopyMetadata(path, expected) {
328
+ if (!existsSync(path)) return void 0;
329
+ try {
330
+ const value = JSON.parse(readFileSync(path, "utf8"));
331
+ if (value.format !== 1 || value.resourceType !== expected.resourceType || value.resourceId !== expected.resourceId || value.relativePath !== expected.relativePath || !Array.isArray(value.knownVersions) || value.knownVersions.some((entry) => !entry || typeof entry.versionId !== "string" || !SHA256.test(entry.contentDigest) || !SHA256.test(entry.sourceSha256))) return void 0;
332
+ return value;
333
+ } catch {
334
+ return void 0;
335
+ }
336
+ }
337
+ function inspectLocalSnapshot(workspaceDir, profile, snapshot) {
338
+ const resolved = structuredClone(snapshot);
339
+ const overrides = /* @__PURE__ */ new Map();
340
+ let projectionOutdated = false;
341
+ let workingMetadataMissing = false;
342
+ for (const type of ["strategy", "persona", "perception"]) {
343
+ for (const item of resolved.items[type]) {
344
+ const source = item.sourceFiles[0];
345
+ if (!source || !item.runtimeEntryPath) continue;
346
+ const projectionPath = resolveLocalAgentWorkspacePath(
347
+ workspaceDir,
348
+ profile,
349
+ resolved,
350
+ item.runtimeEntryPath
351
+ );
352
+ let workingPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item);
353
+ if (!workingPath) {
354
+ workingPath = hubWorkingCopyPath(
355
+ workspaceDir,
356
+ profile,
357
+ type,
358
+ item.resourceId,
359
+ source.relativePath
360
+ );
361
+ item.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath);
362
+ if (!existsSync(workingPath)) {
363
+ const legacyPath = projectionPath;
364
+ if (existsSync(legacyPath)) writeFileAtomically(workingPath, readFileSync(legacyPath));
365
+ }
366
+ }
367
+ if (!existsSync(workingPath)) {
368
+ item.resolution = "hub";
369
+ projectionOutdated = true;
370
+ continue;
371
+ }
372
+ if (!existsSync(workingCopyMetadataPath(workspaceDir, profile, type, item.resourceId))) {
373
+ workingMetadataMissing = true;
374
+ }
375
+ const bytes = readFileSync(workingPath);
376
+ const localSha = sha256(bytes);
377
+ const projectionSha = existsSync(projectionPath) ? sha256(readFileSync(projectionPath)) : void 0;
378
+ item.knownVersions = knownVersions(item);
379
+ if (localSha === source.sha256) {
380
+ item.resolution = "hub";
381
+ if (projectionSha !== localSha) projectionOutdated = true;
382
+ delete item.localContentDigest;
383
+ delete item.localModifiedAtMs;
384
+ continue;
385
+ }
386
+ if (item.knownVersions.some((entry) => entry.sourceSha256 === localSha)) {
387
+ item.resolution = "known_online_old";
388
+ const basePath = resolveLocalAgentWorkspacePath(
389
+ workspaceDir,
390
+ profile,
391
+ resolved,
392
+ source.path
393
+ );
394
+ if (existsSync(basePath)) {
395
+ const baseBytes = readFileSync(basePath);
396
+ writeFileAtomically(workingPath, baseBytes);
397
+ if (projectionSha !== sha256(baseBytes)) projectionOutdated = true;
398
+ }
399
+ delete item.localContentDigest;
400
+ delete item.localModifiedAtMs;
401
+ continue;
402
+ }
403
+ const localDigest = singleFileContentDigest(source.relativePath, bytes);
404
+ const modifiedAtMs = statSync(workingPath).mtimeMs;
405
+ item.resolution = item.resolution === "local_origin_unrecognized" ? "local_origin_unrecognized" : item.resolution === "concurrent_difference" ? "concurrent_difference" : "local_modified";
406
+ item.localContentDigest = localDigest;
407
+ item.localModifiedAtMs = modifiedAtMs;
408
+ if (projectionSha !== localSha) projectionOutdated = true;
409
+ overrides.set(`${type}:${item.resourceId}`, {
410
+ bytes,
411
+ sha256: localSha,
412
+ contentDigest: localDigest,
413
+ modifiedAtMs,
414
+ originRecognized: item.resolution !== "local_origin_unrecognized"
415
+ });
416
+ }
417
+ }
418
+ return { snapshot: resolved, overrides, projectionOutdated, workingMetadataMissing };
419
+ }
420
+ function resolveLocalAgentWorkspaceSnapshot(workspaceDir, profile, snapshot) {
421
+ return inspectLocalSnapshot(workspaceDir, profile, snapshot).snapshot;
422
+ }
423
+ function readLocalAgentWorkspaceSnapshot(workspaceDir, profile) {
424
+ const pointerPath = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile);
425
+ if (!existsSync(pointerPath)) return void 0;
426
+ try {
427
+ const pointer = JSON.parse(readFileSync(pointerPath, "utf8"));
428
+ safeSegment(pointer.relative_dir, "revision_dir");
429
+ const snapshotPath = join(
430
+ getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile),
431
+ pointer.relative_dir,
432
+ "snapshot.json"
433
+ );
434
+ const snapshot = JSON.parse(readFileSync(snapshotPath, "utf8"));
435
+ if (snapshot.revision !== pointer.revision || snapshot.relativeDir !== pointer.relative_dir) return void 0;
436
+ return snapshot;
437
+ } catch {
438
+ return void 0;
439
+ }
440
+ }
441
+ function writeCurrentPointer(workspaceDir, profile, pointer) {
442
+ const target = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile);
443
+ mkdirSync(dirname(target), { recursive: true });
444
+ const temporary = `${target}.${randomUUID()}.tmp`;
445
+ writeFileSync(temporary, `${JSON.stringify(pointer, null, 2)}
446
+ `, "utf8");
447
+ renameSync(temporary, target);
448
+ }
449
+ function retireReplacedForkParent(workspaceDir, profile, parent, transferOperationName) {
450
+ const entry = capabilityEntryForHubResource(workspaceDir, profile, parent.type, parent.resourceId);
451
+ if (!entry || !existsSync(parent.path) || sha256(readFileSync(parent.path)) !== parent.sha256) return;
452
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
453
+ if (registry.entries[entry.key]?.hub?.resourceId !== parent.resourceId) return;
454
+ const child = Object.values(registry.entries).find((candidate) => candidate.type === parent.type && candidate.hub?.resourceId === parent.childResourceId);
455
+ if (!child) return;
456
+ if (transferOperationName && child.declaredId === entry.declaredId && !Object.values(registry.entries).some((candidate) => candidate.key !== entry.key && candidate.key !== child.key && candidate.type === parent.type && candidate.runtimeId === entry.runtimeId)) child.runtimeId = entry.runtimeId;
457
+ const oldOperationName = entry.runtimeId;
458
+ const newOperationName = child.runtimeId;
459
+ if (parent.clean) rmSync(parent.path, { force: true });
460
+ delete registry.entries[entry.key];
461
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
462
+ if (oldOperationName !== newOperationName && parent.type !== "persona") {
463
+ updateGameplayConfig((config) => {
464
+ if (parent.type === "behavior") {
465
+ for (const role of Object.keys(config.fallback_behaviors)) {
466
+ if (config.fallback_behaviors[role] === oldOperationName) {
467
+ config.fallback_behaviors[role] = newOperationName;
468
+ }
469
+ }
470
+ config.disabled_behaviors = [...new Set(config.disabled_behaviors.map((id) => id === oldOperationName ? newOperationName : id))];
471
+ for (const trigger of Object.values(config.triggers)) {
472
+ if (trigger.behavior === oldOperationName) trigger.behavior = newOperationName;
473
+ }
474
+ } else {
475
+ config.disabled_perception_modules = [...new Set(config.disabled_perception_modules.map((id) => id === oldOperationName ? newOperationName : id))];
476
+ }
477
+ }, workspaceDir, profile);
478
+ }
479
+ }
480
+ async function syncAgentWorkspaceConfig(workspaceDir, profile, dependencies = {}) {
481
+ const previousRaw = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
482
+ const inspected = previousRaw ? inspectLocalSnapshot(workspaceDir, profile, previousRaw) : void 0;
483
+ const previous = inspected?.snapshot;
484
+ const client = dependencies.client ?? new AgentWorkspaceClient(profile);
485
+ const remote = await client.getConfig();
486
+ validateRemoteConfig(remote);
487
+ if (previous && dependencies.workspaceInventory) {
488
+ const inventory = dependencies.workspaceInventory;
489
+ for (const item of Object.values(previous.items).flat()) {
490
+ const relation = item.forkReconciliation;
491
+ if (relation?.status !== "linked" || inventory.some((candidate) => candidate.resourceId === relation.parentResourceId) || !inventory.some((candidate) => candidate.resourceId === item.resourceId)) continue;
492
+ const type = item.resourceType === "strategy" ? "behavior" : item.resourceType;
493
+ if (item.resourceType === "skill") continue;
494
+ const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, type, relation.parentResourceId);
495
+ if (!parentEntry) continue;
496
+ const path = capabilityWorkspacePath(workspaceDir, profile, parentEntry);
497
+ if (!existsSync(path)) continue;
498
+ const digest = sha256(readFileSync(path));
499
+ const remoteChild = remote.items[item.resourceType].find((candidate) => candidate.resource_id === item.resourceId);
500
+ const clean = digest === parentEntry.hub?.baseSha256 || digest === remoteChild?.source_files[0]?.sha256;
501
+ if (!clean) continue;
502
+ retireReplacedForkParent(workspaceDir, profile, {
503
+ type,
504
+ resourceId: relation.parentResourceId,
505
+ childResourceId: item.resourceId,
506
+ path,
507
+ sha256: digest,
508
+ clean
509
+ }, false);
510
+ }
511
+ }
512
+ const contentUnchanged = previous && RESOURCE_TYPES.every((type) => {
513
+ const items = previous.items[type];
514
+ return items.length === remote.items[type].length && remote.items[type].every((item) => items.some((old) => old.resourceId === item.resource_id && old.versionId === item.version_id && old.workspaceItemId === item.workspace_item_id && old.contentDigest === item.content_digest && old.title === item.title && old.description === item.description && old.forkedFromResourceId === (item.forked_from_resource_id ?? void 0)));
515
+ });
516
+ if (previous?.revision === remote.revision && contentUnchanged && previous.metadataVersion === 1 && previous.layoutVersion === 3 && inspected?.projectionOutdated !== true && inspected?.workingMetadataMissing !== true) {
517
+ return {
518
+ status: inspected && inspected.overrides.size > 0 ? "local_overrides" : "unchanged",
519
+ snapshot: previous,
520
+ previous
521
+ };
522
+ }
523
+ const revisionsDir = getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile);
524
+ mkdirSync(revisionsDir, { recursive: true });
525
+ const temporary = join(getUserDataAgentWorkspaceDir(workspaceDir, profile), `.staging-${randomUUID()}`);
526
+ mkdirSync(temporary, { recursive: true });
527
+ try {
528
+ const items = emptyItems();
529
+ const workingUpdates = [];
530
+ const workingMetadataUpdates = [];
531
+ const forkReplacements = [];
532
+ const forkRegistrations = [];
533
+ const replacedForkParents = [];
534
+ const unresolvedParentKeys = /* @__PURE__ */ new Set();
535
+ const previousByKey = new Map(
536
+ RESOURCE_TYPES.map((type) => [
537
+ type,
538
+ new Map((previous?.items[type] ?? []).map((item) => [item.resourceId, item]))
539
+ ])
540
+ );
541
+ const selectedResourceIds = new Set(Object.values(remote.items).flat().map((item) => item.resource_id));
542
+ const forkChildren = /* @__PURE__ */ new Map();
543
+ const addChild = (parent, child) => {
544
+ if (!parent) return;
545
+ const children = forkChildren.get(parent) ?? /* @__PURE__ */ new Set();
546
+ children.add(child);
547
+ forkChildren.set(parent, children);
548
+ };
549
+ for (const item of Object.values(remote.items).flat()) addChild(item.forked_from_resource_id, item.resource_id);
550
+ for (const item of dependencies.workspaceInventory ?? []) addChild(item.forkedFromResourceId, item.resourceId);
551
+ for (const type of RESOURCE_TYPES) {
552
+ for (const item of remote.items[type]) {
553
+ let materialized;
554
+ try {
555
+ materialized = await materializeItem(temporary, item, dependencies.download ?? downloadAgentWorkspaceFile);
556
+ } catch (error) {
557
+ throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:${item.source_files.map((file) => file.relative_path).join(",")}:${error instanceof Error ? error.message : String(error)}`);
558
+ }
559
+ const prior = previousByKey.get(type)?.get(materialized.resourceId);
560
+ let workingPath;
561
+ let persistedWorkingMetadata;
562
+ let targetAlreadyRegistered = false;
563
+ let pendingForkConflict = false;
564
+ if (type !== "skill" && materialized.sourceFiles[0]) {
565
+ const workspaceType = type === "strategy" ? "behavior" : type;
566
+ const registered = capabilityEntryForHubResource(
567
+ workspaceDir,
568
+ profile,
569
+ workspaceType,
570
+ materialized.resourceId
571
+ );
572
+ targetAlreadyRegistered = registered !== void 0;
573
+ pendingForkConflict = registered?.hub?.pendingForkConflict === true;
574
+ workingPath = registered ? capabilityWorkspacePath(workspaceDir, profile, registered) : hubWorkingCopyPath(
575
+ workspaceDir,
576
+ profile,
577
+ type,
578
+ materialized.resourceId,
579
+ materialized.sourceFiles[0].relativePath
580
+ );
581
+ materialized.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath);
582
+ persistedWorkingMetadata = readWorkingCopyMetadata(
583
+ workingCopyMetadataPath(workspaceDir, profile, type, materialized.resourceId),
584
+ {
585
+ resourceType: type,
586
+ resourceId: materialized.resourceId,
587
+ relativePath: materialized.sourceFiles[0].relativePath
588
+ }
589
+ );
590
+ }
591
+ materialized.knownVersions = [...new Map([
592
+ ...prior ? knownVersions(prior) : [],
593
+ ...persistedWorkingMetadata?.knownVersions ?? [],
594
+ ...knownVersions(materialized)
595
+ ].map((entry) => [entry.versionId, entry])).values()];
596
+ materialized.forkReconciliation = prior?.forkReconciliation ?? persistedWorkingMetadata?.forkReconciliation;
597
+ let override = inspected?.overrides.get(`${type}:${materialized.resourceId}`);
598
+ let forkCloudChanged;
599
+ const parentId = materialized.forkedFromResourceId;
600
+ const parent = parentId ? previousByKey.get(type)?.get(parentId) : void 0;
601
+ if (type !== "skill" && parent && !prior && !targetAlreadyRegistered && !materialized.forkReconciliation) {
602
+ if (!dependencies.workspaceInventory) {
603
+ throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:fork_inventory_unavailable`);
604
+ }
605
+ const workspaceType = type === "strategy" ? "behavior" : type;
606
+ const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, workspaceType, parent.resourceId);
607
+ const relation = {
608
+ parentResourceId: parent.resourceId,
609
+ parentVersionId: parent.versionId,
610
+ parentOperationName: parentEntry?.runtimeId,
611
+ status: "unresolved"
612
+ };
613
+ const parentPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, parent);
614
+ const baseline = parent.sourceFiles[0]?.sha256;
615
+ if (!item.is_created_by_me || item.workspace_kind !== "owned") relation.reason = "not_owned";
616
+ else if (selectedResourceIds.has(parent.resourceId)) relation.reason = "parent_still_equipped";
617
+ else if (forkChildren.get(parent.resourceId)?.size !== 1) relation.reason = "multiple_forks";
618
+ else if (!baseline || parent.resolution === "local_origin_unrecognized" || parentEntry?.hub?.localOriginUnrecognized) {
619
+ relation.reason = "baseline_unrecognized";
620
+ } else if (!parentPath || !existsSync(parentPath)) relation.reason = "parent_working_copy_missing";
621
+ else if (workingPath && existsSync(workingPath)) relation.reason = "target_working_copy_exists";
622
+ else {
623
+ const bytes = readFileSync(parentPath);
624
+ const digest = sha256(bytes);
625
+ relation.status = "linked";
626
+ forkReplacements.push(item.resource_id);
627
+ const localChanged = digest !== baseline;
628
+ const childSha256 = materialized.sourceFiles[0]?.sha256;
629
+ if (!dependencies.workspaceInventory.some((candidate) => candidate.resourceId === parent.resourceId)) {
630
+ replacedForkParents.push({
631
+ type: workspaceType,
632
+ resourceId: parent.resourceId,
633
+ childResourceId: item.resource_id,
634
+ path: parentPath,
635
+ sha256: digest,
636
+ clean: !localChanged || digest === childSha256
637
+ });
638
+ }
639
+ if (localChanged && digest !== childSha256) {
640
+ override = {
641
+ bytes,
642
+ sha256: digest,
643
+ contentDigest: singleFileContentDigest(materialized.sourceFiles[0].relativePath, bytes),
644
+ modifiedAtMs: statSync(parentPath).mtimeMs,
645
+ originRecognized: true
646
+ };
647
+ forkCloudChanged = true;
648
+ }
649
+ }
650
+ materialized.forkReconciliation = relation;
651
+ if (relation.status === "unresolved" && parentEntry) unresolvedParentKeys.add(parentEntry.key);
652
+ }
653
+ if (!override && !prior && workingPath && existsSync(workingPath)) {
654
+ const bytes = readFileSync(workingPath);
655
+ const localSha = sha256(bytes);
656
+ if (!persistedWorkingMetadata?.knownVersions.some((entry) => entry.sourceSha256 === localSha)) {
657
+ override = {
658
+ bytes,
659
+ sha256: localSha,
660
+ contentDigest: singleFileContentDigest(
661
+ materialized.sourceFiles[0].relativePath,
662
+ bytes
663
+ ),
664
+ modifiedAtMs: statSync(workingPath).mtimeMs,
665
+ originRecognized: persistedWorkingMetadata !== void 0
666
+ };
667
+ }
668
+ }
669
+ let effectiveBytes;
670
+ if (override && materialized.runtimeEntryPath && materialized.sourceFiles[0]?.sha256 !== override.sha256) {
671
+ const runtimePath = ensureInside(
672
+ temporary,
673
+ join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split("/"))
674
+ );
675
+ writeFileSync(runtimePath, override.bytes);
676
+ effectiveBytes = override.bytes;
677
+ const remoteAdvancedFromLocalBaseline = forkCloudChanged ?? (prior ? prior.versionId !== materialized.versionId : persistedWorkingMetadata !== void 0 && !persistedWorkingMetadata.knownVersions.some(
678
+ (entry) => entry.versionId === materialized.versionId
679
+ ));
680
+ materialized.resolution = !override.originRecognized ? "local_origin_unrecognized" : remoteAdvancedFromLocalBaseline || prior?.resolution === "concurrent_difference" || pendingForkConflict ? "concurrent_difference" : "local_modified";
681
+ materialized.localContentDigest = override.contentDigest;
682
+ materialized.localModifiedAtMs = override.modifiedAtMs;
683
+ } else {
684
+ materialized.resolution = "hub";
685
+ if (materialized.runtimeEntryPath) {
686
+ effectiveBytes = readFileSync(ensureInside(
687
+ temporary,
688
+ join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split("/"))
689
+ ));
690
+ }
691
+ }
692
+ if (prior && materialized.resolution === "hub" && materialized.runtimeEntryPath) {
693
+ const path = join(temporary, materialized.runtimeEntryPath);
694
+ if (type === "strategy") {
695
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
696
+ if (!source || source.apiVersion !== BEHAVIOR_PLUGIN_API_VERSION || behaviorSourceCompatibilityError(source)) {
697
+ throw new Error(`agent_workspace_resource_failed:strategy:${item.resource_id}:cloud_module_invalid`);
698
+ }
699
+ } else if (type === "perception") {
700
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path)).find((source2) => source2.sourcePath === path);
701
+ if (!source || !isSupportedPerceptionSource(source)) {
702
+ throw new Error(`agent_workspace_resource_failed:perception:${item.resource_id}:cloud_module_invalid`);
703
+ }
704
+ }
705
+ }
706
+ if (materialized.workingCopyPath && effectiveBytes) {
707
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
708
+ workingUpdates.push({
709
+ path: ensureInside(
710
+ accountRoot,
711
+ join(accountRoot, ...safeRelativePath(materialized.workingCopyPath).split("/"))
712
+ ),
713
+ bytes: effectiveBytes
714
+ });
715
+ workingMetadataUpdates.push({
716
+ path: workingCopyMetadataPath(
717
+ workspaceDir,
718
+ profile,
719
+ type,
720
+ materialized.resourceId
721
+ ),
722
+ value: {
723
+ format: 1,
724
+ resourceType: type,
725
+ resourceId: materialized.resourceId,
726
+ relativePath: materialized.sourceFiles[0].relativePath,
727
+ knownVersions: materialized.knownVersions,
728
+ forkReconciliation: materialized.forkReconciliation
729
+ }
730
+ });
731
+ if (materialized.forkReconciliation?.status === "linked" && forkReplacements.includes(item.resource_id)) {
732
+ const workspaceType = type === "strategy" ? "behavior" : type;
733
+ const stagedPath = join(temporary, materialized.runtimeEntryPath);
734
+ const source = type === "strategy" ? inspectClawclawBehaviorSource(stagedPath, dirname(stagedPath)) : type === "perception" ? listClawclawPerceptionSourcesInDirectory(dirname(stagedPath)).find((source2) => source2.sourcePath === stagedPath) : void 0;
735
+ const parentEntry = capabilityEntryForHubResource(
736
+ workspaceDir,
737
+ profile,
738
+ workspaceType,
739
+ materialized.forkReconciliation.parentResourceId
740
+ );
741
+ const runtimeId = source?.id ?? (type === "persona" ? materialized.sourceFiles[0].relativePath.replace(/\.md$/i, "") : parentEntry?.declaredId ?? parentEntry?.runtimeId);
742
+ if (runtimeId) forkRegistrations.push({
743
+ type: workspaceType,
744
+ path: workingPath,
745
+ runtimeId,
746
+ title: item.title ?? parentEntry?.title ?? source?.id,
747
+ description: item.description ?? parentEntry?.description ?? source?.description,
748
+ selectedByHub: true,
749
+ hub: {
750
+ resourceId: item.resource_id,
751
+ versionId: item.version_id,
752
+ workspaceItemId: item.workspace_item_id,
753
+ publisher: "self",
754
+ baseSha256: materialized.sourceFiles[0].sha256,
755
+ pendingForkConflict: materialized.resolution === "concurrent_difference" || void 0
756
+ }
757
+ });
758
+ }
759
+ }
760
+ items[type].push(materialized);
761
+ }
762
+ }
763
+ const relativeDir = `revision-${remote.revision}-${randomUUID()}`;
764
+ const snapshot = {
765
+ metadataVersion: 1,
766
+ layoutVersion: 3,
767
+ revision: remote.revision,
768
+ syncedAt: (dependencies.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
769
+ relativeDir,
770
+ items
771
+ };
772
+ writeFileSync(join(temporary, "snapshot.json"), `${JSON.stringify(snapshot, null, 2)}
773
+ `, "utf8");
774
+ for (const update of workingUpdates) writeFileAtomically(update.path, update.bytes);
775
+ for (const update of workingMetadataUpdates) {
776
+ writeFileAtomically(update.path, Buffer.from(`${JSON.stringify(update.value, null, 2)}
777
+ `, "utf8"));
778
+ }
779
+ const target = join(revisionsDir, relativeDir);
780
+ renameSync(temporary, target);
781
+ writeCurrentPointer(workspaceDir, profile, { revision: remote.revision, relative_dir: relativeDir });
782
+ for (const registration of forkRegistrations) registerDiscoveredCapability(workspaceDir, profile, registration);
783
+ for (const parent of replacedForkParents) retireReplacedForkParent(workspaceDir, profile, parent, true);
784
+ for (const key of unresolvedParentKeys) {
785
+ const parent = Object.values(previous?.items ?? {}).flat().find((item) => {
786
+ const type2 = item.resourceType === "strategy" ? "behavior" : item.resourceType;
787
+ return capabilityEntryForHubResource(workspaceDir, profile, type2, item.resourceId)?.key === key;
788
+ });
789
+ if (!parent) continue;
790
+ const type = parent.resourceType === "strategy" ? "behavior" : parent.resourceType;
791
+ const entry = capabilityEntryForHubResource(workspaceDir, profile, type, parent.resourceId);
792
+ updateCapabilityHubIdentity(workspaceDir, profile, key, { ...entry.hub, forkRelationshipUnresolved: true });
793
+ }
794
+ return {
795
+ status: "updated",
796
+ snapshot,
797
+ ...previous ? { previous } : {},
798
+ ...forkReplacements.length ? { forkReplacements } : {}
799
+ };
800
+ } catch (error) {
801
+ rmSync(temporary, { recursive: true, force: true });
802
+ throw error;
803
+ }
804
+ }
805
+ export {
806
+ localAgentWorkspaceSnapshotRoot,
807
+ readLocalAgentWorkspaceSnapshot,
808
+ resolveLocalAgentWorkspacePath,
809
+ resolveLocalAgentWorkspaceSnapshot,
810
+ resolveLocalAgentWorkspaceWorkingCopyPath,
811
+ syncAgentWorkspaceConfig
812
+ };