@h1r-ai/croche-react-native 0.6.0 → 0.7.0

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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -5,17 +5,27 @@ import Darwin
5
5
  import Glibc
6
6
  #endif
7
7
 
8
- /// The 0.6 storage primitives (ARCHITECTURE §2a): opaque UTF-8 values under Core-chosen keys.
9
- /// Core owns names, framing and retention; this keeps bytes durable and nothing else.
10
- /// Key encoding is reversible: two hex components, so a 200-byte key fits 255-byte names.
8
+ /// Default StateStore, lifetime locks, and the separate file secret transport.
9
+ /// Core owns the keys and the instance scopes used for deletion.
11
10
  final class PlatformStorage: @unchecked Sendable {
12
11
  private let root: URL
12
+ private let state: PlatformStateStore
13
13
  private let guarded = NSLock()
14
+ /// Tests stop a child after real fsync, before publication; unset in ordinary use.
15
+ var beforeReplace: (() -> Void)?
16
+ var beforeStateCommit: (() throws -> Void)? {
17
+ get { state.beforeCommit }
18
+ set { state.beforeCommit = newValue }
19
+ }
14
20
  /// Held lock files by lock name. flock is per open file: another handle (or process) on the
15
21
  /// same directory contends even inside this process.
16
22
  private var held: [String: Int32] = [:]
17
23
 
18
- init(directory: URL) { root = directory.appendingPathComponent("kv-v1", isDirectory: true) }
24
+ init(directory: URL) {
25
+ let root = directory.appendingPathComponent("kv-v1", isDirectory: true)
26
+ self.root = root
27
+ state = PlatformStateStore(path: root.appendingPathComponent("state.db"))
28
+ }
19
29
 
20
30
  /// Core's portable key grammar; anything else is a Core bug and never reaches the disk.
21
31
  static func valid(_ key: String) -> Bool {
@@ -46,7 +56,7 @@ final class PlatformStorage: @unchecked Sendable {
46
56
  return key
47
57
  }
48
58
 
49
- func read(_ area: String, _ key: String) throws -> String? {
59
+ func readRaw(_ area: String, _ key: String) throws -> String? {
50
60
  let file = try path(area, key, suffix: ".value")
51
61
  do { return String(decoding: try Data(contentsOf: file), as: UTF8.self) }
52
62
  catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil }
@@ -55,7 +65,7 @@ final class PlatformStorage: @unchecked Sendable {
55
65
 
56
66
  /// Atomic replace, durable on return: temp file, fsync, rename, then the directory's fsync.
57
67
  /// A crash leaves the old value or the new one, never a mix.
58
- func write(_ area: String, _ key: String, _ value: String) throws {
68
+ func writeRaw(_ area: String, _ key: String, _ value: String) throws {
59
69
  let file = try path(area, key, suffix: ".value"), dir = file.deletingLastPathComponent()
60
70
  try ensure(dir)
61
71
  let temp = dir.appendingPathComponent(file.lastPathComponent + ".tmp-" + UUID().uuidString)
@@ -70,6 +80,7 @@ final class PlatformStorage: @unchecked Sendable {
70
80
  }
71
81
  ok = ok && fsync(fd) == 0
72
82
  close(fd)
83
+ if ok { beforeReplace?() }
73
84
  guard ok, rename(temp.path, file.path) == 0 else {
74
85
  unlink(temp.path)
75
86
  throw LegacyCrocheError("storage_error", "Storage write failed.")
@@ -78,14 +89,14 @@ final class PlatformStorage: @unchecked Sendable {
78
89
  }
79
90
 
80
91
  /// Real deletion; absent is not an error.
81
- func remove(_ area: String, _ key: String) throws {
92
+ func removeRaw(_ area: String, _ key: String) throws {
82
93
  let file = try path(area, key, suffix: ".value")
83
94
  if unlink(file.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Storage remove failed.") }
84
95
  if FileManager.default.fileExists(atPath: file.deletingLastPathComponent().path) { try sync(file.deletingLastPathComponent()) }
85
96
  }
86
97
 
87
98
  /// All and only the keys starting with `prefix`, in any order. Temporary files are not keys.
88
- func list(_ area: String, _ prefix: String) throws -> [String] {
99
+ func listRaw(_ area: String, _ prefix: String) throws -> [String] {
89
100
  let base = root.appendingPathComponent(area, isDirectory: true), files = FileManager.default
90
101
  guard let heads = try? files.contentsOfDirectory(atPath: base.path) else { return [] }
91
102
  var keys: [String] = []
@@ -123,6 +134,51 @@ final class PlatformStorage: @unchecked Sendable {
123
134
  flock(fd, LOCK_UN); close(fd)
124
135
  }
125
136
 
137
+ func read(_ area: String, _ key: String) throws -> String? {
138
+ _ = try logicalStorageKey(key)
139
+ return area == "state" ? try state.get(key).value : try readRaw(area, key)
140
+ }
141
+ func write(_ area: String, _ key: String, _ value: String) throws {
142
+ _ = try logicalStorageKey(key)
143
+ if area == "state" { try state.write(key, value) } else { try writeRaw(area, key, value) }
144
+ }
145
+ func remove(_ area: String, _ key: String) throws {
146
+ _ = try logicalStorageKey(key)
147
+ if area == "state" { try state.remove(key) } else { try removeRaw(area, key) }
148
+ }
149
+ func list(_ area: String, _ prefix: String) throws -> [String] {
150
+ _ = try logicalStorageKey(prefix)
151
+ guard area == "state" else { return try listRaw(area, prefix) }
152
+ var keys: [String] = []
153
+ var options = StateListOptions()
154
+ repeat {
155
+ let page = try state.list(prefix, options)
156
+ keys.append(contentsOf: page.entries.map(\.key))
157
+ options.cursor = page.nextCursor
158
+ } while options.cursor != nil
159
+ return keys
160
+ }
161
+ func readVersioned(_ key: String) throws -> VersionedValue {
162
+ try state.get(versionedStorageKey(key))
163
+ }
164
+ func writeIf(_ key: String, _ value: String?, _ expect: String?) throws -> WriteOutcome {
165
+ try state.writeIf(versionedStorageKey(key), value, expect)
166
+ }
167
+ func commitState(_ ops: [StateOp], _ condition: StateCondition) throws -> StateCommitResult {
168
+ try state.commit(ops, condition)
169
+ }
170
+ func listState(_ prefix: String, _ options: StateListOptions) throws -> StatePage {
171
+ try state.list(prefix, options)
172
+ }
173
+
174
+ func instancePurgePlan(_ area: String, _ prefix: String) throws -> InstancePayloadPlan {
175
+ let filePlan = try planInstancePayloads(root, area: area, prefix: prefix, sync: { try self.sync($0) })
176
+ guard area == "state" else { return filePlan }
177
+ return InstancePayloadPlan(eraseTemps: filePlan.eraseTemps, durable: filePlan.durable, eraseValues: {
178
+ try filePlan.eraseValues()
179
+ try self.state.purge(prefix)
180
+ })
181
+ }
126
182
  private func ensure(_ dir: URL) throws {
127
183
  do { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) }
128
184
  catch { throw LegacyCrocheError("storage_error", "Storage directory failed.") }
@@ -143,6 +199,7 @@ private let posixWrite = Glibc.write
143
199
 
144
200
  /// Where secrets live: apart from state, never through `read` or `list`.
145
201
  protocol PlatformSecrets: Sendable {
202
+ func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan
146
203
  func read(_ key: String) throws -> String?
147
204
  func write(_ key: String, _ value: String) throws
148
205
  func remove(_ key: String) throws
@@ -151,6 +208,7 @@ protocol PlatformSecrets: Sendable {
151
208
  /// Files in their own area: hosts without a Keychain, and Croche's own tests.
152
209
  struct FileSecrets: PlatformSecrets {
153
210
  let storage: PlatformStorage
211
+ func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan { try storage.instancePurgePlan("secrets", prefix) }
154
212
  func read(_ key: String) throws -> String? { try storage.read("secrets", key) }
155
213
  func write(_ key: String, _ value: String) throws { try storage.write("secrets", key, value) }
156
214
  func remove(_ key: String) throws { try storage.remove("secrets", key) }
@@ -163,6 +221,34 @@ import Security
163
221
  /// this device only (never in a backup or on another device).
164
222
  struct KeychainSecrets: PlatformSecrets {
165
223
  var service = "ai.croche.pal"
224
+ // Instance-local seams keep erasure sensitivity tests out of the real Keychain.
225
+ var deleteItem: @Sendable ([String: Any]) -> OSStatus = { SecItemDelete($0 as CFDictionary) }
226
+ var updateItem: @Sendable ([String: Any], [String: Any]) -> OSStatus = { SecItemUpdate($0 as CFDictionary, $1 as CFDictionary) }
227
+ // Attribute-only query seam; tests supply accounts without touching the real Keychain.
228
+ var listAccounts: @Sendable (String) throws -> [String] = { service in
229
+ let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
230
+ kSecReturnAttributes as String: true, kSecMatchLimit as String: kSecMatchLimitAll]
231
+ var result: CFTypeRef?
232
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
233
+ if status == errSecItemNotFound { return [] }
234
+ guard status == errSecSuccess, let items = result as? [[String: Any]] else {
235
+ throw LegacyCrocheError("storage_error", "Keychain enumeration failed.")
236
+ }
237
+ return try items.map { item in
238
+ guard let account = item[kSecAttrAccount as String] as? String else {
239
+ throw LegacyCrocheError("storage_error", "Invalid Keychain account.")
240
+ }
241
+ return account
242
+ }
243
+ }
244
+ func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan {
245
+ guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
246
+ throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
247
+ }
248
+ let keys = try listAccounts(service).filter { $0.hasPrefix(prefix) }
249
+ guard keys.allSatisfy(PlatformStorage.valid) else { throw LegacyCrocheError("storage_error", "Invalid Keychain account.") }
250
+ return InstancePayloadPlan(eraseTemps: {}, durable: {}, eraseValues: { for key in keys { try self.remove(key) } })
251
+ }
166
252
  private func query(_ key: String) -> [String: Any] {
167
253
  [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key]
168
254
  }
@@ -178,7 +264,7 @@ struct KeychainSecrets: PlatformSecrets {
178
264
  }
179
265
  func write(_ key: String, _ value: String) throws {
180
266
  let data = Data(value.utf8)
181
- let update = SecItemUpdate(query(key) as CFDictionary, [kSecValueData as String: data] as CFDictionary)
267
+ let update = updateItem(query(key), [kSecValueData as String: data])
182
268
  if update == errSecSuccess { return }
183
269
  guard update == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(update)).") }
184
270
  var add = query(key)
@@ -188,7 +274,7 @@ struct KeychainSecrets: PlatformSecrets {
188
274
  guard status == errSecSuccess else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(status)).") }
189
275
  }
190
276
  func remove(_ key: String) throws {
191
- let status = SecItemDelete(query(key) as CFDictionary)
277
+ let status = deleteItem(query(key))
192
278
  guard status == errSecSuccess || status == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain delete failed (\(status)).") }
193
279
  }
194
280
  }
@@ -1,385 +1,6 @@
1
1
  import Foundation
2
2
 
3
- /// Opens a declared agent's main store, or one of its instances. `config` is an app-supplied
4
- /// patch, the final layer over the definition's applied configuration; it needs an `instance`
5
- /// and is never stored, so pass it on every open. `handlers` run the tools a patch adds.
6
- struct LegacyAgentOptions: Sendable {
7
- var instance: String?
8
- var config: JSON?
9
- var handlers: [String: ToolHandler]
10
- init(instance: String? = nil, config: JSON? = nil, handlers: [String: ToolHandler] = [:]) {
11
- self.instance = instance; self.config = config; self.handlers = handlers
12
- }
13
- /// Handler callbacks never enter JSON: Core receives their names for its census.
14
- var json: JSON {
15
- var value: [String: JSON] = [:]
16
- if let instance { value["instance"] = .string(instance) }
17
- if let config { value["config"] = config }
18
- if config != nil || !handlers.isEmpty { value["handlers"] = .array(handlers.keys.sorted().map(JSON.string)) }
19
- return .object(value)
20
- }
21
- }
22
-
23
- /// One of a declared agent's instances for this project's user.
24
- struct InstanceInfo: Sendable, Equatable {
25
- /// Core's `[{instance}]`. A malformed listing fails typed (`core_error`); a key is never read as "".
26
- static func listing(_ text: String) throws -> [InstanceInfo] {
27
- guard let list = try JSON(text).array else { throw LegacyCrocheError("core_error", "Core's instance listing is not a list.") }
28
- return try list.map { InstanceInfo(instance: try required($0, "instance", "instance listing")) }
29
- }
30
- let instance: String
31
- init(instance: String) { self.instance = instance }
32
- }
33
-
34
- /// What `deleteData` deletes for this project's user: with no fields, the declared main stores and
35
- /// every registered instance; with `agent`, that agent's; with `agent` and `instance`, that instance.
36
- struct DeleteDataOptions: Sendable {
37
- var agent: String?
38
- var instance: String?
39
- init(agent: String? = nil, instance: String? = nil) { self.agent = agent; self.instance = instance }
40
- var json: JSON {
41
- var value: [String: JSON] = [:]
42
- if let agent { value["agent"] = .string(agent) }
43
- if let instance { value["instance"] = .string(instance) }
44
- return .object(value)
45
- }
46
- }
47
-
48
- /// A required string in a Core reply. A missing one is a Core bug, so it fails, never as "".
49
- private func required(_ value: JSON, _ key: String, _ what: String) throws -> String {
50
- guard let text = value[key].string else { throw LegacyCrocheError("core_error", "Core's \(what) has no \(key).") }
51
- return text
52
- }
53
-
54
- /// The local resolved view: the full resolved app configuration (an AgentConfig), never host or
55
- /// user fields. Revision values are opaque: compare them for equality only; the effective and
56
- /// patch revisions are meaningful within the same Core version.
57
- struct EffectiveAgentConfig: Sendable, Equatable {
58
- /// The resolved AgentConfig.
59
- let config: JSON
60
- /// Opaque identity of the full resolved app configuration, before host or user fields.
61
- let effectiveRevision: String
62
- /// Opaque identity of the selected bundled or released project snapshot.
63
- let revisionId: String
64
- /// Opaque identity of this instance's config patch; nil without a patch.
65
- let patchRevision: String?
66
- init(config: JSON, effectiveRevision: String, revisionId: String, patchRevision: String?) {
67
- self.config = config; self.effectiveRevision = effectiveRevision; self.revisionId = revisionId; self.patchRevision = patchRevision
68
- }
69
- }
70
-
71
- /// Known agent error codes; other Core and host codes reach `CrocheError.code` verbatim.
72
- enum CrocheErrorCode {
73
- /// The instance is open with another config patch.
74
- static let agentConflict = "agent_conflict"
75
- static let invalidConfiguration = "invalid_configuration"
76
- }
77
-
78
- typealias ProjectToolContext = LegacyToolContext
79
- typealias ProjectUsageEvent = JSON
80
- typealias RuntimeDebugEvent = JSON
3
+ // Retained namespaces for the shared fake-port stream and truncate utilities.
4
+ enum LegacyCrocheAgent {}
5
+ enum LegacyCroche {}
81
6
  typealias MemoryChangedEvent = JSON
82
-
83
- /// The project-returned agent uses the existing Runtime's port, subscriptions and memory.
84
- final class LegacyCrocheAgent: Sendable {
85
- private let core: CoreRuntime
86
- private let runtime: AgentEngine
87
- private let lifetime = ProjectAgentLifetime()
88
- private let hub: StreamHub
89
- var engine: AgentEngine { runtime }
90
- let id: String
91
- let instance: String?
92
- let created: Bool
93
- let logId: String
94
- init(core: CoreRuntime, runtime: AgentEngine, hub: StreamHub) {
95
- self.hub = hub
96
- self.core = core; self.runtime = runtime
97
- id = core.agentId(); instance = core.instance(); created = core.created(); logId = runtime.logId
98
- }
99
- var name: String? { core.name() }
100
- var mode: String? { core.mode() }
101
- var visibleTools: [String]? { core.visibleTools() }
102
- func effectiveConfig() throws -> EffectiveAgentConfig {
103
- let core = self.core
104
- let value: JSON
105
- do { value = try JSON(core.effectiveConfig()) } catch { throw LegacyCrocheError(error) }
106
- guard value["config"].object != nil else { throw LegacyCrocheError("core_error", "Core's effective config has no config.") }
107
- return EffectiveAgentConfig(config: value["config"], effectiveRevision: try required(value, "effectiveRevision", "effective config"),
108
- revisionId: try required(value, "revisionId", "effective config"), patchRevision: value["patchRevision"].string)
109
- }
110
- /// Closed by `close()`, by the project, or by Core (`deleteData` closes the agents in its scope).
111
- var closed: Bool { lifetime.closed || core.isClosed() }
112
- var memory: CrocheMemory { runtime.memory }
113
- private func check() throws { if closed { throw LegacyCrocheError("closed", "The agent is closed.") } }
114
- func setTools(_ visible: [String]?) async throws {
115
- try check(); let core = self.core
116
- _ = try await Offload.run { try core.setTools(visible: visible); return true }
117
- }
118
- func setMode(_ mode: String?) async throws {
119
- try check(); let core = self.core
120
- _ = try await Offload.run { try core.setMode(mode: mode); return true }
121
- }
122
- /// Core's config sync, for Croche's own tests. Not public: Core refreshes before any money
123
- /// refusal, so an app never syncs by hand (APP-API: sync() removed).
124
- func sync() async throws { try check(); _ = try await runtime.sync() }
125
- /// SDK shorthand only; Core generates the id and validates the request.
126
- func send(_ text: String, _ options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
127
- try await send(SendInput(input: [.text(text, kind: .user)]), options)
128
- }
129
- func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
130
- try check(); return try await runtime.send(input, options: options)
131
- }
132
- func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> LegacyRequestResult {
133
- try check()
134
- let result = try await runtime.request(input, options: SendOptions(responseFormat: options.responseFormat), wait: options.wait)
135
- try? await runtime.refreshMemory()
136
- return result
137
- }
138
- func subscribe(_ options: LegacySubscribeOptions) -> Subscription { hub.subscribe(options) }
139
- func cancel(_ id: String? = nil) async throws {
140
- try check()
141
- if let id { try await runtime.cancel(id) }
142
- else {
143
- let core = self.core
144
- _ = try await Offload.run { core.cancelTurn(); return true }
145
- }
146
- }
147
- func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
148
- func close() async throws {
149
- let task = lifetime.close { try await self.runtime.close() }
150
- try await task.value
151
- }
152
- }
153
-
154
- private final class ProjectAgentLifetime: @unchecked Sendable {
155
- private let lock = NSLock()
156
- private var closing: Task<Void, Error>?
157
- var closed: Bool { lock.withLock { closing != nil } }
158
- func close(_ body: @escaping @Sendable () async throws -> Void) -> Task<Void, Error> {
159
- lock.withLock {
160
- if let closing { return closing }
161
- let task = Task { try await body() }; closing = task; return task
162
- }
163
- }
164
- }
165
-
166
- // Internal host construction, shared by platform-owned storage and host tests.
167
- struct NativeProjectOptions: Sendable {
168
- var host: JSON
169
- var bundledConfig: JSON
170
- var user: String?
171
- var language: String?
172
- var handlers: [String: ToolHandler] = [:]
173
- var streaming = true
174
- var backgroundSync = true
175
- var maintenanceIntervalMs = 60_000.0
176
- var storage: @Sendable (String) -> any RuntimeStorage
177
- var secretStorage: @Sendable (String) -> any RuntimeSecretStore
178
- var attestor: (any RuntimeAttestor)?
179
- var fetch: RuntimeHTTP?
180
- var timeZone: TimeZone?
181
- var records: @Sendable () -> ProjectRecordFiles
182
- var onUsage: (@Sendable (JSON) -> Void)?
183
- var onDebugEvent: (@Sendable (JSON) -> Void)?
184
- }
185
-
186
- final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
187
- private let lock = NSLock()
188
- private var hosts: [String: SwiftHost] = [:]
189
- private var all: [SwiftHost] = []
190
- /// The in-flight open's own handlers and its definition id (nil: the default agent). The
191
- /// session serializes opens, so at most one table is staged.
192
- private var staged: (id: String?, handlers: [String: ToolHandler])?
193
- let options: NativeProjectOptions
194
- init(_ options: NativeProjectOptions) { self.options = options }
195
- func pal(agent: String) -> any HostPal {
196
- let options = self.options
197
- let slot = NativeProjectSlot.storageLabel(agent)
198
- // An open's own handlers bind by definition id while it is in flight (the session serializes opens).
199
- let id = NativeProjectSlot.isMaintenance(agent) ? nil : ((try? JSON(agent).array?.first?.string) ?? agent)
200
- let own = lock.withLock { () -> [String: ToolHandler] in
201
- guard let id, let staged, staged.id == nil || staged.id == id else { return [:] }
202
- return staged.handlers
203
- }
204
- let handlers = tools(own)
205
- // A fresh host for every request: record and default-agent PALs are separate.
206
- let host = SwiftHost(storage: options.storage(slot), secrets: options.secretStorage(slot),
207
- attestor: options.attestor, http: options.fetch, tools: handlers,
208
- background: options.backgroundSync, projectRecords: options.records())
209
- host.timeZone = options.timeZone
210
- lock.withLock { if !NativeProjectSlot.isMaintenance(agent) { hosts[agent] = host }; all.append(host) }
211
- return host
212
- }
213
- func stage(_ id: String?, _ handlers: [String: ToolHandler]) { lock.withLock { staged = (id, handlers) } }
214
- func unstage() { lock.withLock { staged = nil } }
215
- /// The project's handlers plus an instance's own (Core refuses a shadowing name), with the
216
- /// project tool context.
217
- private func tools(_ own: [String: ToolHandler]) -> [String: ToolHandler] {
218
- let options = self.options
219
- return options.handlers.merging(own) { _, child in child }.mapValues { handler -> ToolHandler in
220
- { invocation, context in
221
- var data = context.data.object ?? [:]
222
- let issued = data.removeValue(forKey: "userId")?.string
223
- data["user"] = options.user.map(JSON.string) ?? .null
224
- data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
225
- // The throw goes to Core as it is (APP-API: the tool_failed remap is Core's); the
226
- // host's own "nothing ran" rule (handlerError) still applies on the way out.
227
- return try await handler(invocation, LegacyToolContext(data: .object(data), cancellation: context.cancellation, images: context.images))
228
- }
229
- }
230
- }
231
- /// Latest successful open wins: that instance slot's future invocations use these handlers.
232
- func rebind(_ slot: String, _ own: [String: ToolHandler]) throws { try host(slot).replaceTools(tools(own)) }
233
- func host(_ slot: String) throws -> SwiftHost {
234
- try lock.withLock {
235
- guard let host = hosts[slot] else { throw LegacyCrocheError("core_error", "Core opened an agent without requesting its host.") }
236
- return host
237
- }
238
- }
239
- func stop() {
240
- let stopped = lock.withLock { () -> [SwiftHost] in
241
- defer { all.removeAll(); hosts.removeAll() }; return all
242
- }
243
- for host in stopped { host.stop(); host.session.close() }
244
- }
245
- }
246
-
247
- /// Core owns configuration selection, agent census, instances, locks and project identity.
248
- final class LegacyCroche: Sendable {
249
- private let core: CoreProject
250
- private let pals: NativeProjectPals
251
- private let session: NativeProjectSession
252
- private init(core: CoreProject, pals: NativeProjectPals) {
253
- self.core = core; self.pals = pals; session = NativeProjectSession(core: core, pals: pals)
254
- }
255
- var user: String? { core.user() }
256
- var installationId: String? { core.installationId() }
257
- var crocheUserId: String? { core.crocheUserId() }
258
- var agentIds: [String] { core.agentIds() }
259
- var applied: JSON { (try? JSON(core.applied())) ?? .null }
260
- static func open(_ options: LegacyOpenOptions) async throws -> LegacyCroche {
261
- let native = try await Offload.run { try options.native() }
262
- return try await open(native)
263
- }
264
- static func open(_ options: NativeProjectOptions) async throws -> LegacyCroche {
265
- AgentEngine.warnIfReleaseBuildCarriesDebugKey(options.host)
266
- let pals = NativeProjectPals(options)
267
- let context = ProjectObserverContext(user: options.user)
268
- var host = options.host
269
- if let attestor = options.attestor { host["attestationPlatform"] = .string(attestor.platform) }
270
- let wire = ProjectOpenOptions(host: try projectText(host), user: options.user,
271
- bundledConfig: try projectText(options.bundledConfig), handlers: Array(options.handlers.keys), language: options.language,
272
- streaming: options.streaming, backgroundSync: options.backgroundSync,
273
- maintenanceIntervalMs: options.maintenanceIntervalMs)
274
- do {
275
- let core = try await Offload.run {
276
- try CoreProject.open(pals: pals, options: wire, onUsage: options.onUsage.map { listener in EventHook { listener(context.usage($0)) } },
277
- onDebug: options.onDebugEvent.map(EventHook.init))
278
- }
279
- context.attach(core)
280
- return LegacyCroche(core: core, pals: pals)
281
- } catch { pals.stop(); throw error }
282
- }
283
- func agent(_ id: String? = nil, _ options: LegacyAgentOptions = LegacyAgentOptions()) async throws -> LegacyCrocheAgent {
284
- try await session.agent(id, options)
285
- }
286
- /// This user's instances of a declared agent, sorted by key.
287
- func listInstances(_ id: String) async throws -> [InstanceInfo] {
288
- let core = self.core
289
- let text = try await Offload.run { try core.listInstances(agentId: id) }
290
- return try InstanceInfo.listing(text)
291
- }
292
- /// Deletes this user's stores on this device. Core first closes this project's open agents in
293
- /// scope; a store open elsewhere fails `store_busy` and nothing is deleted.
294
- func deleteData(_ options: DeleteDataOptions = DeleteDataOptions()) async throws {
295
- try await session.deleteData(options)
296
- }
297
- func close() async throws { try await session.close() }
298
- }
299
-
300
- private actor NativeProjectSession {
301
- private let core: CoreProject
302
- private let pals: NativeProjectPals
303
- private var agents: [String: LegacyCrocheAgent] = [:]
304
- private var closing: Task<Void, Error>?
305
- private var admission: Task<Void, Never>?
306
- init(core: CoreProject, pals: NativeProjectPals) { self.core = core; self.pals = pals }
307
- func agent(_ id: String? = nil, _ options: LegacyAgentOptions = LegacyAgentOptions()) async throws -> LegacyCrocheAgent {
308
- try await admit { try await self.openAgent(id, options: options) }
309
- }
310
- func deleteData(_ options: DeleteDataOptions) async throws {
311
- guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
312
- let core = self.core, text = try projectText(options.json)
313
- var failure: Error?
314
- do { _ = try await Offload.run { try core.deleteData(options: text); return true } } catch { failure = error }
315
- // Core owns the scope and the close decision, including closes before a failed deletion.
316
- await evictClosed()
317
- if let failure { throw failure }
318
- }
319
- /// Ends and forgets the wrappers whose runtime Core closed, so a later open gets a new one.
320
- private func evictClosed() async {
321
- for (slot, agent) in agents where agent.closed { agents[slot] = nil; try? await agent.close() }
322
- }
323
- private func admit(_ open: @escaping @Sendable () async throws -> LegacyCrocheAgent) async throws -> LegacyCrocheAgent {
324
- guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
325
- let previous = admission
326
- let task = Task { await previous?.value; return try await open() }
327
- admission = Task { _ = try? await task.value }
328
- return try await task.value
329
- }
330
- private func openAgent(_ id: String?, options: LegacyAgentOptions) async throws -> LegacyCrocheAgent {
331
- guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
332
- let core = self.core, pals = self.pals, text = try projectText(options.json)
333
- await evictClosed()
334
- // Opens are serialized, so the staged table is this open's.
335
- let patched = options.config != nil
336
- if patched { pals.stage(id, options.handlers) }
337
- defer { if patched { pals.unstage() } }
338
- // Cached calls still go to Core, which checks admission and the patch's identity.
339
- let handle = try await Offload.run { try core.agentWithOptions(id: id, options: text) }
340
- return try await attach(handle, handlers: patched ? options.handlers : nil)
341
- }
342
- /// `handlers`: a patched open Core admitted, so its handlers replace that slot's (latest wins).
343
- private func attach(_ handle: CoreRuntime, handlers: [String: ToolHandler]? = nil) async throws -> LegacyCrocheAgent {
344
- guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
345
- let slot = try handle.instance().map { try projectText(.array([.string(handle.agentId()), .string($0)])) } ?? handle.agentId()
346
- if let handlers { try pals.rebind(slot, handlers) }
347
- if let existing = agents[slot], !existing.closed { return existing }
348
- let runtime = try await AgentEngine.adopt(core: handle, host: pals.host(slot))
349
- let agent = LegacyCrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
350
- if closing != nil { try await agent.close(); throw LegacyCrocheError("closed", "The project is closed.") }
351
- agents[slot] = agent
352
- return agent
353
- }
354
- func close() async throws {
355
- if let closing { return try await closing.value }
356
- let core = self.core, pals = self.pals
357
- let task = Task {
358
- _ = try await Offload.run { core.close(); return true }
359
- for agent in self.agents.values { try await agent.close() }
360
- pals.stop()
361
- }
362
- closing = task
363
- try await task.value
364
- }
365
- }
366
- private func projectText(_ value: JSON) throws -> String {
367
- let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
368
- do { return String(decoding: try encoder.encode(value), as: UTF8.self) }
369
- catch { throw LegacyCrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
370
- }
371
-
372
- private final class ProjectObserverContext: @unchecked Sendable {
373
- private let lock = NSLock()
374
- private weak var core: CoreProject?
375
- private let user: String?
376
- init(user: String?) { self.user = user }
377
- func attach(_ core: CoreProject) { lock.withLock { self.core = core } }
378
- func usage(_ event: JSON) -> JSON {
379
- let core = lock.withLock { self.core }
380
- var value = event
381
- value["user"] = (core?.user() ?? user).map(JSON.string) ?? .null
382
- value["crocheUserId"] = core?.crocheUserId().map(JSON.string) ?? .null
383
- return value
384
- }
385
- }