peachsim 0.1.2591 → 0.1.2592

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 (139) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +3872 -3531
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +2 -2
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-EMX4WZ72.mjs → acorn-67PU73QE.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-UYJXLDCG.mjs → chunk-5FTHILIE.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-JHXDM3YU.mjs → chunk-6DB5FR7S.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-EGKH2L6J.mjs → chunk-CF3MTPMY.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MC6NMYWY.mjs → chunk-D4LYKRRB.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-QBMFX3J2.mjs → chunk-DFF5XZ5M.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-Q4NA6PUR.mjs → chunk-EHRSWFTD.mjs} +3 -3
  33. package/dist-lib/esm-chunks/{chunk-4QHHRGO4.mjs → chunk-EITX573K.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-J676B57D.mjs → chunk-EWHA6X3Z.mjs} +5 -5
  35. package/dist-lib/esm-chunks/{chunk-AKKHSVJ4.mjs → chunk-FYXXFYML.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-ILWFGZWW.mjs → chunk-GQ3EO2UV.mjs} +107 -6
  37. package/dist-lib/esm-chunks/{chunk-VD27WNCT.mjs → chunk-GY6TE4B4.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-NX23AMX4.mjs → chunk-KDI5YYQ6.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-VYZ5DC3M.mjs → chunk-L5T3HBPO.mjs} +792 -514
  40. package/dist-lib/esm-chunks/{chunk-7627LKJK.mjs → chunk-M4QLI2SY.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-UIVXVMS5.mjs → chunk-PITO2NI2.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-SOAYP72T.mjs → chunk-QSFWBVUO.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-TFG4LZ5T.mjs → chunk-R3WTQB5J.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-ZL5N6ENT.mjs → chunk-RV4ACE6R.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-YR6DNV76.mjs → chunk-SW4PSSTF.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-VF5WVB3D.mjs → chunk-TJZPNFVF.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-VRVXRZI4.mjs → chunk-XSQH4R5E.mjs} +48 -15
  48. package/dist-lib/esm-chunks/{chunk-RKQZGWX2.mjs → chunk-XZ3FX3HW.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-ANKZARNW.mjs → metro-layout-parser-EX65MARK.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-4N5CXBOZ.mjs → swift-package-prebuilt-3BPDQVA7.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-5IUSRXYA.mjs → swift-sdk-app-module-CRX6E3TR.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-7T2LMQS5.mjs → swift-sdk-image-EJD5TPQH.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-7QJ3BF6E.mjs → swift-sdk-image-producer-QAZOSLTZ.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +3243 -2905
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +5669 -4904
  59. package/dist-lib/host/fetch-proxy-handler.cjs +310 -298
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +238 -223
  73. package/dist-lib/native-app-identity-project.mjs +17 -17
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +73 -71
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +6291 -5526
  93. package/dist-lib/swift-compile.cjs +1051 -696
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +12 -6
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/dist-types/packages/peach-engine/src/engine/native-node-queries.d.ts +1 -0
  126. package/package.json +1 -1
  127. package/runtime-companion.json +1 -1
  128. package/src/native-bundles.ts +2 -0
  129. package/src/one-native-controls-package.ts +141 -31
  130. package/src/one-sdk/source.ts +2 -1
  131. package/src/oneSdkContract.ts +13 -2
  132. package/src/swift-compile.ts +301 -48
  133. package/src/swift-host.ts +88 -16
  134. package/src/swift-reproducible.ts +16 -2
  135. package/src/swift-root-lock.ts +77 -5
  136. package/src/swift-sdk-image.ts +53 -10
  137. package/src/swift-startup-split.ts +65 -27
  138. package/src/swift-toolchain.ts +16 -5
  139. package/src/wasm-lazy-split.ts +46 -40
@@ -1,5 +1,19 @@
1
- import { realpathSync } from 'node:fs'
1
+ import { existsSync, realpathSync } from 'node:fs'
2
2
  import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ function canonicalHomeDir(): string {
6
+ const home = os.homedir()
7
+ // agent profiles set HOME to a subdirectory whose ~/.peach symlinks into the
8
+ // host user's real home; map the enclosing real home so shared llbuild slots
9
+ // emit identical -file-prefix-map flags across sessions.
10
+ const dotPeach = path.join(home, '.peach')
11
+ if (existsSync(dotPeach)) {
12
+ const realHome = path.dirname(realpathSync(dotPeach))
13
+ if (home === realHome || home.startsWith(`${realHome}${path.sep}`)) return realHome
14
+ }
15
+ return home
16
+ }
3
17
 
4
18
  // a wasm names its inputs by the paths they compiled from, so its bytes would
5
19
  // depend on the host user, cache directory and checkout path. every build maps
@@ -9,7 +23,7 @@ import os from 'node:os'
9
23
  export function swiftReproducibleBuildFlags(
10
24
  roots: readonly (readonly [root: string, name: string])[],
11
25
  ): string[] {
12
- return [[os.homedir(), 'home'] as const, ...roots]
26
+ return [[canonicalHomeDir(), 'home'] as const, ...roots]
13
27
  .flatMap(([root, name]) =>
14
28
  [...new Set([root, realpathSync(root)])].map((from) => `${from}=/peach/${name}`),
15
29
  )
@@ -235,6 +235,82 @@ export function swiftRootLocksDir(): string {
235
235
  * a waiter names what it waits on once per holder on stderr. locks share one
236
236
  * user directory across Peach homes: the shared build tree has one writer
237
237
  * even with isolated app state. */
238
+ export interface SwiftRootReadHold {
239
+ release(): void
240
+ }
241
+
242
+ function lockDirectoryFor(root: string): string {
243
+ const directory = path.join(
244
+ swiftRootLocksDir(),
245
+ createHash('sha256').update(rootLockKey(root)).digest('hex').slice(0, 32),
246
+ )
247
+ mkdirSync(directory, { recursive: true })
248
+ return directory
249
+ }
250
+
251
+ // records a live shared reader on `root` while the caller holds its exclusive
252
+ // lock, so writers wait or choose another slot instead of evicting products
253
+ // another build is compiling or linking against.
254
+ export function acquireSwiftRootReadHold(root: string): SwiftRootReadHold {
255
+ const directory = lockDirectoryFor(root)
256
+ const token = randomUUID()
257
+ const pending = path.join(directory, `pending.reader.${token}`)
258
+ const reader = path.join(directory, `reader.${token}`)
259
+ writeFileSync(pending, JSON.stringify(ownIdentity(process.pid)))
260
+ try {
261
+ linkSync(pending, reader)
262
+ } finally {
263
+ rmSync(pending, { force: true })
264
+ }
265
+ let released = false
266
+ return {
267
+ release() {
268
+ if (released) return
269
+ released = true
270
+ rmSync(reader, { force: true })
271
+ },
272
+ }
273
+ }
274
+
275
+ export async function hasLiveSwiftRootReaders(
276
+ root: string,
277
+ signal?: AbortSignal,
278
+ ): Promise<boolean> {
279
+ const directory = lockDirectoryFor(root)
280
+ const entries = readdirSync(directory).filter((entry) => entry.startsWith('reader.'))
281
+ if (entries.length === 0) return false
282
+ for (const entry of entries) {
283
+ const file = path.join(directory, entry)
284
+ let text: string
285
+ try {
286
+ text = readFileSync(file, 'utf8')
287
+ } catch (error) {
288
+ if (errorCode(error) === 'ENOENT') continue
289
+ throw error
290
+ }
291
+ const identity = parseIdentity(text)
292
+ const rows = await processTableWithRetry(identity.pid, signal)
293
+ if (rows.some((row) => !row.zombie && sameProcess(row, identity))) return true
294
+ rmSync(file, { force: true })
295
+ }
296
+ return false
297
+ }
298
+
299
+ export async function waitForNoSwiftRootReaders(
300
+ root: string,
301
+ signal?: AbortSignal,
302
+ ): Promise<void> {
303
+ let announced = false
304
+ while (await hasLiveSwiftRootReaders(root, signal)) {
305
+ signal?.throwIfAborted()
306
+ if (!announced) {
307
+ announced = true
308
+ process.stderr.write(`[swift-root-lock] waiting for readers of ${root}\n`)
309
+ }
310
+ await pause(POLL_MS, signal)
311
+ }
312
+ }
313
+
238
314
  export async function withSwiftRootLock<T>(
239
315
  root: string,
240
316
  work: (lease: SwiftRootLease) => Promise<T>,
@@ -254,11 +330,7 @@ export async function withSwiftRootLock<T>(
254
330
  signal?: AbortSignal,
255
331
  wait = true,
256
332
  ): Promise<T | undefined> {
257
- const directory = path.join(
258
- swiftRootLocksDir(),
259
- createHash('sha256').update(rootLockKey(root)).digest('hex').slice(0, 32),
260
- )
261
- mkdirSync(directory, { recursive: true })
333
+ const directory = lockDirectoryFor(root)
262
334
  const token = randomUUID()
263
335
  const ownRow = (await processTableWithRetry(process.pid, signal)).find(
264
336
  (candidate) => candidate.pid === process.pid && !candidate.zombie,
@@ -7,6 +7,7 @@ import {
7
7
  readFileSync,
8
8
  renameSync,
9
9
  rmSync,
10
+ statSync,
10
11
  writeFileSync,
11
12
  } from 'node:fs'
12
13
  import path from 'node:path'
@@ -217,24 +218,56 @@ export function swiftSdkImageEntry(key: string, scopedLookups: boolean) {
217
218
  }
218
219
  }
219
220
 
221
+ // bounded in-memory caches avoid reparsing 70+ MB sdk json across repeated builds in one process.
222
+ const MAX_CACHED_SDK_IMAGES = 4
223
+ const cachedSdkInterfaces = new Map<string, SwiftSdkInterface>()
224
+ const cachedSdkManifestIndices = new Map<string, SwiftSdkManifest>()
225
+ const cachedSdkManifests = new Map<
226
+ string,
227
+ {
228
+ manifest: SwiftSdkManifest
229
+ block: (name: SwiftSdkManifestBlock) => Uint32Array
230
+ segments: Array<SwiftSdkManifest['segments'][number] & { data: Uint8Array }>
231
+ }
232
+ >()
233
+
234
+ function setBoundedCache<T>(cache: Map<string, T>, key: string, value: T): T {
235
+ cache.delete(key)
236
+ cache.set(key, value)
237
+ while (cache.size > MAX_CACHED_SDK_IMAGES) {
238
+ const oldest = cache.keys().next().value
239
+ if (oldest !== undefined) cache.delete(oldest)
240
+ }
241
+ return value
242
+ }
243
+
220
244
  function cached(directory: string, key: string): SwiftSdkImage | undefined {
221
- const sdkInterface = path.join(directory, INTERFACE_FILE)
245
+ const sdkInterfacePath = path.join(directory, INTERFACE_FILE)
222
246
  const image = path.join(directory, IMAGE_FILE)
223
247
  const address = path.join(directory, IMAGE_DIGEST)
224
248
  if (
225
249
  !existsSync(image) ||
226
250
  !existsSync(address) ||
227
- !existsSync(sdkInterface) ||
251
+ !existsSync(sdkInterfacePath) ||
228
252
  !existsSync(path.join(directory, MANIFEST_FILE)) ||
229
253
  !existsSync(path.join(directory, MANIFEST_DATA_FILE))
230
254
  )
231
255
  return undefined
256
+ const sha256 = readFileSync(address, 'utf8')
257
+ const cacheKey = `${directory}\0${sha256}`
258
+ let loadedInterface: SwiftSdkInterface | undefined
232
259
  return {
233
260
  key,
234
261
  directory,
235
262
  image,
236
- sha256: readFileSync(address, 'utf8'),
237
- sdkInterface: JSON.parse(readFileSync(sdkInterface, 'utf8')),
263
+ sha256,
264
+ get sdkInterface(): SwiftSdkInterface {
265
+ if (loadedInterface) return loadedInterface
266
+ const memo = cachedSdkInterfaces.get(cacheKey)
267
+ if (memo) return (loadedInterface = memo)
268
+ const parsed: SwiftSdkInterface = JSON.parse(readFileSync(sdkInterfacePath, 'utf8'))
269
+ return (loadedInterface = setBoundedCache(cachedSdkInterfaces, cacheKey, parsed))
270
+ },
238
271
  }
239
272
  }
240
273
 
@@ -903,18 +936,28 @@ function writeSdkManifest(
903
936
  export function readSwiftSdkManifestIndex(
904
937
  image: Pick<SwiftSdkImage, 'directory'>,
905
938
  ): SwiftSdkManifest {
906
- const manifest: SwiftSdkManifest = JSON.parse(
907
- readFileSync(path.join(image.directory, MANIFEST_FILE), 'utf8'),
908
- )
939
+ const manifestPath = path.join(image.directory, MANIFEST_FILE)
940
+ const stat = statSync(manifestPath, { bigint: true })
941
+ const cacheKey = `${manifestPath}\0${stat.size}:${stat.mtimeNs}`
942
+ const memo = cachedSdkManifestIndices.get(cacheKey)
943
+ if (memo) return memo
944
+ const manifest: SwiftSdkManifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
909
945
  if (manifest.version !== SWIFT_SDK_IMAGE_VERSION)
910
946
  throw new Error(`sdk manifest version ${manifest.version}`)
911
- return manifest
947
+ return setBoundedCache(cachedSdkManifestIndices, cacheKey, manifest)
912
948
  }
913
949
 
914
950
  /** the manifest of a built sdk image, its u32 blocks and the shipped segments' bytes. */
915
951
  export function readSwiftSdkManifest(image: Pick<SwiftSdkImage, 'directory'>) {
952
+ const manifestPath = path.join(image.directory, MANIFEST_FILE)
953
+ const dataPath = path.join(image.directory, MANIFEST_DATA_FILE)
954
+ const mStat = statSync(manifestPath, { bigint: true })
955
+ const dStat = statSync(dataPath, { bigint: true })
956
+ const cacheKey = `${image.directory}\0${mStat.size}:${mStat.mtimeNs}\0${dStat.size}:${dStat.mtimeNs}`
957
+ const memo = cachedSdkManifests.get(cacheKey)
958
+ if (memo) return memo
916
959
  const manifest = readSwiftSdkManifestIndex(image)
917
- const data = readFileSync(path.join(image.directory, MANIFEST_DATA_FILE))
960
+ const data = readFileSync(dataPath)
918
961
  const words = new Uint32Array(data.buffer, data.byteOffset, manifest.segmentBytes / 4)
919
962
  const blocks = new Map<SwiftSdkManifestBlock, Uint32Array>()
920
963
  let at = 0
@@ -928,7 +971,7 @@ export function readSwiftSdkManifest(image: Pick<SwiftSdkImage, 'directory'>) {
928
971
  ...segment,
929
972
  data: data.subarray(segment.bytes, segment.bytes + segment.length),
930
973
  }))
931
- return { manifest, block, segments }
974
+ return setBoundedCache(cachedSdkManifests, cacheKey, { manifest, block, segments })
932
975
  }
933
976
 
934
977
  const MANIFEST_BLOCKS: readonly string[] = [
@@ -34,13 +34,13 @@ import { SWIFT_HMR_PATH, SWIFT_PACKAGE_PATH } from './swift-submit'
34
34
  import { swiftCacheDir } from './swift-toolchain'
35
35
  import {
36
36
  instrumentNativeWasm,
37
- mergeNativeWasmProfiles,
38
37
  sealNativeWasmSplit,
39
38
  splitNativeWasm,
40
39
  } from './wasm-lazy-split'
41
40
  import {
42
41
  makeWasmFunctionNamesSingleLine,
43
42
  readWasmCustomSection,
43
+ readWasmFunctionCount,
44
44
  readWasmMemory,
45
45
  } from './wasm-narrow-boundary'
46
46
  import { installWasmOpt } from './wasm-optimize'
@@ -181,6 +181,27 @@ export async function splitSwiftApp(
181
181
  )
182
182
  }
183
183
 
184
+ // canonicalize binaryen wasm-split profiles (8-byte module hash + u32 slots) to a
185
+ // presence bitset (0 or 1 per function) and union them in memory without spawning
186
+ // wasm-split --merge-profiles. identical hot sets always share one cache hash even
187
+ // when execution timestamps differ.
188
+ function mergeProfileBitsets(files: readonly Buffer[]): Buffer {
189
+ const first = files[0]
190
+ if (!first || first.length < 8 || (first.length - 8) % 4 !== 0)
191
+ throw new Error('invalid native startup profile buffer')
192
+ const merged = Buffer.allocUnsafe(first.length)
193
+ first.copy(merged, 0, 0, 8)
194
+ merged.fill(0, 8)
195
+ const header = first.subarray(0, 8)
196
+ for (const file of files) {
197
+ if (file.length !== first.length || !file.subarray(0, 8).equals(header))
198
+ throw new Error('native startup profiles do not match the same sdk image')
199
+ for (let offset = 8; offset < file.length; offset += 4)
200
+ if (file.readUInt32LE(offset) !== 0) merged.writeUInt32LE(1, offset)
201
+ }
202
+ return merged
203
+ }
204
+
184
205
  /**
185
206
  * splits a shared sdk image by the merged startup of every app profiled on it: each app's
186
207
  * profile stays beside the image, and a new app's profile widens the startup file.
@@ -195,34 +216,40 @@ export async function splitSwiftSdkImage(
195
216
  const prefix = `${app}-`
196
217
  const own = join(profiles, `${prefix}${launch.artifactHash}.profile`)
197
218
  const names = () =>
198
- readdirSync(profiles)
199
- .filter((name) => !name.startsWith('.') && name.endsWith('.profile'))
200
- .sort()
219
+ existsSync(profiles)
220
+ ? readdirSync(profiles)
221
+ .filter((name) => !name.startsWith('.') && name.endsWith('.profile'))
222
+ .sort()
223
+ : []
201
224
  const union = () => {
202
- const files = names().map((name) => readFileSync(join(profiles, name)))
203
- const hash = createHash('sha256')
204
- for (const file of files) hash.update(file)
225
+ const merged = mergeProfileBitsets(
226
+ names().map((name) => readFileSync(join(profiles, name))),
227
+ )
205
228
  const cache = join(
206
229
  directory,
207
- `startup-v11-${platform}-${hash.digest('hex').slice(0, 16)}`,
230
+ `startup-v11-${platform}-${digest(merged).slice(0, 16)}`,
208
231
  )
209
- return { files, cache }
232
+ return { merged, cache }
210
233
  }
234
+ // an existing profile for this normalized app on the same sdk image already covers its
235
+ // startup paths; any newly called sdk function loads lazily on demand.
211
236
  const current = () =>
212
- withSwiftRootLock(profiles, async () => (existsSync(own) ? union() : undefined))
237
+ withSwiftRootLock(profiles, async () =>
238
+ names().some((name) => name.startsWith(prefix)) ? union() : undefined,
239
+ )
213
240
  const available = await current()
214
241
  if (available) {
215
242
  const ready = readSwiftStartupImage(available.cache)
216
243
  if (ready) return ready
217
244
  }
218
245
  return withStartupWork(bytes, async (work) => {
219
- const { files, cache } =
246
+ const { merged, cache } =
220
247
  available ??
221
- (await withSwiftRootLock(own, async () => {
248
+ (await withSwiftRootLock(join(profiles, `${prefix}record`), async () => {
222
249
  const alreadyRecorded = await current()
223
250
  if (alreadyRecorded) return alreadyRecorded
224
251
  const recorded = join(work.directory, 'app.profile')
225
- await profileStartup(work, launch, 'sdkUrl', recorded)
252
+ await profileStartup(work, launch, 'sdkUrl', recorded, directory)
226
253
  return withSwiftRootLock(profiles, async () => {
227
254
  mkdirSync(profiles, { recursive: true })
228
255
  const pending = join(profiles, `.${prefix}${launch.artifactHash}.profile`)
@@ -238,15 +265,10 @@ export async function splitSwiftSdkImage(
238
265
  return withSwiftRootLock(cache, async () => {
239
266
  const existing = readSwiftStartupImage(cache)
240
267
  if (existing) return existing
241
- const inputs = files.map((file, index) => {
242
- const input = join(work.directory, `input-${index}.profile`)
243
- writeFileSync(input, file)
244
- return input
245
- })
246
- const merged = join(work.directory, 'merged.profile')
247
- await mergeNativeWasmProfiles(work.binaryen, inputs, merged)
268
+ const mergedPath = join(work.directory, 'merged.profile')
269
+ writeFileSync(mergedPath, merged)
248
270
  // an app outside the profiled set misses sdk code, so a miss loads a small part
249
- return storeStartupSplit(work, merged, directory, cache, 1 << 18)
271
+ return storeStartupSplit(work, mergedPath, directory, cache, 1 << 18)
250
272
  })
251
273
  })
252
274
  }
@@ -280,13 +302,29 @@ async function profileStartup(
280
302
  launch: SwiftStartupLaunch,
281
303
  role: 'url' | 'sdkUrl',
282
304
  output: string,
305
+ sharedDirectory?: string,
283
306
  ) {
284
- const instrumented = join(work.directory, 'instrumented.wasm')
285
- const functionCount = await instrumentNativeWasm(
286
- work.original,
287
- instrumented,
288
- work.binaryen,
289
- )
307
+ let instrumented = join(work.directory, 'instrumented.wasm')
308
+ let functionCount: number
309
+ if (sharedDirectory) {
310
+ const cachedInstrumented = join(sharedDirectory, `instrumented-v1-${platform}.wasm`)
311
+ if (!existsSync(cachedInstrumented)) {
312
+ await withSwiftRootLock(cachedInstrumented, async () => {
313
+ if (existsSync(cachedInstrumented)) return
314
+ const pending = join(sharedDirectory, `.instrumented-${process.pid}.wasm`)
315
+ try {
316
+ await instrumentNativeWasm(work.original, pending, work.binaryen)
317
+ renameSync(pending, cachedInstrumented)
318
+ } finally {
319
+ rmSync(pending, { force: true })
320
+ }
321
+ })
322
+ }
323
+ instrumented = cachedInstrumented
324
+ functionCount = readWasmFunctionCount(work.bytes)
325
+ } else {
326
+ functionCount = await instrumentNativeWasm(work.original, instrumented, work.binaryen)
327
+ }
290
328
  writeFileSync(
291
329
  output,
292
330
  await bootSwiftPreview(launch, { instrumented, functionCount, role }),
@@ -490,7 +490,8 @@ export function swiftToolchainBin(release: string): string {
490
490
  const dirs = [os.homedir(), '/'].map((base) =>
491
491
  path.join(base, `Library/Developer/Toolchains/${release}.xctoolchain/usr/bin`),
492
492
  )
493
- return dirs.find((dir) => fs.existsSync(path.join(dir, 'swift'))) ?? dirs[0]!
493
+ const found = dirs.find((dir) => fs.existsSync(path.join(dir, 'swift')))
494
+ return found ? fs.realpathSync(found) : dirs[0]!
494
495
  }
495
496
  if (process.env.CONTRAST_SWIFT_TOOLCHAINS) {
496
497
  return path.join(process.env.CONTRAST_SWIFT_TOOLCHAINS, release, 'usr/bin')
@@ -557,7 +558,11 @@ exec ${JSON.stringify(path.join(toolchainBin, 'wasm-ld'))} "$@"
557
558
  // home-paths.ts's rnxHomeDir, repeated because this file imports node builtins only.
558
559
  export function peachHome(): string {
559
560
  const override = process.env.PEACH_HOME
560
- return override ? path.resolve(override) : path.join(os.homedir(), '.peach')
561
+ if (override) return path.resolve(override)
562
+ const home = path.join(os.homedir(), '.peach')
563
+ // agent profiles symlink ~/.peach to the host user's ~/.peach; canonicalize so
564
+ // swift-sdk-views hashes and llbuild plans match across sessions on one host.
565
+ return fs.existsSync(home) ? fs.realpathSync(home) : home
561
566
  }
562
567
 
563
568
  /** where the pinned wasm SDK installs unless PEACH_SWIFT_SDKS_PATH names another. */
@@ -625,11 +630,17 @@ function buildersRootEnv(): string | null {
625
630
  return root ? root : null
626
631
  }
627
632
 
633
+ // mac agent sessions without an explicit private PEACH_HOME share the machine's
634
+ // resolved builders cache rather than cold-rebuilding SDK images on internal disk.
635
+ function resolvedBuildersRoot(): string | null {
636
+ return buildersRootEnv() ?? (process.env.PEACH_HOME ? null : agentSharedCacheRoot())
637
+ }
638
+
628
639
  // machine-wide swift scratch and package caches, shared across lanes. keep
629
640
  // their implementation with the compiler so daemon edits cannot cold-split
630
641
  // the twin warm trees. the complete implementation remains a hashed input.
631
642
  export function swiftCacheDir(): string {
632
- const root = buildersRootEnv()
643
+ const root = resolvedBuildersRoot()
633
644
  return root ? path.join(root, 'peach-cache') : path.join(peachHome(), 'cache')
634
645
  }
635
646
 
@@ -647,7 +658,7 @@ export function refreshSwiftCacheHold(directory: string): void {
647
658
  const [kind, key] = relative.split(path.sep)
648
659
  if (!key || kind === '..' || path.isAbsolute(relative)) return
649
660
  const entry = path.join(cacheRoot, kind, key)
650
- if (!buildersRootEnv()) {
661
+ if (!resolvedBuildersRoot()) {
651
662
  const now = new Date()
652
663
  fs.utimesSync(entry, now, now)
653
664
  return
@@ -665,7 +676,7 @@ export function refreshSwiftCacheHold(directory: string): void {
665
676
  }
666
677
 
667
678
  export function hasSwiftCacheHold(directory: string): boolean {
668
- if (!buildersRootEnv()) return false
679
+ if (!resolvedBuildersRoot()) return false
669
680
  const marker = fs.lstatSync(path.join(directory, SWIFT_CACHE_HOLD_MARKER), {
670
681
  throwIfNoEntry: false,
671
682
  })
@@ -117,19 +117,6 @@ export async function instrumentNativeWasm(
117
117
  return count
118
118
  }
119
119
 
120
- export async function mergeNativeWasmProfiles(
121
- binaryen: string,
122
- profiles: readonly string[],
123
- output: string,
124
- ): Promise<void> {
125
- await run(join(dirname(binaryen), 'wasm-split'), [
126
- '--merge-profiles',
127
- ...profiles,
128
- '-o',
129
- output,
130
- ])
131
- }
132
-
133
120
  // split after lowering and profile collection, before either image's table guard.
134
121
  export async function splitNativeWasm(
135
122
  input: string,
@@ -168,33 +155,52 @@ export async function splitNativeWasm(
168
155
  const source = join(directory, 'source.wasm')
169
156
  writeFileSync(source, prepared)
170
157
  const named = keepNames || !!placement
171
- const symbols = await run(binaryen, [source, ...features, '--print-function-map'], {
172
- maxBuffer: Infinity,
173
- })
174
- const startup = await run(splitter, [...features, '--print-profile', profile, input], {
175
- maxBuffer: Infinity,
176
- })
177
- const bytes = readFileSync(source)
178
- const sizes = readWasmCodeLengths(bytes)
158
+ const sizes = readWasmCodeLengths(prepared)
179
159
  if (!sizes.length) return { primary: describePart(input), sides: [] }
180
- const startIndex = readWasmStartFunction(bytes)
181
- const names = symbols.stdout
182
- .trimEnd()
183
- .split('\n')
184
- .slice(-sizes.length)
185
- .map((line) => {
186
- const separator = line.indexOf(':')
187
- if (separator < 1) throw new Error('invalid Binaryen function map')
188
- return { index: Number(line.slice(0, separator)), name: line.slice(separator + 1) }
189
- })
160
+ const startIndex = readWasmStartFunction(prepared)
161
+ const names = readWasmCustomSection(prepared, 'name')
162
+ ? (
163
+ await run(binaryen, [source, ...features, '--print-function-map'], {
164
+ maxBuffer: Infinity,
165
+ })
166
+ ).stdout
167
+ .trimEnd()
168
+ .split('\n')
169
+ .slice(-sizes.length)
170
+ .map((line) => {
171
+ const separator = line.indexOf(':')
172
+ if (separator < 1) throw new Error('invalid Binaryen function map')
173
+ return {
174
+ index: Number(line.slice(0, separator)),
175
+ name: line.slice(separator + 1),
176
+ }
177
+ })
178
+ : (() => {
179
+ let importedFuncs = 0
180
+ const importSection = wasmSections(prepared).find(({ id }) => id === 2)
181
+ if (importSection)
182
+ readWasmImports(prepared, importSection, ({ kind }) => {
183
+ if (kind === 0) importedFuncs++
184
+ })
185
+ return Array.from({ length: sizes.length }, (_, ordinal) => ({
186
+ index: importedFuncs + ordinal,
187
+ name: String(ordinal),
188
+ }))
189
+ })()
190
190
  if (names.length !== sizes.length)
191
191
  throw new Error('Binaryen function map is incomplete')
192
- const hot = new Set(
193
- startup.stdout
194
- .split('\n')
195
- .filter((line) => line.startsWith('+ '))
196
- .map((line) => line.slice(2)),
192
+ const profileBytes = readFileSync(profile)
193
+ const expectedProfileSlots = readWasmFunctionCount(delivered)
194
+ if (
195
+ profileBytes.length < 8 ||
196
+ profileBytes.length !== 8 + expectedProfileSlots * 4 ||
197
+ expectedProfileSlots < sizes.length
197
198
  )
199
+ throw new Error('native startup profile size does not match module function count')
200
+ const hot = new Set<string>()
201
+ for (let ordinal = 0; ordinal < sizes.length; ordinal++) {
202
+ if (profileBytes.readUInt32LE(8 + ordinal * 4) !== 0) hot.add(names[ordinal]!.name)
203
+ }
198
204
  if (hot.size === 0)
199
205
  throw new Error('native startup profile contains no executed functions')
200
206
  const lazyAt = new Map<number, number[]>()
@@ -371,11 +377,11 @@ export async function splitNativeWasm(
371
377
  if (!parts.length) return { primary: describePart(input), sides: [] }
372
378
  const admitted = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES)
373
379
  const requested = Number(process.env.BINARYEN_CORES)
380
+ const cores = Math.max(1, availableParallelism())
374
381
  const jobs = Math.min(
375
- 8,
376
- availableParallelism(),
377
- Number.isInteger(admitted) && admitted > 0 ? admitted : 8,
378
- Number.isInteger(requested) && requested > 0 ? requested : 8,
382
+ cores,
383
+ Number.isInteger(admitted) && admitted > 0 ? admitted : cores,
384
+ Number.isInteger(requested) && requested > 0 ? requested : cores,
379
385
  )
380
386
  const env = jobs > 1 ? { ...process.env, BINARYEN_CORES: '1' } : undefined
381
387
  const sides = await mapLimit(