@myclaw163/clawclaw-cli 0.8.4 → 0.8.6

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 (330) hide show
  1. package/README.md +4 -3
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/behavior.md +10 -19
  5. package/docs/custom-modules/perception.md +1 -1
  6. package/docs/custom-modules/trigger.md +1 -1
  7. package/docs/runtime/README.md +4 -4
  8. package/docs/runtime/official-perception-modules.md +2 -2
  9. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  10. package/package.json +15 -2
  11. package/scripts/enable_ccl_permissions.cjs +4 -2
  12. package/scripts/find-hide-spots.py +2 -2
  13. package/scripts/postinstall.mjs +1 -4
  14. package/scripts/sync-bundled-skill.mjs +12 -159
  15. package/skills/clawclaw/SKILL.md +25 -18
  16. package/skills/clawclaw/references/BEHAVIORS.md +15 -11
  17. package/skills/clawclaw/references/COMMANDS.md +45 -41
  18. package/skills/clawclaw/references/HUB.md +25 -38
  19. package/skills/clawclaw/references/TACTICS.md +1 -1
  20. package/src/commands/account.ts +58 -14
  21. package/src/commands/behavior.ts +116 -38
  22. package/src/commands/hub.ts +110 -153
  23. package/src/commands/load.ts +138 -33
  24. package/src/commands/perception.ts +55 -24
  25. package/src/commands/persona.ts +66 -20
  26. package/src/commands/skill.ts +12 -48
  27. package/src/commands/trigger.ts +68 -40
  28. package/src/lib/account-guidance.ts +54 -9
  29. package/src/lib/agent-workspace-client.ts +135 -0
  30. package/src/lib/agent-workspace-runtime.ts +154 -0
  31. package/src/lib/agent-workspace-skills.ts +177 -0
  32. package/src/lib/agent-workspace-sync.ts +852 -0
  33. package/src/lib/gameplay-config.ts +29 -15
  34. package/src/lib/hub-client.ts +252 -34
  35. package/src/lib/hub-reminder.ts +24 -11
  36. package/src/lib/init-command.ts +0 -6
  37. package/src/lib/load-context.ts +12 -6
  38. package/src/lib/persona.ts +141 -69
  39. package/src/lib/server-status.ts +78 -0
  40. package/src/lib/skill-host.ts +160 -0
  41. package/src/lib/user-data.ts +197 -4
  42. package/src/runtime/clawclaw/behavior-read-api.ts +1 -1
  43. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/astar-path.ts +1 -1
  44. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/escape-planner.ts +1 -1
  45. package/src/{strategies → runtime/clawclaw/navigation}/hide-spots.ts +2 -2
  46. package/src/{strategies → runtime/clawclaw/navigation}/off-route-points.ts +6 -3
  47. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/walkable-grid.ts +1 -1
  48. package/src/runtime/clawclaw/owner.ts +63 -19
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  51. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +1 -1
  52. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  53. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  54. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  55. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -54
  56. package/src/sdk/behavior-toolkit/escape.ts +2 -2
  57. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  58. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  59. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  60. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  61. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  62. package/scripts/compare-perception-replays.test.ts +0 -188
  63. package/scripts/enable_ccl_permissions.test.mjs +0 -163
  64. package/scripts/enable_monitor.test.mjs +0 -201
  65. package/scripts/sync-bundled-skill.test.mjs +0 -152
  66. package/scripts/watch-perception-events.test.ts +0 -43
  67. package/src/behaviors/official-finite/do-task.ts +0 -211
  68. package/src/behaviors/official-finite/evade.ts +0 -78
  69. package/src/behaviors/official-finite/find-player.ts +0 -50
  70. package/src/behaviors/official-finite/follow-player.ts +0 -70
  71. package/src/behaviors/official-finite/go-to.ts +0 -69
  72. package/src/behaviors/official-finite/hide-temporarily.ts +0 -77
  73. package/src/behaviors/official-finite/hold-position.ts +0 -48
  74. package/src/behaviors/official-finite/hunt-player.ts +0 -47
  75. package/src/behaviors/official-finite/index.test.ts +0 -249
  76. package/src/behaviors/official-finite/index.ts +0 -44
  77. package/src/behaviors/official-finite/inspect-corpse.ts +0 -64
  78. package/src/behaviors/official-finite/patrol-area.ts +0 -80
  79. package/src/behaviors/official-finite/report-corpse.ts +0 -73
  80. package/src/behaviors/official-finite/seek-kill-opportunity.ts +0 -152
  81. package/src/behaviors/official-finite/shared.ts +0 -27
  82. package/src/channel/claude-channel-server.test.ts +0 -202
  83. package/src/commands/account.test.ts +0 -570
  84. package/src/commands/behavior.test.ts +0 -158
  85. package/src/commands/communication.test.ts +0 -282
  86. package/src/commands/competition.test.ts +0 -116
  87. package/src/commands/data.test.ts +0 -89
  88. package/src/commands/events-canonical-state.test.ts +0 -406
  89. package/src/commands/events.test.ts +0 -58
  90. package/src/commands/game/index.test.ts +0 -1251
  91. package/src/commands/game-map.test.ts +0 -69
  92. package/src/commands/hub.test.ts +0 -124
  93. package/src/commands/load.test.ts +0 -440
  94. package/src/commands/perception.test.ts +0 -75
  95. package/src/commands/setup/hermes.test.ts +0 -96
  96. package/src/commands/setup/openclaw.test.ts +0 -124
  97. package/src/commands/trigger.test.ts +0 -140
  98. package/src/commands/upgrade.test.ts +0 -82
  99. package/src/lib/account-guidance.test.ts +0 -36
  100. package/src/lib/auth.test.ts +0 -151
  101. package/src/lib/behavior-export.test.ts +0 -326
  102. package/src/lib/behavior-export.ts +0 -537
  103. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  104. package/src/lib/custom-tts.test.ts +0 -387
  105. package/src/lib/diagnostics-config.test.ts +0 -59
  106. package/src/lib/game-client-tts.test.ts +0 -151
  107. package/src/lib/game-client.test.ts +0 -250
  108. package/src/lib/gameplay-config.test.ts +0 -301
  109. package/src/lib/host-config-patcher.test.ts +0 -130
  110. package/src/lib/http-transport.test.ts +0 -124
  111. package/src/lib/hub-client.test.ts +0 -57
  112. package/src/lib/hub-install.test.ts +0 -135
  113. package/src/lib/hub-install.ts +0 -185
  114. package/src/lib/hub-unzip.test.ts +0 -69
  115. package/src/lib/init-command.test.ts +0 -103
  116. package/src/lib/load-context.test.ts +0 -62
  117. package/src/lib/match-state.test.ts +0 -134
  118. package/src/lib/official-resource-sync.test.ts +0 -199
  119. package/src/lib/official-resource-sync.ts +0 -221
  120. package/src/lib/perception-config.test.ts +0 -143
  121. package/src/lib/perception-export.test.ts +0 -145
  122. package/src/lib/perception-export.ts +0 -178
  123. package/src/lib/persona.test.ts +0 -84
  124. package/src/lib/room.test.ts +0 -88
  125. package/src/lib/server-registry.test.ts +0 -64
  126. package/src/lib/service-status.test.ts +0 -81
  127. package/src/lib/skill-version.test.ts +0 -48
  128. package/src/lib/trigger-config.test.ts +0 -102
  129. package/src/lib/trigger-export.test.ts +0 -80
  130. package/src/lib/trigger-export.ts +0 -210
  131. package/src/lib/user-data.test.ts +0 -121
  132. package/src/lib/workspace-argv.test.ts +0 -49
  133. package/src/pipeline/canonical-event-presentation.test.ts +0 -257
  134. package/src/pipeline/event-format.test.ts +0 -879
  135. package/src/pipeline/event-hints.test.ts +0 -337
  136. package/src/pipeline/game-sync-event-normalization.test.ts +0 -419
  137. package/src/pipeline/player-projection.test.ts +0 -247
  138. package/src/runtime/auto-upgrade.test.ts +0 -66
  139. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  140. package/src/runtime/canonical-monitor.test.ts +0 -577
  141. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -60
  142. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  143. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  144. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  145. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  146. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  147. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  148. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  149. package/src/runtime/clawclaw/owner.test.ts +0 -203
  150. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -328
  151. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  152. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  153. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -43
  154. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  155. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  156. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  157. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  158. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  159. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -757
  160. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  161. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  162. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  163. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  164. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  165. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  166. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  167. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  168. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  169. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  170. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  171. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  172. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  173. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  174. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  175. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  176. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  177. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  178. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  179. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  180. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  181. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  182. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  183. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  184. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  185. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  186. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  187. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  188. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  189. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  190. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  191. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  192. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  193. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  194. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  195. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -853
  196. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  197. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  198. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  199. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  200. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  201. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  202. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  203. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  204. package/src/runtime/clawclaw-event-catalog.test.ts +0 -128
  205. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  206. package/src/runtime/framework/capability-registry.test.ts +0 -423
  207. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  208. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  209. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  210. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  211. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  212. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  213. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  214. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  215. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  216. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  217. package/src/runtime/framework/participation-manager.test.ts +0 -108
  218. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  219. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  220. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  221. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  222. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  223. package/src/runtime/framework/state/state-core.test.ts +0 -197
  224. package/src/runtime/game-sync-protocol.test.ts +0 -123
  225. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  226. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  227. package/src/runtime/observability/observability.test.ts +0 -583
  228. package/src/runtime/owner-control.test.ts +0 -153
  229. package/src/runtime/parent-process-watch.test.ts +0 -27
  230. package/src/runtime/pending-event-handoff.test.ts +0 -29
  231. package/src/runtime/raw-ws-log.test.ts +0 -102
  232. package/src/runtime/runtime-logger.test.ts +0 -58
  233. package/src/runtime/runtime-persistence.test.ts +0 -26
  234. package/src/runtime/runtime.test.ts +0 -1770
  235. package/src/runtime/ws-client.test.ts +0 -562
  236. package/src/sdk/action.test.ts +0 -8
  237. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  238. package/src/sdk/index.test.ts +0 -45
  239. package/src/sdk/module-input/index.test.ts +0 -49
  240. package/src/sdk/perception-plugin/index.test.ts +0 -22
  241. package/src/sdk/resource-metadata.test.ts +0 -40
  242. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  243. package/src/short-command/classifier.test.ts +0 -107
  244. package/src/short-command/presenter.test.ts +0 -119
  245. package/src/short-command/runner.test.ts +0 -78
  246. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  247. package/src/short-command/transport-response.test.ts +0 -39
  248. package/src/strategies/avoid-lone.ts +0 -32
  249. package/src/strategies/avoid-players.ts +0 -43
  250. package/src/strategies/corpse-patrol.ts +0 -50
  251. package/src/strategies/crab-sabotage.ts +0 -48
  252. package/src/strategies/custom-module.test.ts +0 -267
  253. package/src/strategies/find-player.ts +0 -49
  254. package/src/strategies/game-utils.test.ts +0 -305
  255. package/src/strategies/game-utils.ts +0 -927
  256. package/src/strategies/goals/anchor-linger.ts +0 -77
  257. package/src/strategies/goals/avoid-lone-top.ts +0 -189
  258. package/src/strategies/goals/avoid-players-top.test.ts +0 -95
  259. package/src/strategies/goals/avoid-players-top.ts +0 -122
  260. package/src/strategies/goals/conversation-goal.ts +0 -51
  261. package/src/strategies/goals/corpse-patrol-top.ts +0 -120
  262. package/src/strategies/goals/crab-octopus-reflexes.ts +0 -109
  263. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -131
  264. package/src/strategies/goals/crab-sabotage-top.ts +0 -139
  265. package/src/strategies/goals/emergency-hunt-goal.ts +0 -40
  266. package/src/strategies/goals/find-player-top.ts +0 -136
  267. package/src/strategies/goals/flee-players-goal.ts +0 -55
  268. package/src/strategies/goals/follow-companion-goal.ts +0 -130
  269. package/src/strategies/goals/goal-manager.ts +0 -41
  270. package/src/strategies/goals/goal-root-strategy.ts +0 -49
  271. package/src/strategies/goals/goal.ts +0 -28
  272. package/src/strategies/goals/hide-top.ts +0 -240
  273. package/src/strategies/goals/keep-away-goal.ts +0 -243
  274. package/src/strategies/goals/kill-frenzy-top.ts +0 -90
  275. package/src/strategies/goals/kill-lone-top.test.ts +0 -96
  276. package/src/strategies/goals/kill-lone-top.ts +0 -166
  277. package/src/strategies/goals/kill-target-goal.ts +0 -69
  278. package/src/strategies/goals/kill-target-top.test.ts +0 -65
  279. package/src/strategies/goals/kill-target-top.ts +0 -121
  280. package/src/strategies/goals/leaf-goal.ts +0 -27
  281. package/src/strategies/goals/linger-corpse-goal.ts +0 -43
  282. package/src/strategies/goals/lone-kill-core.ts +0 -86
  283. package/src/strategies/goals/lone-kill-goal.ts +0 -24
  284. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -84
  285. package/src/strategies/goals/lone-kill-task-top.ts +0 -133
  286. package/src/strategies/goals/move-room-goal.ts +0 -102
  287. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -112
  288. package/src/strategies/goals/normal-shrimp-top.ts +0 -248
  289. package/src/strategies/goals/paradise-fish-top.test.ts +0 -203
  290. package/src/strategies/goals/paradise-fish-top.ts +0 -234
  291. package/src/strategies/goals/patrol-top.ts +0 -68
  292. package/src/strategies/goals/report-patrol-top.ts +0 -97
  293. package/src/strategies/goals/safe-task-goal.ts +0 -130
  294. package/src/strategies/goals/social-task-top.ts +0 -192
  295. package/src/strategies/goals/task-kill-report-top.ts +0 -187
  296. package/src/strategies/goals/task-only-top.test.ts +0 -88
  297. package/src/strategies/goals/task-only-top.ts +0 -64
  298. package/src/strategies/goals/task-or-patrol-goal.ts +0 -59
  299. package/src/strategies/goals/task-report-top.ts +0 -57
  300. package/src/strategies/goals/wander-task-goal.ts +0 -33
  301. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -138
  302. package/src/strategies/goals/warrior-shrimp-top.ts +0 -293
  303. package/src/strategies/greeting.ts +0 -60
  304. package/src/strategies/hide.ts +0 -51
  305. package/src/strategies/kill-frenzy.ts +0 -32
  306. package/src/strategies/kill-lone.ts +0 -52
  307. package/src/strategies/kill-target.ts +0 -48
  308. package/src/strategies/lone-kill-task.ts +0 -48
  309. package/src/strategies/meeting-gate.test.ts +0 -59
  310. package/src/strategies/meeting-gate.ts +0 -28
  311. package/src/strategies/move-room.ts +0 -46
  312. package/src/strategies/official-long-behavior.test.ts +0 -89
  313. package/src/strategies/paradise-fish.ts +0 -70
  314. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  315. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  316. package/src/strategies/patrol.ts +0 -32
  317. package/src/strategies/player-targets.test.ts +0 -10
  318. package/src/strategies/player-targets.ts +0 -18
  319. package/src/strategies/report-patrol.ts +0 -32
  320. package/src/strategies/shrimp-memory.ts +0 -87
  321. package/src/strategies/social-task.ts +0 -67
  322. package/src/strategies/speech-module.ts +0 -123
  323. package/src/strategies/task-kill-report.ts +0 -49
  324. package/src/strategies/task-only.test.ts +0 -138
  325. package/src/strategies/task-only.ts +0 -34
  326. package/src/strategies/task-report.ts +0 -50
  327. package/src/strategies/types.ts +0 -116
  328. package/src/strategies/warrior-memory.ts +0 -54
  329. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/clawclaw-walkable.bin +0 -0
  330. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/distance-field.ts +0 -0
@@ -0,0 +1,852 @@
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 type { AuthProfile } from './auth.js';
14
+ import {
15
+ AgentWorkspaceClient,
16
+ downloadAgentWorkspaceFile,
17
+ type AgentWorkspaceConfigReader,
18
+ type AgentWorkspaceRemoteConfig,
19
+ type AgentWorkspaceRemoteFile,
20
+ type AgentWorkspaceRemoteItem,
21
+ } from './agent-workspace-client.js';
22
+ import type { ResourceType } from './hub-client.js';
23
+ import { unzip } from './hub-unzip.js';
24
+ import {
25
+ getUserDataAgentWorkspaceCurrentFile,
26
+ getUserDataAgentWorkspaceDir,
27
+ getUserDataAgentWorkspaceRevisionsDir,
28
+ getUserDataAccountDir,
29
+ getUserDataAccountHubBehaviorsDir,
30
+ getUserDataAccountHubPerceptionsDir,
31
+ getUserDataAccountHubPersonasDir,
32
+ getUserDataPersonaFile,
33
+ } from './user-data.js';
34
+
35
+ const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception'];
36
+ const SHA256 = /^[0-9a-f]{64}$/;
37
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
38
+
39
+ export interface LocalAgentWorkspaceFile {
40
+ relativePath: string;
41
+ path: string;
42
+ fileId: string;
43
+ sha256: string;
44
+ sizeBytes: number;
45
+ contentType: string;
46
+ }
47
+
48
+ export interface LocalAgentWorkspaceItem {
49
+ workspaceItemId: string;
50
+ resourceId: string;
51
+ versionId: string;
52
+ resourceType: ResourceType;
53
+ hub?: {
54
+ workspaceKind: 'owned' | 'installed';
55
+ publisher: 'official' | 'self' | 'community';
56
+ ownerId: string;
57
+ ownerName: string | null;
58
+ ownerAvatarUrl: string | null;
59
+ ownerIsOfficial: boolean;
60
+ };
61
+ contentDigest: string;
62
+ sourceFiles: LocalAgentWorkspaceFile[];
63
+ archiveFile?: Omit<LocalAgentWorkspaceFile, 'relativePath'>;
64
+ workingCopyPath?: string;
65
+ runtimeEntryPath?: string;
66
+ skillRootPath?: string;
67
+ knownVersions?: Array<{
68
+ versionId: string;
69
+ contentDigest: string;
70
+ sourceSha256: string;
71
+ }>;
72
+ resolution?: 'hub' | 'local_modified' | 'concurrent_difference' | 'known_online_old';
73
+ localContentDigest?: string;
74
+ localModifiedAtMs?: number;
75
+ }
76
+
77
+ export interface LocalAgentWorkspaceSnapshot {
78
+ metadataVersion?: 1;
79
+ layoutVersion?: 2;
80
+ revision: number;
81
+ syncedAt: string;
82
+ relativeDir: string;
83
+ items: Record<ResourceType, LocalAgentWorkspaceItem[]>;
84
+ }
85
+
86
+ interface CurrentPointer {
87
+ revision: number;
88
+ relative_dir: string;
89
+ }
90
+
91
+ export type AgentWorkspaceSyncStatus = 'updated' | 'unchanged' | 'local_overrides';
92
+
93
+ export interface AgentWorkspaceSyncResult {
94
+ status: AgentWorkspaceSyncStatus;
95
+ snapshot: LocalAgentWorkspaceSnapshot;
96
+ previous?: LocalAgentWorkspaceSnapshot;
97
+ }
98
+
99
+ export interface AgentWorkspaceSyncDependencies {
100
+ client?: AgentWorkspaceConfigReader;
101
+ download?: (url: string) => Promise<Buffer>;
102
+ now?: () => Date;
103
+ }
104
+
105
+ function record(value: unknown): Record<string, unknown> | null {
106
+ return value && typeof value === 'object' && !Array.isArray(value)
107
+ ? value as Record<string, unknown>
108
+ : null;
109
+ }
110
+
111
+ function safeSegment(value: string, field: string): string {
112
+ if (!SAFE_SEGMENT.test(value) || value === '.' || value === '..') {
113
+ throw new Error(`agent_workspace_${field}_invalid`);
114
+ }
115
+ return value;
116
+ }
117
+
118
+ function safeRelativePath(value: string): string {
119
+ if (
120
+ !value
121
+ || value.includes('\\')
122
+ || value.startsWith('/')
123
+ || value.split('/').some((segment) => !segment || segment === '.' || segment === '..')
124
+ ) throw new Error('agent_workspace_relative_path_invalid');
125
+ return value;
126
+ }
127
+
128
+ function pathInside(root: string, candidate: string): boolean {
129
+ const child = relative(resolve(root), resolve(candidate));
130
+ return child === '' || (!child.startsWith('..') && !isAbsolute(child));
131
+ }
132
+
133
+ function ensureInside(root: string, candidate: string): string {
134
+ if (!pathInside(root, candidate)) throw new Error('agent_workspace_path_escape');
135
+ return candidate;
136
+ }
137
+
138
+ function sha256(buffer: Buffer): string {
139
+ return createHash('sha256').update(buffer).digest('hex');
140
+ }
141
+
142
+ function validateRemoteFile(file: AgentWorkspaceRemoteFile, source: boolean): void {
143
+ if (!SAFE_SEGMENT.test(file.file_id) || !SHA256.test(file.sha256)) {
144
+ throw new Error('agent_workspace_file_metadata_invalid');
145
+ }
146
+ if (!Number.isSafeInteger(file.size_bytes) || file.size_bytes < 0 || file.size_bytes > 10 * 1024 * 1024) {
147
+ throw new Error('agent_workspace_file_size_invalid');
148
+ }
149
+ if (typeof file.url !== 'string' || typeof file.content_type !== 'string') {
150
+ throw new Error('agent_workspace_file_metadata_invalid');
151
+ }
152
+ if (source) safeRelativePath(file.relative_path ?? '');
153
+ }
154
+
155
+ function validateRemoteItem(item: AgentWorkspaceRemoteItem, expectedType: ResourceType): void {
156
+ if (item.resource_type !== expectedType) throw new Error('agent_workspace_resource_type_mismatch');
157
+ safeSegment(item.workspace_item_id, 'workspace_item_id');
158
+ safeSegment(item.resource_id, 'resource_id');
159
+ safeSegment(item.version_id, 'version_id');
160
+ if (
161
+ !['owned', 'installed'].includes(item.workspace_kind)
162
+ || typeof item.is_created_by_me !== 'boolean'
163
+ || !record(item.owner)
164
+ || typeof item.owner.id !== 'string'
165
+ || !SAFE_SEGMENT.test(item.owner.id)
166
+ || (item.owner.name !== null && typeof item.owner.name !== 'string')
167
+ || (item.owner.avatar_url !== null && typeof item.owner.avatar_url !== 'string')
168
+ || typeof item.owner.is_official !== 'boolean'
169
+ ) {
170
+ throw new Error('agent_workspace_owner_metadata_invalid');
171
+ }
172
+ if (!SHA256.test(item.content_digest) || !Array.isArray(item.source_files)) {
173
+ throw new Error('agent_workspace_item_invalid');
174
+ }
175
+ for (const file of item.source_files) validateRemoteFile(file, true);
176
+ if (expectedType === 'skill') {
177
+ if (!item.archive_file) throw new Error('agent_workspace_skill_archive_missing');
178
+ validateRemoteFile(item.archive_file, false);
179
+ } else if (item.archive_file !== undefined) {
180
+ throw new Error('agent_workspace_archive_unexpected');
181
+ }
182
+ if (expectedType !== 'skill' && item.source_files.length !== 1) {
183
+ throw new Error(`agent_workspace_${expectedType}_source_count_invalid`);
184
+ }
185
+ if (expectedType === 'strategy') {
186
+ const path = item.source_files[0]?.relative_path ?? '';
187
+ if (path.includes('/') || !['.ts', '.js'].includes(extname(path).toLowerCase())) {
188
+ throw new Error('agent_workspace_strategy_entry_invalid');
189
+ }
190
+ }
191
+ if (expectedType === 'persona') {
192
+ const path = item.source_files[0]?.relative_path ?? '';
193
+ if (path.includes('/') || extname(path).toLowerCase() !== '.md') {
194
+ throw new Error('agent_workspace_persona_entry_invalid');
195
+ }
196
+ }
197
+ if (expectedType === 'perception') {
198
+ const path = item.source_files[0]?.relative_path ?? '';
199
+ if (path.includes('/') || !['.ts', '.js'].includes(extname(path).toLowerCase())) {
200
+ throw new Error('agent_workspace_perception_entry_invalid');
201
+ }
202
+ }
203
+ }
204
+
205
+ function validateRemoteConfig(config: AgentWorkspaceRemoteConfig): void {
206
+ if (!Number.isSafeInteger(config.revision) || config.revision < 0 || !record(config.items)) {
207
+ throw new Error('agent_workspace_config_invalid');
208
+ }
209
+ for (const type of RESOURCE_TYPES) {
210
+ const items = config.items[type];
211
+ if (!Array.isArray(items)) throw new Error(`agent_workspace_${type}_items_invalid`);
212
+ for (const item of items) validateRemoteItem(item, type);
213
+ }
214
+ if (config.items.persona.length > 1) throw new Error('agent_workspace_persona_multiple');
215
+ }
216
+
217
+ function contentDigest(files: readonly LocalAgentWorkspaceFile[]): string {
218
+ const canonical = [...files]
219
+ .sort((left, right) => (
220
+ left.relativePath < right.relativePath ? -1 : left.relativePath > right.relativePath ? 1 : 0
221
+ ))
222
+ .map((file) => ({
223
+ relative_path: file.relativePath,
224
+ sha256: file.sha256,
225
+ size_bytes: file.sizeBytes,
226
+ }));
227
+ return createHash('sha256').update(JSON.stringify(canonical), 'utf8').digest('hex');
228
+ }
229
+
230
+ async function writeVerifiedFile(
231
+ root: string,
232
+ relativePath: string,
233
+ remote: AgentWorkspaceRemoteFile,
234
+ download: (url: string) => Promise<Buffer>,
235
+ ): Promise<LocalAgentWorkspaceFile> {
236
+ const bytes = await download(remote.url);
237
+ if (bytes.length !== remote.size_bytes) throw new Error('agent_workspace_file_size_mismatch');
238
+ if (sha256(bytes) !== remote.sha256) throw new Error('agent_workspace_file_hash_mismatch');
239
+ const target = ensureInside(root, join(root, ...safeRelativePath(relativePath).split('/')));
240
+ mkdirSync(dirname(target), { recursive: true });
241
+ writeFileSync(target, bytes);
242
+ return {
243
+ relativePath,
244
+ path: relative(root, target).replaceAll('\\', '/'),
245
+ fileId: remote.file_id,
246
+ sha256: remote.sha256,
247
+ sizeBytes: remote.size_bytes,
248
+ contentType: remote.content_type,
249
+ };
250
+ }
251
+
252
+ function skillRoot(packageRoot: string): string {
253
+ if (existsSync(join(packageRoot, 'SKILL.md'))) return packageRoot;
254
+ const directories = [...new Set(
255
+ unzipDirectories(packageRoot).filter((directory) => existsSync(join(directory, 'SKILL.md'))),
256
+ )];
257
+ if (directories.length !== 1) throw new Error('agent_workspace_skill_root_invalid');
258
+ return directories[0];
259
+ }
260
+
261
+ function unzipDirectories(root: string): string[] {
262
+ const results: string[] = [];
263
+ const visit = (directory: string): void => {
264
+ const entries = requireDirectoryEntries(directory);
265
+ for (const entry of entries) {
266
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
267
+ const child = join(directory, entry.name);
268
+ results.push(child);
269
+ visit(child);
270
+ }
271
+ };
272
+ visit(root);
273
+ return results;
274
+ }
275
+
276
+ function requireDirectoryEntries(directory: string) {
277
+ // Kept behind a helper so all recursive traversal stays rooted in the freshly extracted package.
278
+ return readdirSync(directory, { withFileTypes: true });
279
+ }
280
+
281
+ async function materializeItem(
282
+ stageRoot: string,
283
+ item: AgentWorkspaceRemoteItem,
284
+ download: (url: string) => Promise<Buffer>,
285
+ ): Promise<LocalAgentWorkspaceItem> {
286
+ const itemRoot = join(
287
+ stageRoot,
288
+ 'resources',
289
+ item.resource_type,
290
+ safeSegment(item.resource_id, 'resource_id'),
291
+ safeSegment(item.version_id, 'version_id'),
292
+ );
293
+ const sourceRoot = join(itemRoot, 'source');
294
+ mkdirSync(sourceRoot, { recursive: true });
295
+ const sourceFiles: LocalAgentWorkspaceFile[] = [];
296
+ for (const source of item.source_files) {
297
+ sourceFiles.push(await writeVerifiedFile(
298
+ sourceRoot,
299
+ source.relative_path!,
300
+ source,
301
+ download,
302
+ ));
303
+ }
304
+ if (contentDigest(sourceFiles) !== item.content_digest) {
305
+ throw new Error('agent_workspace_content_digest_mismatch');
306
+ }
307
+
308
+ let archiveFile: LocalAgentWorkspaceItem['archiveFile'];
309
+ let skillRootPath: string | undefined;
310
+ if (item.archive_file) {
311
+ const archive = await writeVerifiedFile(itemRoot, 'package.zip', item.archive_file, download);
312
+ archiveFile = {
313
+ path: relative(stageRoot, join(itemRoot, archive.path)).replaceAll('\\', '/'),
314
+ fileId: archive.fileId,
315
+ sha256: archive.sha256,
316
+ sizeBytes: archive.sizeBytes,
317
+ contentType: archive.contentType,
318
+ };
319
+ const packageRoot = join(itemRoot, 'package');
320
+ mkdirSync(packageRoot, { recursive: true });
321
+ for (const entry of unzip(readFileSync(join(itemRoot, 'package.zip')))) {
322
+ const relativePath = safeRelativePath(entry.path);
323
+ const target = ensureInside(packageRoot, join(packageRoot, ...relativePath.split('/')));
324
+ mkdirSync(dirname(target), { recursive: true });
325
+ writeFileSync(target, entry.content);
326
+ }
327
+ skillRootPath = relative(stageRoot, skillRoot(packageRoot)).replaceAll('\\', '/');
328
+ }
329
+
330
+ let runtimeEntryPath: string | undefined;
331
+ if (item.resource_type === 'strategy' || item.resource_type === 'perception' || item.resource_type === 'persona') {
332
+ const source = sourceFiles[0];
333
+ const extension = extname(source.relativePath).toLowerCase();
334
+ const runtimeDir = item.resource_type === 'strategy'
335
+ ? 'behaviors'
336
+ : item.resource_type === 'perception'
337
+ ? 'perceptions'
338
+ : 'personas';
339
+ const runtimePath = join(stageRoot, 'runtime', runtimeDir, `${item.resource_id}${extension}`);
340
+ mkdirSync(dirname(runtimePath), { recursive: true });
341
+ writeFileSync(runtimePath, readFileSync(join(sourceRoot, ...source.path.split('/'))));
342
+ runtimeEntryPath = relative(stageRoot, runtimePath).replaceAll('\\', '/');
343
+ }
344
+
345
+ return {
346
+ workspaceItemId: item.workspace_item_id,
347
+ resourceId: item.resource_id,
348
+ versionId: item.version_id,
349
+ resourceType: item.resource_type,
350
+ hub: {
351
+ workspaceKind: item.workspace_kind,
352
+ publisher: item.owner.is_official
353
+ ? 'official'
354
+ : item.is_created_by_me ? 'self' : 'community',
355
+ ownerId: item.owner.id,
356
+ ownerName: item.owner.name,
357
+ ownerAvatarUrl: item.owner.avatar_url,
358
+ ownerIsOfficial: item.owner.is_official,
359
+ },
360
+ contentDigest: item.content_digest,
361
+ sourceFiles: sourceFiles.map((file) => ({
362
+ ...file,
363
+ path: relative(stageRoot, join(sourceRoot, ...file.path.split('/'))).replaceAll('\\', '/'),
364
+ })),
365
+ ...(archiveFile ? { archiveFile } : {}),
366
+ ...(runtimeEntryPath ? { runtimeEntryPath } : {}),
367
+ ...(skillRootPath ? { skillRootPath } : {}),
368
+ };
369
+ }
370
+
371
+ function emptyItems(): Record<ResourceType, LocalAgentWorkspaceItem[]> {
372
+ return { skill: [], strategy: [], persona: [], perception: [] };
373
+ }
374
+
375
+ export function localAgentWorkspaceSnapshotRoot(
376
+ workspaceDir: string,
377
+ profile: Pick<AuthProfile, 'apiKey'>,
378
+ snapshot: LocalAgentWorkspaceSnapshot,
379
+ ): string {
380
+ return join(getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile), snapshot.relativeDir);
381
+ }
382
+
383
+ export function resolveLocalAgentWorkspacePath(
384
+ workspaceDir: string,
385
+ profile: Pick<AuthProfile, 'apiKey'>,
386
+ snapshot: LocalAgentWorkspaceSnapshot,
387
+ relativePath: string,
388
+ ): string {
389
+ const root = localAgentWorkspaceSnapshotRoot(workspaceDir, profile, snapshot);
390
+ return ensureInside(root, join(root, ...safeRelativePath(relativePath).split('/')));
391
+ }
392
+
393
+ interface LocalOverride {
394
+ bytes: Buffer;
395
+ sha256: string;
396
+ contentDigest: string;
397
+ modifiedAtMs: number;
398
+ }
399
+
400
+ interface WorkingCopyMetadata {
401
+ format: 1;
402
+ resourceType: 'strategy' | 'persona' | 'perception';
403
+ resourceId: string;
404
+ relativePath: string;
405
+ knownVersions: NonNullable<LocalAgentWorkspaceItem['knownVersions']>;
406
+ }
407
+
408
+ function singleFileContentDigest(relativePath: string, bytes: Buffer): string {
409
+ return createHash('sha256').update(JSON.stringify([{
410
+ relative_path: relativePath,
411
+ sha256: sha256(bytes),
412
+ size_bytes: bytes.length,
413
+ }]), 'utf8').digest('hex');
414
+ }
415
+
416
+ function knownVersions(item: LocalAgentWorkspaceItem): NonNullable<LocalAgentWorkspaceItem['knownVersions']> {
417
+ const entries = [
418
+ ...(item.knownVersions ?? []),
419
+ ...(item.sourceFiles[0] ? [{
420
+ versionId: item.versionId,
421
+ contentDigest: item.contentDigest,
422
+ sourceSha256: item.sourceFiles[0].sha256,
423
+ }] : []),
424
+ ];
425
+ return [...new Map(entries.map((entry) => [entry.versionId, entry])).values()];
426
+ }
427
+
428
+ function hubWorkingRoot(
429
+ workspaceDir: string,
430
+ profile: Pick<AuthProfile, 'apiKey'>,
431
+ type: 'strategy' | 'persona' | 'perception',
432
+ ): string {
433
+ if (type === 'strategy') return getUserDataAccountHubBehaviorsDir(workspaceDir, profile);
434
+ if (type === 'perception') return getUserDataAccountHubPerceptionsDir(workspaceDir, profile);
435
+ return getUserDataAccountHubPersonasDir(workspaceDir, profile);
436
+ }
437
+
438
+ function hubWorkingCopyPath(
439
+ workspaceDir: string,
440
+ profile: Pick<AuthProfile, 'apiKey'>,
441
+ type: 'strategy' | 'persona' | 'perception',
442
+ resourceId: string,
443
+ relativePath: string,
444
+ ): string {
445
+ const root = hubWorkingRoot(workspaceDir, profile, type);
446
+ return ensureInside(
447
+ root,
448
+ join(root, safeSegment(resourceId, 'resource_id'), ...safeRelativePath(relativePath).split('/')),
449
+ );
450
+ }
451
+
452
+ function accountRelativePath(
453
+ workspaceDir: string,
454
+ profile: Pick<AuthProfile, 'apiKey'>,
455
+ path: string,
456
+ ): string {
457
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
458
+ return relative(accountRoot, ensureInside(accountRoot, path)).replaceAll('\\', '/');
459
+ }
460
+
461
+ export function resolveLocalAgentWorkspaceWorkingCopyPath(
462
+ workspaceDir: string,
463
+ profile: Pick<AuthProfile, 'apiKey'>,
464
+ item: LocalAgentWorkspaceItem,
465
+ ): string | undefined {
466
+ if (!item.workingCopyPath) return undefined;
467
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
468
+ return ensureInside(
469
+ accountRoot,
470
+ join(accountRoot, ...safeRelativePath(item.workingCopyPath).split('/')),
471
+ );
472
+ }
473
+
474
+ function writeFileAtomically(path: string, bytes: Buffer): void {
475
+ mkdirSync(dirname(path), { recursive: true });
476
+ const temporary = `${path}.${randomUUID()}.tmp`;
477
+ writeFileSync(temporary, bytes);
478
+ renameSync(temporary, path);
479
+ }
480
+
481
+ function workingCopyMetadataPath(
482
+ workspaceDir: string,
483
+ profile: Pick<AuthProfile, 'apiKey'>,
484
+ type: 'strategy' | 'persona' | 'perception',
485
+ resourceId: string,
486
+ ): string {
487
+ return join(
488
+ getUserDataAgentWorkspaceDir(workspaceDir, profile),
489
+ 'working-copies',
490
+ type,
491
+ `${safeSegment(resourceId, 'resource_id')}.json`,
492
+ );
493
+ }
494
+
495
+ function readWorkingCopyMetadata(
496
+ path: string,
497
+ expected: Pick<WorkingCopyMetadata, 'resourceType' | 'resourceId' | 'relativePath'>,
498
+ ): WorkingCopyMetadata | undefined {
499
+ if (!existsSync(path)) return undefined;
500
+ try {
501
+ const value = JSON.parse(readFileSync(path, 'utf8')) as WorkingCopyMetadata;
502
+ if (
503
+ value.format !== 1
504
+ || value.resourceType !== expected.resourceType
505
+ || value.resourceId !== expected.resourceId
506
+ || value.relativePath !== expected.relativePath
507
+ || !Array.isArray(value.knownVersions)
508
+ || value.knownVersions.some((entry) => (
509
+ !entry
510
+ || typeof entry.versionId !== 'string'
511
+ || !SHA256.test(entry.contentDigest)
512
+ || !SHA256.test(entry.sourceSha256)
513
+ ))
514
+ ) return undefined;
515
+ return value;
516
+ } catch {
517
+ return undefined;
518
+ }
519
+ }
520
+
521
+ function inspectLocalSnapshot(
522
+ workspaceDir: string,
523
+ profile: Pick<AuthProfile, 'apiKey'>,
524
+ snapshot: LocalAgentWorkspaceSnapshot,
525
+ ): {
526
+ snapshot: LocalAgentWorkspaceSnapshot;
527
+ overrides: Map<string, LocalOverride>;
528
+ projectionOutdated: boolean;
529
+ workingMetadataMissing: boolean;
530
+ } {
531
+ const resolved = structuredClone(snapshot);
532
+ const overrides = new Map<string, LocalOverride>();
533
+ let projectionOutdated = false;
534
+ let workingMetadataMissing = false;
535
+ for (const type of ['strategy', 'persona', 'perception'] as const) {
536
+ for (const item of resolved.items[type]) {
537
+ const source = item.sourceFiles[0];
538
+ if (!source || !item.runtimeEntryPath) continue;
539
+ const projectionPath = resolveLocalAgentWorkspacePath(
540
+ workspaceDir,
541
+ profile,
542
+ resolved,
543
+ item.runtimeEntryPath,
544
+ );
545
+ let workingPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item);
546
+ if (!workingPath) {
547
+ workingPath = hubWorkingCopyPath(
548
+ workspaceDir,
549
+ profile,
550
+ type,
551
+ item.resourceId,
552
+ source.relativePath,
553
+ );
554
+ item.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath);
555
+ if (!existsSync(workingPath)) {
556
+ const legacyPath = type === 'persona' && existsSync(getUserDataPersonaFile(workspaceDir, profile))
557
+ ? getUserDataPersonaFile(workspaceDir, profile)
558
+ : projectionPath;
559
+ if (existsSync(legacyPath)) writeFileAtomically(workingPath, readFileSync(legacyPath));
560
+ }
561
+ }
562
+ if (!existsSync(workingPath)) {
563
+ item.resolution = 'hub';
564
+ projectionOutdated = true;
565
+ continue;
566
+ }
567
+ if (!existsSync(workingCopyMetadataPath(workspaceDir, profile, type, item.resourceId))) {
568
+ workingMetadataMissing = true;
569
+ }
570
+ const bytes = readFileSync(workingPath);
571
+ const localSha = sha256(bytes);
572
+ const projectionSha = existsSync(projectionPath)
573
+ ? sha256(readFileSync(projectionPath))
574
+ : undefined;
575
+ item.knownVersions = knownVersions(item);
576
+ if (localSha === source.sha256) {
577
+ item.resolution = 'hub';
578
+ if (projectionSha !== localSha) projectionOutdated = true;
579
+ delete item.localContentDigest;
580
+ delete item.localModifiedAtMs;
581
+ continue;
582
+ }
583
+ if (item.knownVersions.some((entry) => entry.sourceSha256 === localSha)) {
584
+ item.resolution = 'known_online_old';
585
+ const basePath = resolveLocalAgentWorkspacePath(
586
+ workspaceDir,
587
+ profile,
588
+ resolved,
589
+ source.path,
590
+ );
591
+ if (existsSync(basePath)) {
592
+ const baseBytes = readFileSync(basePath);
593
+ writeFileAtomically(workingPath, baseBytes);
594
+ if (projectionSha !== sha256(baseBytes)) projectionOutdated = true;
595
+ }
596
+ delete item.localContentDigest;
597
+ delete item.localModifiedAtMs;
598
+ continue;
599
+ }
600
+ const localDigest = singleFileContentDigest(source.relativePath, bytes);
601
+ const modifiedAtMs = statSync(workingPath).mtimeMs;
602
+ item.resolution = 'local_modified';
603
+ item.localContentDigest = localDigest;
604
+ item.localModifiedAtMs = modifiedAtMs;
605
+ if (projectionSha !== localSha) projectionOutdated = true;
606
+ overrides.set(`${type}:${item.resourceId}`, {
607
+ bytes,
608
+ sha256: localSha,
609
+ contentDigest: localDigest,
610
+ modifiedAtMs,
611
+ });
612
+ }
613
+ }
614
+ return { snapshot: resolved, overrides, projectionOutdated, workingMetadataMissing };
615
+ }
616
+
617
+ export function resolveLocalAgentWorkspaceSnapshot(
618
+ workspaceDir: string,
619
+ profile: Pick<AuthProfile, 'apiKey'>,
620
+ snapshot: LocalAgentWorkspaceSnapshot,
621
+ ): LocalAgentWorkspaceSnapshot {
622
+ return inspectLocalSnapshot(workspaceDir, profile, snapshot).snapshot;
623
+ }
624
+
625
+ export function readLocalAgentWorkspaceSnapshot(
626
+ workspaceDir: string,
627
+ profile: Pick<AuthProfile, 'apiKey'>,
628
+ ): LocalAgentWorkspaceSnapshot | undefined {
629
+ const pointerPath = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile);
630
+ if (!existsSync(pointerPath)) return undefined;
631
+ try {
632
+ const pointer = JSON.parse(readFileSync(pointerPath, 'utf8')) as CurrentPointer;
633
+ safeSegment(pointer.relative_dir, 'revision_dir');
634
+ const snapshotPath = join(
635
+ getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile),
636
+ pointer.relative_dir,
637
+ 'snapshot.json',
638
+ );
639
+ const snapshot = JSON.parse(readFileSync(snapshotPath, 'utf8')) as LocalAgentWorkspaceSnapshot;
640
+ if (snapshot.revision !== pointer.revision || snapshot.relativeDir !== pointer.relative_dir) return undefined;
641
+ return snapshot;
642
+ } catch {
643
+ return undefined;
644
+ }
645
+ }
646
+
647
+ function writeCurrentPointer(
648
+ workspaceDir: string,
649
+ profile: Pick<AuthProfile, 'apiKey'>,
650
+ pointer: CurrentPointer,
651
+ ): void {
652
+ const target = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile);
653
+ mkdirSync(dirname(target), { recursive: true });
654
+ const temporary = `${target}.${randomUUID()}.tmp`;
655
+ writeFileSync(temporary, `${JSON.stringify(pointer, null, 2)}\n`, 'utf8');
656
+ renameSync(temporary, target);
657
+ }
658
+
659
+ export async function syncAgentWorkspaceConfig(
660
+ workspaceDir: string,
661
+ profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
662
+ dependencies: AgentWorkspaceSyncDependencies = {},
663
+ ): Promise<AgentWorkspaceSyncResult> {
664
+ const previousRaw = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
665
+ const inspected = previousRaw
666
+ ? inspectLocalSnapshot(workspaceDir, profile, previousRaw)
667
+ : undefined;
668
+ const previous = inspected?.snapshot;
669
+ const client = dependencies.client ?? new AgentWorkspaceClient(profile);
670
+ const remote = await client.getConfig();
671
+ validateRemoteConfig(remote);
672
+ if (
673
+ previous?.revision === remote.revision
674
+ && previous.metadataVersion === 1
675
+ && previous.layoutVersion === 2
676
+ && inspected?.projectionOutdated !== true
677
+ && inspected?.workingMetadataMissing !== true
678
+ ) {
679
+ return {
680
+ status: inspected && inspected.overrides.size > 0 ? 'local_overrides' : 'unchanged',
681
+ snapshot: previous,
682
+ previous,
683
+ };
684
+ }
685
+
686
+ const revisionsDir = getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile);
687
+ mkdirSync(revisionsDir, { recursive: true });
688
+ const temporary = join(getUserDataAgentWorkspaceDir(workspaceDir, profile), `.staging-${randomUUID()}`);
689
+ mkdirSync(temporary, { recursive: true });
690
+ try {
691
+ const items = emptyItems();
692
+ const workingUpdates: Array<{ path: string; bytes: Buffer }> = [];
693
+ const workingMetadataUpdates: Array<{ path: string; value: WorkingCopyMetadata }> = [];
694
+ const previousByKey = new Map<ResourceType, Map<string, LocalAgentWorkspaceItem>>(
695
+ RESOURCE_TYPES.map((type) => [
696
+ type,
697
+ new Map((previous?.items[type] ?? []).map((item) => [item.resourceId, item])),
698
+ ]),
699
+ );
700
+ for (const type of RESOURCE_TYPES) {
701
+ for (const item of remote.items[type]) {
702
+ const materialized = await materializeItem(
703
+ temporary,
704
+ item,
705
+ dependencies.download ?? downloadAgentWorkspaceFile,
706
+ );
707
+ const prior = previousByKey.get(type)?.get(materialized.resourceId);
708
+ let workingPath: string | undefined;
709
+ let persistedWorkingMetadata: WorkingCopyMetadata | undefined;
710
+ if (type !== 'skill' && materialized.sourceFiles[0]) {
711
+ workingPath = hubWorkingCopyPath(
712
+ workspaceDir,
713
+ profile,
714
+ type,
715
+ materialized.resourceId,
716
+ materialized.sourceFiles[0].relativePath,
717
+ );
718
+ materialized.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath);
719
+ persistedWorkingMetadata = readWorkingCopyMetadata(
720
+ workingCopyMetadataPath(workspaceDir, profile, type, materialized.resourceId),
721
+ {
722
+ resourceType: type,
723
+ resourceId: materialized.resourceId,
724
+ relativePath: materialized.sourceFiles[0].relativePath,
725
+ },
726
+ );
727
+ }
728
+ materialized.knownVersions = [...new Map([
729
+ ...(prior ? knownVersions(prior) : []),
730
+ ...(persistedWorkingMetadata?.knownVersions ?? []),
731
+ ...knownVersions(materialized),
732
+ ].map((entry) => [entry.versionId, entry])).values()];
733
+ let override = inspected?.overrides.get(`${type}:${materialized.resourceId}`);
734
+ if (!override && !prior && workingPath && existsSync(workingPath)) {
735
+ const bytes = readFileSync(workingPath);
736
+ const localSha = sha256(bytes);
737
+ if (!persistedWorkingMetadata?.knownVersions.some((entry) => entry.sourceSha256 === localSha)) {
738
+ override = {
739
+ bytes,
740
+ sha256: localSha,
741
+ contentDigest: singleFileContentDigest(
742
+ materialized.sourceFiles[0]!.relativePath,
743
+ bytes,
744
+ ),
745
+ modifiedAtMs: statSync(workingPath).mtimeMs,
746
+ };
747
+ }
748
+ }
749
+ if (
750
+ !override
751
+ && !previous
752
+ && type === 'persona'
753
+ && existsSync(getUserDataPersonaFile(workspaceDir, profile))
754
+ && materialized.sourceFiles[0]
755
+ ) {
756
+ const personaBytes = readFileSync(getUserDataPersonaFile(workspaceDir, profile));
757
+ const personaSha = sha256(personaBytes);
758
+ if (personaBytes.toString('utf8').trim() && personaSha !== materialized.sourceFiles[0].sha256) {
759
+ override = {
760
+ bytes: personaBytes,
761
+ sha256: personaSha,
762
+ contentDigest: singleFileContentDigest(
763
+ materialized.sourceFiles[0].relativePath,
764
+ personaBytes,
765
+ ),
766
+ modifiedAtMs: statSync(getUserDataPersonaFile(workspaceDir, profile)).mtimeMs,
767
+ };
768
+ }
769
+ }
770
+ let effectiveBytes: Buffer | undefined;
771
+ if (
772
+ override
773
+ && materialized.runtimeEntryPath
774
+ && materialized.sourceFiles[0]?.sha256 !== override.sha256
775
+ ) {
776
+ const runtimePath = ensureInside(
777
+ temporary,
778
+ join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split('/')),
779
+ );
780
+ writeFileSync(runtimePath, override.bytes);
781
+ effectiveBytes = override.bytes;
782
+ const remoteAdvancedFromLocalBaseline = prior
783
+ ? prior.versionId !== materialized.versionId
784
+ : persistedWorkingMetadata !== undefined
785
+ && !persistedWorkingMetadata.knownVersions.some(
786
+ (entry) => entry.versionId === materialized.versionId,
787
+ );
788
+ materialized.resolution = remoteAdvancedFromLocalBaseline
789
+ ? 'concurrent_difference'
790
+ : 'local_modified';
791
+ materialized.localContentDigest = override.contentDigest;
792
+ materialized.localModifiedAtMs = override.modifiedAtMs;
793
+ } else {
794
+ materialized.resolution = 'hub';
795
+ if (materialized.runtimeEntryPath) {
796
+ effectiveBytes = readFileSync(ensureInside(
797
+ temporary,
798
+ join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split('/')),
799
+ ));
800
+ }
801
+ }
802
+ if (materialized.workingCopyPath && effectiveBytes) {
803
+ const accountRoot = getUserDataAccountDir(workspaceDir, profile);
804
+ workingUpdates.push({
805
+ path: ensureInside(
806
+ accountRoot,
807
+ join(accountRoot, ...safeRelativePath(materialized.workingCopyPath).split('/')),
808
+ ),
809
+ bytes: effectiveBytes,
810
+ });
811
+ workingMetadataUpdates.push({
812
+ path: workingCopyMetadataPath(
813
+ workspaceDir,
814
+ profile,
815
+ type as 'strategy' | 'persona' | 'perception',
816
+ materialized.resourceId,
817
+ ),
818
+ value: {
819
+ format: 1,
820
+ resourceType: type as 'strategy' | 'persona' | 'perception',
821
+ resourceId: materialized.resourceId,
822
+ relativePath: materialized.sourceFiles[0]!.relativePath,
823
+ knownVersions: materialized.knownVersions,
824
+ },
825
+ });
826
+ }
827
+ items[type].push(materialized);
828
+ }
829
+ }
830
+ const relativeDir = `revision-${remote.revision}-${randomUUID()}`;
831
+ const snapshot: LocalAgentWorkspaceSnapshot = {
832
+ metadataVersion: 1,
833
+ layoutVersion: 2,
834
+ revision: remote.revision,
835
+ syncedAt: (dependencies.now ?? (() => new Date()))().toISOString(),
836
+ relativeDir,
837
+ items,
838
+ };
839
+ writeFileSync(join(temporary, 'snapshot.json'), `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
840
+ for (const update of workingUpdates) writeFileAtomically(update.path, update.bytes);
841
+ for (const update of workingMetadataUpdates) {
842
+ writeFileAtomically(update.path, Buffer.from(`${JSON.stringify(update.value, null, 2)}\n`, 'utf8'));
843
+ }
844
+ const target = join(revisionsDir, relativeDir);
845
+ renameSync(temporary, target);
846
+ writeCurrentPointer(workspaceDir, profile, { revision: remote.revision, relative_dir: relativeDir });
847
+ return { status: 'updated', snapshot, ...(previous ? { previous } : {}) };
848
+ } catch (error) {
849
+ rmSync(temporary, { recursive: true, force: true });
850
+ throw error;
851
+ }
852
+ }