dorkos 0.98.0 → 0.101.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 (194) hide show
  1. package/README.md +43 -13
  2. package/dist/bin/cli.js +10649 -8676
  3. package/dist/browser/fresh-verifier.mjs +3 -2
  4. package/dist/browser/native/darwin-journal-worker.mjs +2244 -0
  5. package/dist/browser/native/darwin-process-observer +0 -0
  6. package/dist/browser/native/darwin-process-observer.c +252 -0
  7. package/dist/browser/native/darwin-process-observer.h +37 -0
  8. package/dist/browser/native/darwin-process-observer.manifest.json +1 -0
  9. package/dist/browser/native/darwin-supervisor-worker.mjs +1996 -0
  10. package/dist/browser/native/package-manifest.json +1 -0
  11. package/dist/browser/source-manifest.json +1 -1
  12. package/dist/client/assets/{AboutPage-DqTcRYx5.js → AboutPage-CwxCTicf.js} +1 -1
  13. package/dist/client/assets/ActivityRow-D0QQ0SFu.js +1 -0
  14. package/dist/client/assets/AdapterIcon-CL-MyyKy.js +1 -0
  15. package/dist/client/assets/AdapterSetupWizard-C8HOvHLF.js +2 -0
  16. package/dist/client/assets/AgentRequestCard-BLLmoAES.js +12 -0
  17. package/dist/client/assets/AppearancePage-GqrWckTQ.js +1 -0
  18. package/dist/client/assets/AttentionSignalRow-sEhnIPBB.js +1 -0
  19. package/dist/client/assets/{BaseTanStackRouterDevtoolsPanel-B-iktbLX-Bmlsorom.js → BaseTanStackRouterDevtoolsPanel-B-iktbLX-BXjzhT_D.js} +1 -1
  20. package/dist/client/assets/{BlintzCanvas-BBW7iNEC.js → BlintzCanvas-CXi0fvcM.js} +1 -1
  21. package/dist/client/assets/{CanvasCsvContent-D6qWSQm4.js → CanvasCsvContent-QhDSf8Pd.js} +2 -2
  22. package/dist/client/assets/CanvasFileContent-ZZhdofR4.js +2 -0
  23. package/dist/client/assets/CanvasModel3dContent-DMMMZh4o.js +2 -0
  24. package/dist/client/assets/{CodeMirrorDiff-DsOh9sIB.js → CodeMirrorDiff-BMG7DBg2.js} +1 -1
  25. package/dist/client/assets/{CodeMirrorEditor-BxIWDXqr.js → CodeMirrorEditor-BYdz0ipX.js} +1 -1
  26. package/dist/client/assets/ConnectionAccessLists-PW1uzcGU.js +1 -0
  27. package/dist/client/assets/{ConnectionsPage-DvxSfsfG.js → ConnectionsPage-EwitZwOE.js} +3 -3
  28. package/dist/client/assets/ConventionPage-y-Zq3Klp.js +11 -0
  29. package/dist/client/assets/ExtensionPageRoute-gZKKPhaj.js +6 -0
  30. package/dist/client/assets/{FloatingTanStackRouterDevtools-CqogiFob-BCrkUo51.js → FloatingTanStackRouterDevtools-CqogiFob-CbKIa11X.js} +1 -1
  31. package/dist/client/assets/HandlePage-CL3_n1CI.js +1 -0
  32. package/dist/client/assets/{LexicalField-mvJHHMqo.js → LexicalField-Ceoa9flp.js} +13 -13
  33. package/dist/client/assets/{ManagesPage-DScJn5uY.js → ManagesPage-Dcqdm6I8.js} +1 -1
  34. package/dist/client/assets/Marketplace-DsU-q1ZZ.js +36 -0
  35. package/dist/client/assets/MarketplaceSourcesView-D72YoKNR.js +1 -0
  36. package/dist/client/assets/McpAppFrame-B1ThSf2U.js +6 -0
  37. package/dist/client/assets/McpSigninBody-Btg3PnYN.js +1 -0
  38. package/dist/client/assets/{Model3dViewer-BYNxJNRV.js → Model3dViewer-DlcQ3-LS.js} +1 -1
  39. package/dist/client/assets/NamePage-Bzqj4Eob.js +1 -0
  40. package/dist/client/assets/NewDirectMessageMenu-89yeGqvy.js +1 -0
  41. package/dist/client/assets/{NotificationsPage-CU6oIOwb.js → NotificationsPage-CQQIdLtI.js} +1 -1
  42. package/dist/client/assets/OperatorIdentityForm-BhiB9tQp.js +1 -0
  43. package/dist/client/assets/{PermissionsPage-BIatOhyg.js → PermissionsPage-TX-d7aVQ.js} +1 -1
  44. package/dist/client/assets/PersonalityPicker-C_9JVOva.js +1 -0
  45. package/dist/client/assets/PersonalityPopover-BoTED73t.js +1 -0
  46. package/dist/client/assets/PhotoPage-C3fMlebQ.js +1 -0
  47. package/dist/client/assets/PreviewRefusedNotice-ChCgdKWN.js +1 -0
  48. package/dist/client/assets/PromptSuggestionChips-B_oUtFMI.js +1 -0
  49. package/dist/client/assets/RoomSurface-CgtNuYhl.js +39 -0
  50. package/dist/client/assets/RoomsPage-zOjjpHdA.js +1 -0
  51. package/dist/client/assets/RunsOnPopover-JTm1cYuw.js +1 -0
  52. package/dist/client/assets/SessionsPage-D4kyvHQf.js +6 -0
  53. package/dist/client/assets/SkillsPage-KYUVzuVa.js +1 -0
  54. package/dist/client/assets/TasksPage-BZapA_v6.js +1 -0
  55. package/dist/client/assets/{ToolsPage-BMW27c-X.js → ToolsPage-CWpHMlrR.js} +2 -2
  56. package/dist/client/assets/{TopologyGraph-u-ihEvQa.js → TopologyGraph-BMcPxZsA.js} +3 -3
  57. package/dist/client/assets/TourHost-VY1-sy1Y.js +1 -0
  58. package/dist/client/assets/UnlinkDialog-3p38G_9q.js +1 -0
  59. package/dist/client/assets/UnreadDivider-KSqqcHKN.js +1 -0
  60. package/dist/client/assets/_shell-DAjwimLg.js +93 -0
  61. package/dist/client/assets/_shell._home-Bp_p1VUv.js +1 -0
  62. package/dist/client/assets/_shell._home.activity-tk-XApvX.js +1 -0
  63. package/dist/client/assets/_shell._home.index-BNVhSN0y.js +3 -0
  64. package/dist/client/assets/_shell._home.tasks-BsBH_4tZ.js +1 -0
  65. package/dist/client/assets/_shell._home.workspaces-DuXnjQh0.js +1 -0
  66. package/dist/client/assets/_shell.channels-DWAHkDPV.js +10 -0
  67. package/dist/client/assets/_shell.connections-DIm3mUHy.js +6 -0
  68. package/dist/client/assets/_shell.feedback-requests-Hjv640j9.js +2 -0
  69. package/dist/client/assets/_shell.marketplace-DF6Y7mc0.js +1 -0
  70. package/dist/client/assets/_shell.marketplace_.sources-Do8cm7kq.js +1 -0
  71. package/dist/client/assets/_shell.session-DlN8iOl-.js +43 -0
  72. package/dist/client/assets/_shell.team-ctLQztjw.js +28 -0
  73. package/dist/client/assets/_shell.x._extensionId-0Q1rJtud.js +1 -0
  74. package/dist/client/assets/_shell.x._extensionId_._-0Q1rJtud.js +1 -0
  75. package/dist/client/assets/agent-attention-Dn__3LQE.js +5 -0
  76. package/dist/client/assets/{agent-browser-Bn5EG403.js → agent-browser-CCN16ZOz.js} +1 -1
  77. package/dist/client/assets/banner-DOm9_4l-.js +6 -0
  78. package/dist/client/assets/composer-insert-BpyATrmR.js +1 -0
  79. package/dist/client/assets/dorkbot-templates-cu4wApxb.js +1 -0
  80. package/dist/client/assets/file-drag-GDx2qhdk.js +1 -0
  81. package/dist/client/assets/file-exclamation-point-BKzL0QhY.js +6 -0
  82. package/dist/client/assets/format-duration-BCr6uzby.js +1 -0
  83. package/dist/client/assets/hand-DLUdsiuR.js +6 -0
  84. package/dist/client/assets/{highlighted-body-KPVGNVTW-CL9x-9e4.js → highlighted-body-KPVGNVTW-DTxMTVdP.js} +1 -1
  85. package/dist/client/assets/hover-card-qzuFUCaR.js +1 -0
  86. package/dist/client/assets/{index-nEOi__50.js → index-3lQkXKcq.js} +1 -1
  87. package/dist/client/assets/{index-CpJvQdyn.js → index-B-z7hA9x.js} +1 -1
  88. package/dist/client/assets/{index-C-wQjAlh.js → index-BIMClIrX.js} +1 -1
  89. package/dist/client/assets/{index-lrzDDn8S.js → index-BMOfHKE0.js} +1 -1
  90. package/dist/client/assets/{index-CK35WFBO.js → index-BPcwoJoz.js} +1 -1
  91. package/dist/client/assets/{index-CsQv_9cY.js → index-BW5ce4t8.js} +1 -1
  92. package/dist/client/assets/{index-C2L0bOg6.js → index-BaB-skF0.js} +3 -3
  93. package/dist/client/assets/{index-DAXybyxB.js → index-Bk98IpMn.js} +1 -1
  94. package/dist/client/assets/{index-62aJQhJd.js → index-C3XnoXTY.js} +1 -1
  95. package/dist/client/assets/{index-tY8nAJmx.js → index-C7B2uRgo.js} +2 -2
  96. package/dist/client/assets/index-C8ZMfyGc.js +1 -0
  97. package/dist/client/assets/{index-BSl_jWtK.js → index-CDTumWMC.js} +1 -1
  98. package/dist/client/assets/{index-DuWGfUC7.js → index-CF9fqPef.js} +5 -5
  99. package/dist/client/assets/{index-DEYZcwYZ.js → index-CIPHHziB.js} +1 -1
  100. package/dist/client/assets/{index-DOVEs6Rq.js → index-CIfwPLXd.js} +1 -1
  101. package/dist/client/assets/{index-DnjFcJhW.js → index-CLhD0Bno.js} +36 -36
  102. package/dist/client/assets/index-CQWqpw_G.js +1 -0
  103. package/dist/client/assets/index-CScfHuKF.js +1 -0
  104. package/dist/client/assets/index-CTXNRyRE.js +1 -0
  105. package/dist/client/assets/{index-C3fr7zOo.js → index-CTai_TxZ.js} +1 -1
  106. package/dist/client/assets/{index-CniKYwdp.js → index-CVl132_4.js} +1 -1
  107. package/dist/client/assets/index-CejezM4U.js +1 -0
  108. package/dist/client/assets/{index-Bc9XDEj8.js → index-CmlaXay_.js} +1 -1
  109. package/dist/client/assets/{index-KIOfBCox.js → index-CtOB9fS3.js} +1 -1
  110. package/dist/client/assets/{index-DyFf2nbN.js → index-D3DXMH4x.js} +1 -1
  111. package/dist/client/assets/index-D5uYwabS.js +1 -0
  112. package/dist/client/assets/{index-CaEda4s3.js → index-DA-i3I4q.js} +1 -1
  113. package/dist/client/assets/index-DFMDv6qR.js +1 -0
  114. package/dist/client/assets/index-DMYBI16t.js +1252 -0
  115. package/dist/client/assets/{index-DzBsotRj.js → index-DOxEmnH2.js} +1 -1
  116. package/dist/client/assets/{index-Dxkj6c9m.js → index-DR1JT9Uz.js} +12 -12
  117. package/dist/client/assets/{index-BO-CpekL.js → index-DT_v3O-B.js} +1 -1
  118. package/dist/client/assets/index-DbbZNAKk.js +5 -0
  119. package/dist/client/assets/{index-BBz-vkiB.js → index-Dcs6e-U_.js} +1 -1
  120. package/dist/client/assets/{index-BE54c4kA.js → index-DgH_dl1a.js} +2 -2
  121. package/dist/client/assets/{index-DPGgujWh.js → index-DgtF-nBt.js} +1 -1
  122. package/dist/client/assets/{index-BlbBz069.js → index-DwzSdOh3.js} +1 -1
  123. package/dist/client/assets/index-IgIVF9T_.js +1 -0
  124. package/dist/client/assets/{index-aFkVVlMJ.js → index-WjW-NUCp.js} +1 -1
  125. package/dist/client/assets/layers-CJHXSEKK.js +6 -0
  126. package/dist/client/assets/lightbulb-DWjxw7lb.js +6 -0
  127. package/dist/client/assets/mention-pill-akMU3IVs.js +1 -0
  128. package/dist/client/assets/message-square-off-DEagHpQY.js +6 -0
  129. package/dist/client/assets/owner-notice-CLsx0s7q.js +1 -0
  130. package/dist/client/assets/page-container-W7byjRmk.js +1 -0
  131. package/dist/client/assets/primer-trigger-DuM9vVnV.js +3 -0
  132. package/dist/client/assets/radio-B8Ozjv9U.js +6 -0
  133. package/dist/client/assets/{room-files-source-BXJ2jlgd.js → room-files-source-Bsc3YA91.js} +2 -2
  134. package/dist/client/assets/rotate-ccw-clock-CNcDcTvq.js +6 -0
  135. package/dist/client/assets/rotate-cw-xvfipJLN.js +6 -0
  136. package/dist/client/assets/scroll-area-C95q3ss7.js +1 -0
  137. package/dist/client/assets/search-x-C6SAxw7a.js +6 -0
  138. package/dist/client/assets/session-strategy-labels-C7Wduch3.js +1 -0
  139. package/dist/client/assets/shield-x-DxOGc0dW.js +6 -0
  140. package/dist/client/assets/{soul-file-11avkxYV.js → soul-file-pg0ShYy3.js} +1 -1
  141. package/dist/client/assets/untrusted-text-1hXdPgLA.js +1 -0
  142. package/dist/client/assets/use-delete-binding-CZVeHqn0.js +1 -0
  143. package/dist/client/assets/use-dev-links-Df2WkCic.js +1 -0
  144. package/dist/client/assets/use-external-adapter-catalog-B0gcY-k7.js +1 -0
  145. package/dist/client/assets/use-full-activity-feed-SYcgdMZu.js +1 -0
  146. package/dist/client/assets/use-is-below-desktop-C5_YenEp.js +1 -0
  147. package/dist/client/assets/use-jump-back-in-DWUPb1gi.js +11 -0
  148. package/dist/client/assets/use-mesh-topology-HLzZIgis.js +1 -0
  149. package/dist/client/assets/use-pending-read-BuJknrxG.js +1 -0
  150. package/dist/client/assets/{use-personality-commit-PCN2Kh8p.js → use-personality-commit-OH7d0xl_.js} +1 -1
  151. package/dist/client/assets/use-promo-activation-BgdGasXE.js +11 -0
  152. package/dist/client/assets/use-pulse-freshness-BlD-dM_g.js +1 -0
  153. package/dist/client/assets/use-rename-session-D3MuyK-F.js +1 -0
  154. package/dist/client/assets/use-room-follow-claim-CyjhzbRJ.js +1 -0
  155. package/dist/client/assets/use-roving-tab-list-Be60AWK3.js +1 -0
  156. package/dist/client/assets/use-session-canvas-Bqs6IQO7.js +64 -0
  157. package/dist/client/assets/use-session-diagnostics-CfKdB2iY.js +16 -0
  158. package/dist/client/assets/use-unclaimed-chats-lqMhotUB.js +1 -0
  159. package/dist/client/index.html +1 -1
  160. package/dist/client/manifest.webmanifest +1 -1
  161. package/dist/drizzle/20261005194144_connector_auth_flow_failure_code.sql +1 -0
  162. package/dist/drizzle/20261005230915_task_run_occurrence.sql +2 -0
  163. package/dist/drizzle/20261006231015_audit_events.sql +63 -0
  164. package/dist/drizzle/20261007230701_private_session_identity.sql +15 -0
  165. package/dist/drizzle/meta/20261005194144_snapshot.json +12238 -0
  166. package/dist/drizzle/meta/20261005230915_snapshot.json +12252 -0
  167. package/dist/drizzle/meta/20261006231015_snapshot.json +12519 -0
  168. package/dist/drizzle/meta/20261007230701_snapshot.json +12611 -0
  169. package/dist/drizzle/meta/_journal.json +28 -0
  170. package/dist/server/index.js +161811 -97213
  171. package/dist/server/index.js.map +2 -2
  172. package/package.json +5 -5
  173. package/dist/client/assets/AdapterIcon-CiK683Vv.js +0 -1
  174. package/dist/client/assets/AppearancePage-CBq2_KUY.js +0 -1
  175. package/dist/client/assets/CanvasFileContent-jV63reY5.js +0 -2
  176. package/dist/client/assets/CanvasModel3dContent-DzvsEWGD.js +0 -2
  177. package/dist/client/assets/ConnectionAccessLists-BWuegEtZ.js +0 -1
  178. package/dist/client/assets/ConventionPage-CYV7X_nF.js +0 -11
  179. package/dist/client/assets/HandlePage-CJpRpaLw.js +0 -1
  180. package/dist/client/assets/NamePage-KoYyo25o.js +0 -1
  181. package/dist/client/assets/PersonalityPopover-CFRYfO5E.js +0 -1
  182. package/dist/client/assets/PhotoPage-DkGyFlWQ.js +0 -1
  183. package/dist/client/assets/RoomsPage-ClT030eV.js +0 -1
  184. package/dist/client/assets/RunsOnPopover-CNCO9sZk.js +0 -1
  185. package/dist/client/assets/SessionsPage-5xEcQImi.js +0 -6
  186. package/dist/client/assets/SkillsPage-ic4TDV4I.js +0 -1
  187. package/dist/client/assets/TasksPage-C_GFpRgB.js +0 -1
  188. package/dist/client/assets/index-6COO_Ljw.js +0 -1
  189. package/dist/client/assets/index-BKl9b2dT.js +0 -1
  190. package/dist/client/assets/index-BVtk6Sb_.js +0 -1
  191. package/dist/client/assets/index-Bxrxl2HH.js +0 -1
  192. package/dist/client/assets/index-C6uVMs3w.js +0 -1
  193. package/dist/client/assets/index-DEvFAO8t.js +0 -1
  194. package/dist/client/assets/index-DpSk7iO1.js +0 -1680
@@ -0,0 +1,2244 @@
1
+ // packages/browser/src/runtime/darwin-journal-worker.ts
2
+ import { spawn as spawn3 } from "node:child_process";
3
+ import { z as z3 } from "zod";
4
+
5
+ // packages/browser/src/lifecycle/process-journal.ts
6
+ import { createHash } from "node:crypto";
7
+ import { constants } from "node:fs";
8
+ import * as fs from "node:fs/promises";
9
+ import { isAbsolute, join, normalize, parse } from "node:path";
10
+ import { z } from "zod";
11
+ var JOURNAL_LIMITS = Object.freeze({
12
+ bytes: 1048576,
13
+ writerBytes: 4096,
14
+ identities: 512,
15
+ gaps: 32,
16
+ depth: 16,
17
+ pending: 8
18
+ });
19
+ var GAP_CODES = [
20
+ "boot-unknown",
21
+ "boot-changed",
22
+ "identity-unknown",
23
+ "root-pending",
24
+ "parent-changed",
25
+ "association-missing",
26
+ "observer-lost",
27
+ "sequence-gap",
28
+ "frame-invalid",
29
+ "capacity-exceeded",
30
+ "read-uncertain",
31
+ "persistence-uncertain",
32
+ "custody-pending"
33
+ ];
34
+ var counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
35
+ var text = (cap) => z.string().min(1).refine(
36
+ (v) => v.length <= cap && Buffer.byteLength(v) <= cap && Buffer.from(v).toString("utf8") === v && ![...v].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)
37
+ );
38
+ var opaque = text(64).refine((v) => /^[A-Za-z0-9_-]+$/.test(v));
39
+ var digestSchema = z.string().regex(/^[a-f0-9]{64}$/);
40
+ var ProcessIdentitySchema = z.object({ pid: counter.refine((v) => v > 0), birth: text(128) }).strict();
41
+ var BootScopeSchema = z.discriminatedUnion("kind", [
42
+ z.object({ kind: z.literal("observed"), value: text(128), sourceIdentityDigest: digestSchema }).strict(),
43
+ z.object({ kind: z.literal("unknown"), cause: z.enum(GAP_CODES) }).strict()
44
+ ]);
45
+ var JournalBindingSchema = z.object({
46
+ journalId: opaque,
47
+ browserId: opaque,
48
+ profile: z.discriminatedUnion("kind", [
49
+ z.object({ kind: z.literal("persistent"), profileId: opaque }).strict(),
50
+ z.object({ kind: z.literal("ephemeral") }).strict()
51
+ ]),
52
+ browserGeneration: counter,
53
+ reservationNonce: opaque,
54
+ runtimeIdentityDigest: digestSchema,
55
+ manager: ProcessIdentitySchema,
56
+ bootScope: BootScopeSchema
57
+ }).strict();
58
+ var JournalWriterSchema = z.object({ writerId: opaque, epoch: counter, kind: z.enum(["manager", "observer", "reconciler"]) }).strict();
59
+ var ObservationWindowSchema = z.object({
60
+ startSequence: counter,
61
+ checkpointSequence: counter,
62
+ endSequence: counter,
63
+ startMonotonic: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
64
+ endMonotonic: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER)
65
+ }).strict().refine(
66
+ (w) => w.startSequence <= w.checkpointSequence && w.checkpointSequence <= w.endSequence && w.startMonotonic <= w.endMonotonic
67
+ );
68
+ var AssociationSchema = z.object({
69
+ parentBefore: ProcessIdentitySchema,
70
+ parentAfter: ProcessIdentitySchema,
71
+ child: ProcessIdentitySchema,
72
+ childParentPid: counter.refine((v) => v > 0),
73
+ window: ObservationWindowSchema,
74
+ recordedSequence: counter,
75
+ parentDeathSequence: counter.nullable()
76
+ }).strict().refine(
77
+ (a) => sameProcess(a.parentBefore, a.parentAfter) && a.child.pid !== a.parentBefore.pid && a.childParentPid === a.parentBefore.pid && a.window.endSequence <= a.recordedSequence && (a.parentDeathSequence === null || a.recordedSequence < a.parentDeathSequence)
78
+ );
79
+ var retainedSchema = z.object({
80
+ identity: ProcessIdentitySchema,
81
+ role: z.enum(["manager", "root", "descendant"]),
82
+ parent: ProcessIdentitySchema.nullable(),
83
+ association: AssociationSchema.nullable(),
84
+ currentParent: ProcessIdentitySchema.nullable(),
85
+ acquisitionEpoch: counter,
86
+ firstSeenSequence: counter,
87
+ lastSeenSequence: counter,
88
+ relationWindow: ObservationWindowSchema,
89
+ lifecycle: z.enum(["alive", "exited-unreaped", "dead", "replacement", "unknown"])
90
+ }).strict();
91
+ var gapSchema = z.object({
92
+ cause: z.enum(GAP_CODES),
93
+ firstSequence: counter,
94
+ identity: ProcessIdentitySchema.nullable(),
95
+ count: counter.refine((v) => v > 0)
96
+ }).strict();
97
+ var causeSchema = z.object({ cause: z.enum(GAP_CODES), sequence: counter }).strict();
98
+ var JournalSnapshotSchema = z.object({
99
+ schemaVersion: z.literal(1),
100
+ kind: z.literal("browser-process-journal"),
101
+ provenance: z.literal("recorded-data"),
102
+ binding: JournalBindingSchema,
103
+ writer: JournalWriterSchema,
104
+ sequence: counter,
105
+ phase: z.enum([
106
+ "allocated",
107
+ "launch-intent",
108
+ "observing",
109
+ "manager-lost",
110
+ "reconciling",
111
+ "observation-ended",
112
+ "retained"
113
+ ]),
114
+ observationWindow: ObservationWindowSchema,
115
+ root: z.discriminatedUnion("kind", [
116
+ z.object({ kind: z.literal("pending") }).strict(),
117
+ z.object({ kind: z.literal("absent-before-launch") }).strict(),
118
+ z.object({
119
+ kind: z.literal("attributed"),
120
+ identity: ProcessIdentitySchema,
121
+ association: AssociationSchema
122
+ }).strict()
123
+ ]),
124
+ retainedIdentities: z.array(retainedSchema).max(JOURNAL_LIMITS.identities),
125
+ gaps: z.array(gapSchema).max(JOURNAL_LIMITS.gaps),
126
+ firstCause: causeSchema.nullable()
127
+ }).strict();
128
+ var ProcessJournalError = class extends Error {
129
+ constructor(causeCode) {
130
+ super(causeCode);
131
+ this.causeCode = causeCode;
132
+ this.name = "ProcessJournalError";
133
+ }
134
+ causeCode;
135
+ };
136
+ function insist(ok, cause = "frame-invalid") {
137
+ if (!ok) throw new ProcessJournalError(cause);
138
+ }
139
+ function sameProcess(a, b) {
140
+ return a.pid === b.pid && a.birth === b.birth;
141
+ }
142
+ function processKey(identity4) {
143
+ return JSON.stringify([identity4.pid, identity4.birth]);
144
+ }
145
+ function copyJournalData(value) {
146
+ const seen = /* @__PURE__ */ new WeakSet();
147
+ let nodes = 0;
148
+ const visit = (item, depth) => {
149
+ insist(++nodes <= 32768 && depth <= JOURNAL_LIMITS.depth, "capacity-exceeded");
150
+ if (item === null || typeof item === "boolean") return item;
151
+ if (typeof item === "number") {
152
+ insist(Number.isFinite(item));
153
+ return item;
154
+ }
155
+ if (typeof item === "string") {
156
+ insist(item.length <= 128 && Buffer.byteLength(item) <= 128, "capacity-exceeded");
157
+ insist(Buffer.from(item).toString("utf8") === item);
158
+ return item;
159
+ }
160
+ insist(typeof item === "object" && item !== null);
161
+ insist(!seen.has(item));
162
+ seen.add(item);
163
+ const array = Array.isArray(item);
164
+ const proto = Object.getPrototypeOf(item);
165
+ insist(array ? proto === Array.prototype : proto === Object.prototype || proto === null);
166
+ insist(Object.getOwnPropertySymbols(item).length === 0);
167
+ const keys = Object.getOwnPropertyNames(item);
168
+ if (array) {
169
+ const length = Object.getOwnPropertyDescriptor(item, "length");
170
+ insist(
171
+ length && "value" in length && Number.isSafeInteger(length.value) && length.value >= 0 && length.value <= JOURNAL_LIMITS.identities,
172
+ "capacity-exceeded"
173
+ );
174
+ insist(keys.length === length.value + 1);
175
+ const out2 = [];
176
+ for (let i = 0; i < length.value; i++) {
177
+ const descriptor = Object.getOwnPropertyDescriptor(item, String(i));
178
+ insist(descriptor && "value" in descriptor && descriptor.enumerable);
179
+ out2.push(visit(descriptor.value, depth + 1));
180
+ }
181
+ seen.delete(item);
182
+ return out2;
183
+ }
184
+ insist(keys.length <= 24, "capacity-exceeded");
185
+ const out = /* @__PURE__ */ Object.create(null);
186
+ for (const key of keys) {
187
+ insist(
188
+ key.length <= 64 && !["__proto__", "constructor", "prototype", "then", "toJSON"].includes(key)
189
+ );
190
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
191
+ insist(descriptor && "value" in descriptor && descriptor.enumerable);
192
+ out[key] = visit(descriptor.value, depth + 1);
193
+ }
194
+ seen.delete(item);
195
+ return out;
196
+ };
197
+ try {
198
+ return visit(value, 0);
199
+ } catch (error) {
200
+ throw error instanceof ProcessJournalError ? error : new ProcessJournalError("frame-invalid");
201
+ }
202
+ }
203
+ function frozen(value) {
204
+ if (value && typeof value === "object") {
205
+ for (const child of Object.values(value)) frozen(child);
206
+ Object.freeze(value);
207
+ }
208
+ return value;
209
+ }
210
+ function recordedJSON(value) {
211
+ const sort = (item) => {
212
+ if (Array.isArray(item)) return item.map(sort);
213
+ if (item && typeof item === "object")
214
+ return Object.fromEntries(
215
+ Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sort(v)])
216
+ );
217
+ return item;
218
+ };
219
+ return JSON.stringify(sort(copyJournalData(value)));
220
+ }
221
+ function sameJournalBinding(a, b) {
222
+ return recordedJSON(a) === recordedJSON(b);
223
+ }
224
+ function validateJournalSnapshot(value) {
225
+ const parsed = JournalSnapshotSchema.safeParse(copyJournalData(value));
226
+ insist(parsed.success);
227
+ const s = parsed.data;
228
+ insist(s.observationWindow.endSequence <= s.sequence);
229
+ const identities = new Map(s.retainedIdentities.map((r) => [processKey(r.identity), r]));
230
+ insist(identities.size === s.retainedIdentities.length);
231
+ const managers = s.retainedIdentities.filter((r) => r.role === "manager");
232
+ insist(managers.length === 1 && sameProcess(managers[0].identity, s.binding.manager));
233
+ for (const r of s.retainedIdentities) {
234
+ insist(
235
+ r.firstSeenSequence <= r.lastSeenSequence && r.lastSeenSequence <= s.sequence && r.relationWindow.endSequence <= r.firstSeenSequence && r.acquisitionEpoch <= s.writer.epoch
236
+ );
237
+ if (r.lifecycle === "exited-unreaped")
238
+ insist(
239
+ r.role === "descendant" && r.association !== null && r.parent !== null && r.firstSeenSequence < r.lastSeenSequence,
240
+ "association-missing"
241
+ );
242
+ if (r.lifecycle === "unknown")
243
+ insist(
244
+ s.gaps.some(
245
+ (g) => g.cause === "identity-unknown" && (g.identity === null || sameProcess(g.identity, r.identity))
246
+ ),
247
+ "identity-unknown"
248
+ );
249
+ if (r.role === "manager") insist(r.parent === null && r.association === null);
250
+ else {
251
+ const a = r.association;
252
+ insist(
253
+ a && r.parent && sameProcess(a.parentBefore, r.parent) && sameProcess(a.child, r.identity) && a.recordedSequence === r.firstSeenSequence && identities.has(processKey(r.parent)),
254
+ "association-missing"
255
+ );
256
+ insist(recordedJSON(a.window) === recordedJSON(r.relationWindow));
257
+ let ancestor = r.parent, depth = 0;
258
+ const visited = /* @__PURE__ */ new Set([processKey(r.identity)]);
259
+ while (ancestor) {
260
+ const key = processKey(ancestor);
261
+ insist(!visited.has(key) && ++depth <= JOURNAL_LIMITS.depth, "association-missing");
262
+ visited.add(key);
263
+ const parent = identities.get(key);
264
+ insist(parent, "association-missing");
265
+ ancestor = parent.parent;
266
+ }
267
+ }
268
+ }
269
+ const roots = s.retainedIdentities.filter((r) => r.role === "root");
270
+ if (s.root.kind === "attributed") {
271
+ insist(
272
+ roots.length === 1 && sameProcess(roots[0].identity, s.root.identity) && recordedJSON(roots[0].association) === recordedJSON(s.root.association),
273
+ "association-missing"
274
+ );
275
+ } else insist(roots.length === 0, "root-pending");
276
+ const gapKinds = new Set(s.gaps.map((g) => g.cause));
277
+ insist(gapKinds.size === s.gaps.length && s.gaps.every((g) => g.firstSequence <= s.sequence));
278
+ if (s.gaps.length)
279
+ insist(
280
+ s.firstCause && s.gaps.some(
281
+ (g) => g.cause === s.firstCause.cause && g.firstSequence === s.firstCause.sequence
282
+ ) && s.firstCause.sequence === Math.min(...s.gaps.map((g) => g.firstSequence))
283
+ );
284
+ else insist(s.firstCause === null);
285
+ insist(Buffer.byteLength(recordedJSON(s)) <= JOURNAL_LIMITS.bytes, "capacity-exceeded");
286
+ return frozen(s);
287
+ }
288
+ var phases = [
289
+ "allocated",
290
+ "launch-intent",
291
+ "observing",
292
+ "manager-lost",
293
+ "reconciling",
294
+ "observation-ended",
295
+ "retained"
296
+ ];
297
+ function successor(prior, next) {
298
+ insist(
299
+ sameJournalBinding(prior.binding, next.binding) && next.sequence === prior.sequence + 1 && next.writer.epoch === prior.writer.epoch && recordedJSON(next.writer) === recordedJSON(prior.writer),
300
+ "sequence-gap"
301
+ );
302
+ insist(
303
+ phases.indexOf(next.phase) >= phases.indexOf(prior.phase) && next.observationWindow.startSequence >= prior.observationWindow.startSequence && next.observationWindow.checkpointSequence >= prior.observationWindow.checkpointSequence && next.observationWindow.endSequence >= prior.observationWindow.endSequence && next.observationWindow.startMonotonic >= prior.observationWindow.startMonotonic && next.observationWindow.endMonotonic >= prior.observationWindow.endMonotonic,
304
+ "sequence-gap"
305
+ );
306
+ if (prior.root.kind === "attributed")
307
+ insist(recordedJSON(prior.root) === recordedJSON(next.root), "association-missing");
308
+ if (prior.firstCause) insist(recordedJSON(prior.firstCause) === recordedJSON(next.firstCause));
309
+ for (const gap of prior.gaps)
310
+ insist(
311
+ next.gaps.some(
312
+ (g) => g.cause === gap.cause && g.firstSequence === gap.firstSequence && g.count >= gap.count && recordedJSON(g.identity) === recordedJSON(gap.identity)
313
+ )
314
+ );
315
+ for (const old of prior.retainedIdentities) {
316
+ const current = next.retainedIdentities.find((r) => sameProcess(r.identity, old.identity));
317
+ insist(
318
+ current && current.role === old.role && current.acquisitionEpoch === old.acquisitionEpoch && current.firstSeenSequence === old.firstSeenSequence && current.lastSeenSequence >= old.lastSeenSequence && recordedJSON(current.parent) === recordedJSON(old.parent) && recordedJSON(current.association) === recordedJSON(old.association) && recordedJSON(current.relationWindow) === recordedJSON(old.relationWindow),
319
+ "association-missing"
320
+ );
321
+ }
322
+ for (const old of prior.retainedIdentities)
323
+ if (old.lifecycle === "exited-unreaped") {
324
+ const current = next.retainedIdentities.find((r) => sameProcess(r.identity, old.identity));
325
+ insist(current && current.lifecycle !== "alive", "identity-unknown");
326
+ }
327
+ for (const added of next.retainedIdentities)
328
+ if (!prior.retainedIdentities.some((r) => sameProcess(r.identity, added.identity))) {
329
+ const parent = prior.retainedIdentities.find(
330
+ (r) => added.parent && sameProcess(r.identity, added.parent)
331
+ );
332
+ insist(
333
+ added.role !== "manager" && added.firstSeenSequence === next.sequence && parent && parent.lifecycle === "alive",
334
+ "association-missing"
335
+ );
336
+ }
337
+ }
338
+ var heldFiles = /* @__PURE__ */ new Set();
339
+ var localFileSlots = 0;
340
+ var Files = class {
341
+ constructor(hooks = {}) {
342
+ this.hooks = hooks;
343
+ }
344
+ hooks;
345
+ duties = [];
346
+ async point(point) {
347
+ await this.hooks.fault?.(point);
348
+ }
349
+ async open(path, flags, mode = 384) {
350
+ insist(this.duties.length < 64 && localFileSlots < 64, "capacity-exceeded");
351
+ const duty = {
352
+ acquisitionPending: true,
353
+ acquired: false,
354
+ closeAttempted: false,
355
+ closed: false
356
+ };
357
+ this.duties.push(duty);
358
+ localFileSlots++;
359
+ try {
360
+ duty.handle = await fs.open(path, flags, mode);
361
+ duty.acquired = true;
362
+ duty.acquisitionPending = false;
363
+ } catch (error) {
364
+ const code = error.code;
365
+ if (code === "EEXIST" || code === "ENOENT") {
366
+ duty.acquisitionPending = false;
367
+ localFileSlots--;
368
+ }
369
+ throw error;
370
+ }
371
+ return duty;
372
+ }
373
+ async close(duty, point) {
374
+ if (duty.closeAttempted) return;
375
+ duty.closeAttempted = true;
376
+ let failed = false, fault;
377
+ try {
378
+ if (point) await this.point(point);
379
+ } catch (error) {
380
+ failed = true;
381
+ fault = error;
382
+ }
383
+ try {
384
+ await duty.handle.close();
385
+ duty.closed = true;
386
+ localFileSlots--;
387
+ } catch (error) {
388
+ if (!failed) {
389
+ failed = true;
390
+ fault = error;
391
+ }
392
+ }
393
+ if (failed) throw fault;
394
+ }
395
+ async drain() {
396
+ let ok = true;
397
+ for (const duty of this.duties)
398
+ if (duty.acquired && !duty.closeAttempted) {
399
+ try {
400
+ await this.close(duty);
401
+ } catch {
402
+ ok = false;
403
+ }
404
+ }
405
+ const returned = ok && this.duties.every((d) => !d.acquisitionPending && (!d.acquired || d.closed));
406
+ if (this.duties.some((d) => d.acquisitionPending || d.acquired && !d.closed))
407
+ heldFiles.add(this);
408
+ return returned;
409
+ }
410
+ custody() {
411
+ return Object.freeze({
412
+ opens: this.duties.filter((d) => d.acquired).length,
413
+ closesAttempted: this.duties.filter((d) => d.closeAttempted).length,
414
+ closed: this.duties.filter((d) => d.closed).length,
415
+ held: this.duties.filter((d) => d.acquisitionPending || d.acquired && !d.closed).length
416
+ });
417
+ }
418
+ };
419
+ async function withOriginalClose(io, duty, operation, point) {
420
+ let failed = false, failure;
421
+ let result;
422
+ try {
423
+ result = await operation();
424
+ } catch (error) {
425
+ failed = true;
426
+ failure = error;
427
+ }
428
+ try {
429
+ await io.close(duty, point);
430
+ } catch (error) {
431
+ if (!failed) {
432
+ failed = true;
433
+ failure = error;
434
+ }
435
+ }
436
+ if (failed) throw failure;
437
+ return result;
438
+ }
439
+ var readFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
440
+ var createFlags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_NONBLOCK;
441
+ function identity(s) {
442
+ const shared = {
443
+ device: String(s.dev),
444
+ inode: String(s.ino),
445
+ mode: Number(s.mode),
446
+ uid: Number(s.uid)
447
+ };
448
+ if (s.isDirectory()) return { ...shared, type: "directory" };
449
+ insist(s.isFile() && !s.isSymbolicLink(), "read-uncertain");
450
+ return {
451
+ ...shared,
452
+ type: "file",
453
+ size: String(s.size),
454
+ mtimeNs: String(s.mtimeNs),
455
+ ctimeNs: String(s.ctimeNs)
456
+ };
457
+ }
458
+ function sameFile(a, b) {
459
+ return JSON.stringify(a) === JSON.stringify(b);
460
+ }
461
+ function sameDirectory(a, b) {
462
+ return a.type === "directory" && a.device === b.device && a.inode === b.inode && a.mode === b.mode && a.uid === b.uid;
463
+ }
464
+ async function named(path) {
465
+ return identity(await fs.lstat(path, { bigint: true }));
466
+ }
467
+ async function maybe(path) {
468
+ try {
469
+ return await named(path);
470
+ } catch (error) {
471
+ if (error.code === "ENOENT") return null;
472
+ throw error;
473
+ }
474
+ }
475
+ async function observeJournalDirectory(path) {
476
+ insist(isAbsolute(path) && normalize(path) === path && path.length <= 4096, "read-uncertain");
477
+ let current = parse(path).root;
478
+ for (const part of path.slice(current.length).split("/").filter(Boolean)) {
479
+ current = join(current, part);
480
+ insist((await named(current)).type === "directory", "read-uncertain");
481
+ }
482
+ const value = await named(path);
483
+ insist(value.type === "directory" && (value.mode & 63) === 0, "read-uncertain");
484
+ return Object.freeze(value);
485
+ }
486
+ function location(options) {
487
+ const binding = JournalBindingSchema.parse(copyJournalData(options.binding));
488
+ const p = z.object({
489
+ device: z.string().regex(/^\d+$/),
490
+ inode: z.string().regex(/^\d+$/),
491
+ mode: counter,
492
+ uid: counter,
493
+ type: z.literal("directory")
494
+ }).strict().parse(copyJournalData(options.parentIdentity));
495
+ insist(
496
+ p && p.type === "directory" && /^\d+$/.test(p.device) && /^\d+$/.test(p.inode) && Number.isSafeInteger(p.mode) && Number.isSafeInteger(p.uid) && (p.mode & 63) === 0,
497
+ "read-uncertain"
498
+ );
499
+ insist(
500
+ isAbsolute(options.parentDirectory) && normalize(options.parentDirectory) === options.parentDirectory && options.parentDirectory.length <= 4096,
501
+ "read-uncertain"
502
+ );
503
+ return Object.freeze({
504
+ parentDirectory: options.parentDirectory,
505
+ parentIdentity: Object.freeze({ ...p }),
506
+ binding: frozen(binding)
507
+ });
508
+ }
509
+ function rootPath(l) {
510
+ return join(l.parentDirectory, "journal-" + l.binding.journalId);
511
+ }
512
+ async function assertParent(l, io) {
513
+ await io.point("parent-check");
514
+ insist(
515
+ sameDirectory(await observeJournalDirectory(l.parentDirectory), l.parentIdentity),
516
+ "parent-changed"
517
+ );
518
+ }
519
+ async function assertRoot(l, pin, io) {
520
+ await assertParent(l, io);
521
+ insist(sameDirectory(await named(rootPath(l)), pin), "parent-changed");
522
+ }
523
+ async function syncDirectory(path, io, point) {
524
+ const before = await named(path);
525
+ insist(before.type === "directory", "persistence-uncertain");
526
+ const d = await io.open(path, readFlags | constants.O_DIRECTORY);
527
+ await withOriginalClose(
528
+ io,
529
+ d,
530
+ async () => {
531
+ insist(
532
+ sameFile(before, identity(await d.handle.stat({ bigint: true }))),
533
+ "persistence-uncertain"
534
+ );
535
+ await io.point(point);
536
+ await d.handle.sync();
537
+ insist(sameFile(before, await named(path)), "persistence-uncertain");
538
+ },
539
+ "directory-close"
540
+ );
541
+ }
542
+ async function writeAll(d, bytes, io, point) {
543
+ const cap = io.hooks.writeChunkBytes ?? 65536;
544
+ insist(Number.isSafeInteger(cap) && cap > 0 && cap <= 65536);
545
+ let offset = 0;
546
+ while (offset < bytes.length) {
547
+ await io.point(point);
548
+ const { bytesWritten } = await d.handle.write(
549
+ bytes,
550
+ offset,
551
+ Math.min(cap, bytes.length - offset),
552
+ offset
553
+ );
554
+ insist(
555
+ bytesWritten > 0 && bytesWritten <= Math.min(cap, bytes.length - offset),
556
+ "persistence-uncertain"
557
+ );
558
+ offset += bytesWritten;
559
+ }
560
+ }
561
+ var sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
562
+ function checkDepth(bytes) {
563
+ const textValue = bytes.toString("utf8");
564
+ insist(Buffer.from(textValue).equals(bytes));
565
+ let depth = 0, quoted = false, escaped = false;
566
+ for (const char of textValue) {
567
+ if (quoted) {
568
+ if (escaped) escaped = false;
569
+ else if (char === "\\") escaped = true;
570
+ else if (char === '"') quoted = false;
571
+ } else if (char === '"') quoted = true;
572
+ else if (char === "{" || char === "[")
573
+ insist(++depth <= JOURNAL_LIMITS.depth, "capacity-exceeded");
574
+ else if (char === "}" || char === "]") insist(--depth >= 0);
575
+ }
576
+ insist(!quoted && depth === 0);
577
+ return textValue;
578
+ }
579
+ async function readSnapshot(l, root, io) {
580
+ await assertRoot(l, root, io);
581
+ const path = join(rootPath(l), "snapshot.json");
582
+ const before = await maybe(path);
583
+ if (!before) {
584
+ await assertRoot(l, root, io);
585
+ insist(await maybe(path) === null, "read-uncertain");
586
+ return null;
587
+ }
588
+ insist(
589
+ before.type === "file" && BigInt(before.size) <= BigInt(JOURNAL_LIMITS.bytes) && before.uid === root.uid && (before.mode & 63) === 0,
590
+ "read-uncertain"
591
+ );
592
+ await io.point("reader-open");
593
+ const d = await io.open(path, readFlags);
594
+ const result = await withOriginalClose(
595
+ io,
596
+ d,
597
+ async () => {
598
+ insist(sameFile(before, identity(await d.handle.stat({ bigint: true }))), "read-uncertain");
599
+ const buffer = Buffer.alloc(Math.min(JOURNAL_LIMITS.bytes + 1, Number(before.size) + 1));
600
+ let offset = 0;
601
+ while (offset < buffer.length) {
602
+ await io.point("reader-read");
603
+ const { bytesRead } = await d.handle.read(
604
+ buffer,
605
+ offset,
606
+ Math.min(65536, buffer.length - offset),
607
+ offset
608
+ );
609
+ if (!bytesRead) break;
610
+ offset += bytesRead;
611
+ }
612
+ insist(offset === Number(before.size), "read-uncertain");
613
+ const bytes = buffer.subarray(0, offset);
614
+ const raw = checkDepth(bytes);
615
+ const snapshot = validateJournalSnapshot(JSON.parse(raw));
616
+ insist(recordedJSON(snapshot) === raw);
617
+ insist(sameJournalBinding(snapshot.binding, l.binding), "boot-changed");
618
+ insist(
619
+ sameFile(before, identity(await d.handle.stat({ bigint: true }))) && sameFile(before, await named(path)),
620
+ "read-uncertain"
621
+ );
622
+ return { snapshot, digest: sha(bytes), identity: before };
623
+ },
624
+ "reader-close"
625
+ );
626
+ insist(sameFile(before, await named(path)), "read-uncertain");
627
+ await assertRoot(l, root, io);
628
+ return result;
629
+ }
630
+ var ticketBrand = /* @__PURE__ */ Symbol("journal-successor");
631
+ var tickets = /* @__PURE__ */ new WeakMap();
632
+ async function openJournalWriter(options) {
633
+ const io = new Files(options);
634
+ let marker;
635
+ let l, root, prior;
636
+ let writerIdentity, markerPin;
637
+ const markerName = "writer.json", temporaryName = "snapshot.tmp";
638
+ let markerAcquired = false;
639
+ try {
640
+ l = location(options);
641
+ writerIdentity = frozen(JournalWriterSchema.parse(copyJournalData(options.writer)));
642
+ const expected = z.discriminatedUnion("kind", [
643
+ z.object({ kind: z.literal("absent") }).strict(),
644
+ z.object({ kind: z.literal("recorded"), sequence: counter, digest: digestSchema }).strict()
645
+ ]).parse(copyJournalData(options.prior));
646
+ await assertParent(l, io);
647
+ const ticket = options.ticket && tickets.get(options.ticket);
648
+ if (options.ticket) {
649
+ insist(
650
+ ticket && !ticket.used && sameJournalBinding(ticket.location.binding, l.binding) && ticket.location.parentDirectory === l.parentDirectory && sameDirectory(ticket.location.parentIdentity, l.parentIdentity) && recordedJSON(ticket.writer) === recordedJSON(writerIdentity),
651
+ "sequence-gap"
652
+ );
653
+ ticket.used = true;
654
+ } else insist(expected.kind === "absent", "custody-pending");
655
+ let initial = await maybe(rootPath(l));
656
+ if (initial && !ticket) {
657
+ if (await maybe(join(rootPath(l), markerName))) {
658
+ const busy = new Error("journal writer exists");
659
+ busy.code = "EEXIST";
660
+ throw busy;
661
+ }
662
+ throw new ProcessJournalError("custody-pending");
663
+ }
664
+ if (!initial) {
665
+ insist(!ticket && expected.kind === "absent", "sequence-gap");
666
+ await fs.mkdir(rootPath(l), { mode: 448 });
667
+ initial = await named(rootPath(l));
668
+ insist(
669
+ initial.type === "directory" && initial.uid === l.parentIdentity.uid && (initial.mode & 63) === 0
670
+ );
671
+ await io.point("namespace-created");
672
+ await assertRoot(l, initial, io);
673
+ await syncDirectory(rootPath(l), io, "namespace-sync");
674
+ await syncDirectory(l.parentDirectory, io, "parent-sync");
675
+ }
676
+ insist(
677
+ initial.type === "directory" && initial.uid === l.parentIdentity.uid && (initial.mode & 63) === 0,
678
+ "read-uncertain"
679
+ );
680
+ root = initial;
681
+ if (ticket) insist(sameDirectory(root, ticket.root), "read-uncertain");
682
+ await assertRoot(l, root, io);
683
+ await io.point("marker-open");
684
+ await assertRoot(l, root, io);
685
+ marker = await io.open(join(rootPath(l), markerName), createFlags);
686
+ markerAcquired = true;
687
+ prior = await readSnapshot(l, root, io);
688
+ if (expected.kind === "absent") insist(prior === null, "sequence-gap");
689
+ else
690
+ insist(
691
+ prior && prior.digest === expected.digest && prior.snapshot.sequence === expected.sequence && ticket && ticket.prior?.digest === prior.digest,
692
+ "sequence-gap"
693
+ );
694
+ insist(await maybe(join(rootPath(l), temporaryName)) === null, "persistence-uncertain");
695
+ const ownerBytes = Buffer.from(
696
+ recordedJSON({
697
+ schemaVersion: 1,
698
+ binding: l.binding,
699
+ writer: writerIdentity,
700
+ phase: "allocated",
701
+ sequence: prior?.snapshot.sequence ?? null,
702
+ digest: prior?.digest ?? null
703
+ })
704
+ );
705
+ insist(ownerBytes.length <= JOURNAL_LIMITS.writerBytes, "capacity-exceeded");
706
+ await writeAll(marker, ownerBytes, io, "marker-write");
707
+ await io.point("marker-sync");
708
+ await marker.handle.sync();
709
+ markerPin = identity(await marker.handle.stat({ bigint: true }));
710
+ insist(sameFile(markerPin, await named(join(rootPath(l), markerName))));
711
+ await syncDirectory(rootPath(l), io, "namespace-sync");
712
+ await syncDirectory(l.parentDirectory, io, "parent-sync");
713
+ await assertRoot(l, root, io);
714
+ } catch (error) {
715
+ await io.drain();
716
+ const busy = !markerAcquired && error?.code === "EEXIST";
717
+ return Object.freeze({
718
+ state: busy ? "busy" : markerAcquired ? "uncertain" : "refused",
719
+ cause: error instanceof ProcessJournalError ? error.causeCode : busy ? "custody-pending" : "persistence-uncertain",
720
+ custody: io.custody()
721
+ });
722
+ }
723
+ const markerOriginal = marker;
724
+ let accepting = true, firstCause = null, pending = 0;
725
+ let tail = Promise.resolve();
726
+ let closePromise = null;
727
+ let handoffPromise = null;
728
+ const heldCalls = /* @__PURE__ */ new Set();
729
+ const custody = () => {
730
+ const records = [io.custody(), ...[...heldCalls].map((call) => call.custody())];
731
+ return Object.freeze({
732
+ opens: records.reduce((n, r) => n + r.opens, 0),
733
+ closesAttempted: records.reduce((n, r) => n + r.closesAttempted, 0),
734
+ closed: records.reduce((n, r) => n + r.closed, 0),
735
+ held: records.reduce((n, r) => n + r.held, 0)
736
+ });
737
+ };
738
+ const fail = (cause) => {
739
+ firstCause ??= cause;
740
+ accepting = false;
741
+ };
742
+ const markerCurrent = async (call) => {
743
+ insist(firstCause === null, firstCause ?? "persistence-uncertain");
744
+ await assertRoot(l, root, call);
745
+ insist(firstCause === null, firstCause ?? "persistence-uncertain");
746
+ insist(
747
+ sameFile(markerPin, identity(await markerOriginal.handle.stat({ bigint: true }))) && sameFile(markerPin, await named(join(rootPath(l), markerName))),
748
+ "persistence-uncertain"
749
+ );
750
+ };
751
+ const uncertain = (call, phase, nextDigest) => Object.freeze({
752
+ state: "uncertain",
753
+ cause: firstCause ?? "persistence-uncertain",
754
+ phase,
755
+ oldDigest: prior?.digest ?? null,
756
+ newDigest: nextDigest,
757
+ custody: call.custody()
758
+ });
759
+ const commit = async (input) => {
760
+ const call = new Files(options);
761
+ let phase = "validation", nextDigest = null;
762
+ try {
763
+ insist(firstCause === null, firstCause ?? "persistence-uncertain");
764
+ const next = validateJournalSnapshot(input);
765
+ insist(
766
+ sameJournalBinding(next.binding, l.binding) && recordedJSON(next.writer) === recordedJSON(writerIdentity),
767
+ "sequence-gap"
768
+ );
769
+ if (prior) {
770
+ const previous = prior.snapshot;
771
+ if (previous.writer.epoch === writerIdentity.epoch) successor(previous, next);
772
+ else {
773
+ insist(
774
+ previous.writer.epoch < Number.MAX_SAFE_INTEGER && writerIdentity.epoch === previous.writer.epoch + 1,
775
+ "sequence-gap"
776
+ );
777
+ successor(validateJournalSnapshot({ ...previous, writer: writerIdentity }), next);
778
+ }
779
+ } else insist(next.sequence === 0, "sequence-gap");
780
+ const bytes = Buffer.from(recordedJSON(next));
781
+ nextDigest = sha(bytes);
782
+ await markerCurrent(call);
783
+ const current = await readSnapshot(l, root, call);
784
+ insist(
785
+ (current?.digest ?? null) === (prior?.digest ?? null) && (!current || !prior || sameFile(current.identity, prior.identity)),
786
+ "persistence-uncertain"
787
+ );
788
+ const temporary = join(rootPath(l), temporaryName);
789
+ insist(await maybe(temporary) === null, "persistence-uncertain");
790
+ phase = "temporary";
791
+ await call.point("payload-open");
792
+ await markerCurrent(call);
793
+ const d = await call.open(temporary, createFlags);
794
+ const payloadPin = await withOriginalClose(
795
+ call,
796
+ d,
797
+ async () => {
798
+ await writeAll(d, bytes, call, "payload-write");
799
+ await call.point("payload-sync");
800
+ await d.handle.sync();
801
+ const pin = identity(await d.handle.stat({ bigint: true }));
802
+ insist(
803
+ pin.type === "file" && Number(pin.size) === bytes.length && sameFile(pin, await named(temporary)),
804
+ "persistence-uncertain"
805
+ );
806
+ return pin;
807
+ },
808
+ "payload-close"
809
+ );
810
+ await markerCurrent(call);
811
+ insist(sameFile(payloadPin, await named(temporary)), "persistence-uncertain");
812
+ const destination = join(rootPath(l), "snapshot.json"), namedPrior = await maybe(destination);
813
+ insist(
814
+ prior ? namedPrior && sameFile(namedPrior, prior.identity) : namedPrior === null,
815
+ "persistence-uncertain"
816
+ );
817
+ phase = "rename-pending";
818
+ await call.point("snapshot-rename");
819
+ await markerCurrent(call);
820
+ const finalPrior = await maybe(destination);
821
+ insist(
822
+ prior ? finalPrior && sameFile(finalPrior, prior.identity) : finalPrior === null,
823
+ "persistence-uncertain"
824
+ );
825
+ await fs.rename(temporary, destination);
826
+ phase = "renamed";
827
+ await syncDirectory(rootPath(l), call, "snapshot-directory-sync");
828
+ await syncDirectory(l.parentDirectory, call, "parent-sync");
829
+ await markerCurrent(call);
830
+ const read = await readSnapshot(l, root, call);
831
+ insist(read && read.digest === nextDigest, "persistence-uncertain");
832
+ insist(await call.drain(), "custody-pending");
833
+ prior = read;
834
+ return Object.freeze({
835
+ state: "durable-recorded",
836
+ sequence: next.sequence,
837
+ digest: nextDigest,
838
+ custody: call.custody()
839
+ });
840
+ } catch (error) {
841
+ fail(error instanceof ProcessJournalError ? error.causeCode : "persistence-uncertain");
842
+ if (!await call.drain()) {
843
+ heldCalls.add(call);
844
+ fail("custody-pending");
845
+ }
846
+ return uncertain(call, phase, nextDigest);
847
+ }
848
+ };
849
+ const owner = Object.freeze({
850
+ commitSnapshot(input) {
851
+ if (!accepting || pending >= JOURNAL_LIMITS.pending) {
852
+ if (pending >= JOURNAL_LIMITS.pending) fail("capacity-exceeded");
853
+ return Promise.resolve(uncertain(new Files(), "admission", null));
854
+ }
855
+ let snapshot;
856
+ try {
857
+ snapshot = validateJournalSnapshot(input);
858
+ } catch (error) {
859
+ fail(error instanceof ProcessJournalError ? error.causeCode : "frame-invalid");
860
+ return Promise.resolve(uncertain(new Files(), "validation", null));
861
+ }
862
+ pending++;
863
+ const operation = tail.then(() => commit(snapshot));
864
+ tail = operation.then(
865
+ () => {
866
+ pending--;
867
+ },
868
+ () => {
869
+ pending--;
870
+ fail("persistence-uncertain");
871
+ }
872
+ );
873
+ return operation;
874
+ },
875
+ handoff(nextWriter) {
876
+ if (handoffPromise) return handoffPromise;
877
+ if (closePromise || !accepting)
878
+ return Promise.resolve(
879
+ Object.freeze({
880
+ state: "uncertain",
881
+ cause: firstCause ?? "custody-pending",
882
+ custody: custody()
883
+ })
884
+ );
885
+ accepting = false;
886
+ let proposedWriter;
887
+ try {
888
+ proposedWriter = frozen(JournalWriterSchema.parse(copyJournalData(nextWriter)));
889
+ } catch {
890
+ fail("frame-invalid");
891
+ handoffPromise = (async () => {
892
+ await tail;
893
+ await io.drain();
894
+ return Object.freeze({
895
+ state: "uncertain",
896
+ cause: firstCause,
897
+ custody: custody()
898
+ });
899
+ })();
900
+ return handoffPromise;
901
+ }
902
+ handoffPromise = (async () => {
903
+ await tail;
904
+ const call = new Files(options);
905
+ try {
906
+ insist(firstCause === null, firstCause ?? "persistence-uncertain");
907
+ const next = proposedWriter;
908
+ insist(
909
+ writerIdentity.epoch < Number.MAX_SAFE_INTEGER && next.epoch === writerIdentity.epoch + 1,
910
+ "sequence-gap"
911
+ );
912
+ await markerCurrent(call);
913
+ const bytes = Buffer.from(
914
+ recordedJSON({
915
+ schemaVersion: 1,
916
+ binding: l.binding,
917
+ writer: writerIdentity,
918
+ phase: "handoff",
919
+ successor: next,
920
+ sequence: prior?.snapshot.sequence ?? null,
921
+ digest: prior?.digest ?? null
922
+ })
923
+ );
924
+ insist(bytes.length <= JOURNAL_LIMITS.writerBytes, "capacity-exceeded");
925
+ await call.point("handoff-write");
926
+ await markerOriginal.handle.truncate(0);
927
+ await writeAll(markerOriginal, bytes, call, "marker-write");
928
+ await call.point("marker-sync");
929
+ await markerOriginal.handle.sync();
930
+ markerPin = identity(await markerOriginal.handle.stat({ bigint: true }));
931
+ await syncDirectory(rootPath(l), call, "namespace-sync");
932
+ await markerCurrent(call);
933
+ await io.close(markerOriginal, "marker-close");
934
+ insist(await io.drain(), "custody-pending");
935
+ insist(
936
+ sameFile(markerPin, await named(join(rootPath(l), markerName))),
937
+ "persistence-uncertain"
938
+ );
939
+ await call.point("marker-unlink");
940
+ await assertRoot(l, root, call);
941
+ insist(
942
+ sameFile(markerPin, await named(join(rootPath(l), markerName))),
943
+ "persistence-uncertain"
944
+ );
945
+ await fs.unlink(join(rootPath(l), markerName));
946
+ await syncDirectory(rootPath(l), call, "handoff-directory-sync");
947
+ await syncDirectory(l.parentDirectory, call, "parent-sync");
948
+ insist(await maybe(join(rootPath(l), markerName)) === null, "persistence-uncertain");
949
+ insist(await call.drain(), "custody-pending");
950
+ const ticket = Object.freeze({ [ticketBrand]: true });
951
+ tickets.set(ticket, { location: l, root, prior, writer: next, used: false });
952
+ return Object.freeze({
953
+ state: "handed-off",
954
+ ticket,
955
+ sequence: prior?.snapshot.sequence ?? null,
956
+ digest: prior?.digest ?? null,
957
+ custody: custody()
958
+ });
959
+ } catch (error) {
960
+ fail(error instanceof ProcessJournalError ? error.causeCode : "persistence-uncertain");
961
+ if (!await call.drain()) heldCalls.add(call);
962
+ await io.drain();
963
+ return Object.freeze({ state: "uncertain", cause: firstCause, custody: custody() });
964
+ }
965
+ })();
966
+ return handoffPromise;
967
+ },
968
+ close() {
969
+ if (closePromise) return closePromise;
970
+ accepting = false;
971
+ closePromise = (async () => {
972
+ if (handoffPromise) await handoffPromise;
973
+ else {
974
+ await tail;
975
+ try {
976
+ await io.close(markerOriginal, "marker-close");
977
+ } catch {
978
+ fail("custody-pending");
979
+ }
980
+ if (!await io.drain()) fail("custody-pending");
981
+ }
982
+ return Object.freeze(
983
+ firstCause ? { state: "uncertain", cause: firstCause, custody: custody() } : { state: "closed", custody: custody() }
984
+ );
985
+ })();
986
+ return closePromise;
987
+ }
988
+ });
989
+ return Object.freeze({ state: "allocated", writer: owner, custody: io.custody() });
990
+ }
991
+
992
+ // packages/browser/src/runtime/darwin-process-observer.ts
993
+ import { createHash as createHash2 } from "node:crypto";
994
+ import { constants as constants2 } from "node:fs";
995
+ import { open as open2, realpath, lstat as lstat2 } from "node:fs/promises";
996
+ import { spawn } from "node:child_process";
997
+ import { z as z2 } from "zod";
998
+ var decimal = z2.string().regex(/^(0|[1-9][0-9]{0,19})$/).refine(
999
+ (value) => /^(0|[1-9][0-9]{0,19})$/.test(value) && BigInt(value) <= 18446744073709551615n
1000
+ );
1001
+ var identity2 = z2.object({
1002
+ pid: z2.number().int().positive().max(2147483647),
1003
+ seconds: decimal,
1004
+ microseconds: decimal
1005
+ }).strict();
1006
+ var replySchema = z2.object({
1007
+ version: z2.literal(1),
1008
+ bootSeconds: decimal,
1009
+ bootMicroseconds: decimal,
1010
+ processes: z2.array(
1011
+ z2.discriminatedUnion("kind", [
1012
+ z2.object({
1013
+ kind: z2.literal("present"),
1014
+ identity: identity2,
1015
+ parentPid: z2.number().int().nonnegative().max(2147483647),
1016
+ zombie: z2.boolean()
1017
+ }).strict(),
1018
+ z2.object({ kind: z2.literal("absent"), pid: z2.number().int().positive().max(2147483647) }).strict(),
1019
+ z2.object({
1020
+ kind: z2.literal("unknown"),
1021
+ pid: z2.number().int().positive().max(2147483647),
1022
+ error: z2.number().int()
1023
+ }).strict()
1024
+ ])
1025
+ ).max(512)
1026
+ }).strict();
1027
+ var childrenSchema = replySchema.extend({
1028
+ parentBefore: identity2.nullable(),
1029
+ parentAfter: identity2.nullable(),
1030
+ complete: z2.boolean()
1031
+ }).strict();
1032
+ function parseDarwinChildrenBatch(bytes, parent) {
1033
+ if (bytes.byteLength > 256 * 1024) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1034
+ const batch = childrenSchema.parse(
1035
+ JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
1036
+ );
1037
+ if (BigInt(batch.bootMicroseconds) >= 1000000n)
1038
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1039
+ const pids = /* @__PURE__ */ new Set();
1040
+ for (const fact of batch.processes) {
1041
+ const pid = fact.kind === "present" ? fact.identity.pid : fact.pid;
1042
+ if (pids.has(pid)) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1043
+ pids.add(pid);
1044
+ if (fact.kind === "present") darwinBirth(fact.identity);
1045
+ }
1046
+ if (batch.complete && (!batch.parentBefore || !batch.parentAfter || darwinBirth(batch.parentBefore).birth !== parent.birth || batch.parentBefore.pid !== parent.pid || darwinBirth(batch.parentAfter).birth !== parent.birth || batch.parentAfter.pid !== parent.pid || batch.processes.some(
1047
+ (fact) => fact.kind !== "present" || fact.parentPid !== parent.pid || fact.identity.pid === parent.pid
1048
+ )))
1049
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1050
+ return batch;
1051
+ }
1052
+ function darwinBirth(value) {
1053
+ if (BigInt(value.microseconds) >= 1000000n) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1054
+ return Object.freeze({
1055
+ pid: value.pid,
1056
+ birth: `darwin-bsd-start:${value.seconds}:${value.microseconds}`
1057
+ });
1058
+ }
1059
+ function parseDarwinProcessBatch(bytes, requested) {
1060
+ if (bytes.byteLength > 256 * 1024) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1061
+ const batch = replySchema.parse(
1062
+ JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
1063
+ );
1064
+ if (BigInt(batch.bootMicroseconds) >= 1000000n || batch.processes.length !== requested.length)
1065
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1066
+ const remaining = new Set(requested);
1067
+ for (const fact of batch.processes) {
1068
+ const pid = fact.kind === "present" ? fact.identity.pid : fact.pid;
1069
+ if (!remaining.delete(pid)) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1070
+ if (fact.kind === "present") darwinBirth(fact.identity);
1071
+ }
1072
+ if (remaining.size) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1073
+ return batch;
1074
+ }
1075
+ var heldReads = /* @__PURE__ */ new Set();
1076
+ var heldChildren = /* @__PURE__ */ new Set();
1077
+ var readCustodyUncertain = false;
1078
+ function createDarwinProcessObserver(artifact) {
1079
+ const descriptor = Object.freeze({ ...artifact });
1080
+ const invoke = async (command, pids) => {
1081
+ if (readCustodyUncertain || process.platform !== "darwin" || !/^[a-f0-9]{64}$/.test(descriptor.sha256) || pids.length < 1 || pids.length > 512 || new Set(pids).size !== pids.length || pids.some((pid) => !Number.isSafeInteger(pid) || pid < 1 || pid > 2147483647))
1082
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1083
+ if (await realpath(descriptor.path) !== descriptor.path)
1084
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1085
+ const file = await open2(
1086
+ descriptor.path,
1087
+ constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK
1088
+ );
1089
+ heldReads.add(file);
1090
+ let primary, failed = false;
1091
+ try {
1092
+ const before = await file.stat({ bigint: true });
1093
+ if (!before.isFile() || before.size > 4n * 1024n * 1024n || (before.mode & 0o111n) === 0n)
1094
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1095
+ const hash = createHash2("sha256");
1096
+ const buffer = new Uint8Array(65536);
1097
+ let bytes = 0;
1098
+ for (; ; ) {
1099
+ const read = await file.read(
1100
+ buffer,
1101
+ 0,
1102
+ Math.min(buffer.length, 4 * 1024 * 1024 + 1 - bytes),
1103
+ null
1104
+ );
1105
+ if (!read.bytesRead) break;
1106
+ bytes += read.bytesRead;
1107
+ if (bytes > 4 * 1024 * 1024) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1108
+ hash.update(buffer.subarray(0, read.bytesRead));
1109
+ }
1110
+ const after = await file.stat({ bigint: true });
1111
+ const named2 = await lstat2(descriptor.path, { bigint: true });
1112
+ if (!named2.isFile() || named2.dev !== after.dev || named2.ino !== after.ino)
1113
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1114
+ if (hash.digest("hex") !== descriptor.sha256 || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)
1115
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1116
+ } catch (error) {
1117
+ primary = error;
1118
+ failed = true;
1119
+ }
1120
+ try {
1121
+ await file.close();
1122
+ heldReads.delete(file);
1123
+ } catch (error) {
1124
+ readCustodyUncertain = true;
1125
+ if (!failed) primary = error;
1126
+ failed = true;
1127
+ }
1128
+ if (failed) throw primary;
1129
+ if (readCustodyUncertain) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1130
+ const child = spawn(descriptor.path, [command, ...pids.map(String)], {
1131
+ shell: false,
1132
+ detached: false,
1133
+ stdio: ["ignore", "pipe", "pipe"],
1134
+ env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" }
1135
+ });
1136
+ heldChildren.add(child);
1137
+ let failedChild = false;
1138
+ const terminal = new Promise((done) => {
1139
+ child.on("error", () => {
1140
+ failedChild = true;
1141
+ });
1142
+ child.once("close", (code2) => done(code2));
1143
+ });
1144
+ const pipeReturns = [
1145
+ { eof: false, closed: false },
1146
+ { eof: false, closed: false }
1147
+ ];
1148
+ const drain = async (stream, duty) => {
1149
+ if (!stream) {
1150
+ failedChild = true;
1151
+ return new Uint8Array();
1152
+ }
1153
+ stream.once("end", () => {
1154
+ duty.eof = true;
1155
+ });
1156
+ stream.once("close", () => {
1157
+ duty.closed = true;
1158
+ });
1159
+ const chunks = [];
1160
+ let bytes = 0;
1161
+ for await (const value of stream) {
1162
+ const chunk = Buffer.from(value);
1163
+ bytes += chunk.length;
1164
+ if (bytes <= 256 * 1024) chunks.push(chunk);
1165
+ else failedChild = true;
1166
+ }
1167
+ if (!stream.readableEnded || !duty.eof) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1168
+ return Buffer.concat(chunks);
1169
+ };
1170
+ const streams = await Promise.allSettled([
1171
+ drain(child.stdout, pipeReturns[0]),
1172
+ drain(child.stderr, pipeReturns[1])
1173
+ ]);
1174
+ const code = await terminal;
1175
+ const pipesReturned = streams.every((stream) => stream.status === "fulfilled") && pipeReturns.every((duty) => duty.eof && duty.closed);
1176
+ if (pipesReturned) heldChildren.delete(child);
1177
+ else readCustodyUncertain = true;
1178
+ if (readCustodyUncertain || failedChild || code !== 0 || !pipesReturned)
1179
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1180
+ const stdout = streams[0];
1181
+ if (stdout.status !== "fulfilled") throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1182
+ return stdout.value;
1183
+ };
1184
+ return Object.freeze({
1185
+ async inspect(pids) {
1186
+ return parseDarwinProcessBatch(await invoke("inspect", pids), pids);
1187
+ },
1188
+ async children(parent) {
1189
+ return parseDarwinChildrenBatch(await invoke("children", [parent.pid]), parent);
1190
+ }
1191
+ });
1192
+ }
1193
+
1194
+ // packages/browser/src/runtime/darwin-owned-child.ts
1195
+ import { spawn as spawn2 } from "node:child_process";
1196
+ var returnBrand = /* @__PURE__ */ Symbol("Darwin original child return");
1197
+ var ownership = /* @__PURE__ */ new WeakMap();
1198
+ var returns = /* @__PURE__ */ new WeakMap();
1199
+ var retained = /* @__PURE__ */ new Set();
1200
+ function acceptsDarwinOwnedChildReturn(child, returned) {
1201
+ return !!returned && typeof returned === "object" && ownership.has(child) && returns.get(returned) === ownership.get(child);
1202
+ }
1203
+ function createDarwinOwnedChildLauncher(options) {
1204
+ const observer = createDarwinProcessObserver(options.artifact);
1205
+ const manager = Object.freeze({ ...options.manager });
1206
+ return Object.freeze({
1207
+ async launch(command) {
1208
+ if (process.platform !== "darwin" || process.pid === manager.pid)
1209
+ throw new Error("SUPERVISOR_PROCESS_REQUIRED");
1210
+ const initial = await observer.inspect([process.pid, manager.pid]);
1211
+ const supervisor = initial.processes.find(
1212
+ (fact) => fact.kind === "present" && fact.identity.pid === process.pid
1213
+ );
1214
+ const observedManager = initial.processes.find(
1215
+ (fact) => fact.kind === "present" && fact.identity.pid === manager.pid
1216
+ );
1217
+ if (!supervisor || supervisor.kind !== "present" || supervisor.zombie || !observedManager || observedManager.kind !== "present" || observedManager.zombie || !sameProcess(darwinBirth(observedManager.identity), manager))
1218
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1219
+ const boot = `${initial.bootSeconds}:${initial.bootMicroseconds}`;
1220
+ const state = { child: null, pending: true, firstCause: null };
1221
+ retained.add(state);
1222
+ const fail = (cause) => {
1223
+ state.firstCause ??= cause;
1224
+ };
1225
+ let child;
1226
+ try {
1227
+ child = spawn2(command.executable, [...command.argv], {
1228
+ cwd: command.cwd,
1229
+ env: { ...command.env },
1230
+ shell: false,
1231
+ detached: false,
1232
+ stdio: command.ipc ? ["ignore", "pipe", "pipe", "ipc"] : ["ignore", "pipe", "pipe"]
1233
+ });
1234
+ state.child = child;
1235
+ } catch (error) {
1236
+ fail("CHILD_ACQUISITION_UNCERTAIN");
1237
+ throw error;
1238
+ }
1239
+ let exitObserved = false, closeObserved = false;
1240
+ let exitCode = null, signal = null;
1241
+ const terminal = new Promise((resolve) => {
1242
+ child.on("error", () => fail("CHILD_ERROR"));
1243
+ child.once("exit", (code, killedBy) => {
1244
+ exitObserved = true;
1245
+ exitCode = code;
1246
+ signal = killedBy;
1247
+ if (killedBy) fail("CHILD_SIGNALED");
1248
+ else if (code !== 0) fail("CHILD_EXIT_FAILED");
1249
+ });
1250
+ child.once("close", (code, killedBy) => {
1251
+ closeObserved = true;
1252
+ if (!exitObserved || code !== exitCode || killedBy !== signal)
1253
+ fail("CHILD_TERMINAL_UNCERTAIN");
1254
+ resolve();
1255
+ });
1256
+ });
1257
+ const drain = (original) => {
1258
+ let eof = false, closed = false, overflow = false;
1259
+ const chunks = [];
1260
+ let retainedBytes = 0;
1261
+ const completion2 = new Promise((resolve) => {
1262
+ if (!original) {
1263
+ fail("CHILD_PIPE_UNAVAILABLE");
1264
+ resolve(new Uint8Array());
1265
+ return;
1266
+ }
1267
+ original.once("end", () => {
1268
+ eof = true;
1269
+ });
1270
+ original.on("error", () => fail("CHILD_PIPE_ERROR"));
1271
+ original.once("close", () => {
1272
+ closed = true;
1273
+ if (!eof) fail("CHILD_PIPE_EOF_UNAVAILABLE");
1274
+ try {
1275
+ resolve(Buffer.concat(chunks));
1276
+ } catch {
1277
+ fail("CHILD_PIPE_RETENTION_UNAVAILABLE");
1278
+ resolve(new Uint8Array());
1279
+ }
1280
+ });
1281
+ original.on("data", (value) => {
1282
+ if (overflow) return;
1283
+ if (value.byteLength > 256 * 1024 - retainedBytes) {
1284
+ overflow = true;
1285
+ fail("CHILD_PIPE_OVERFLOW");
1286
+ return;
1287
+ }
1288
+ try {
1289
+ const copy = Uint8Array.from(value);
1290
+ retainedBytes += copy.byteLength;
1291
+ chunks.push(copy);
1292
+ } catch {
1293
+ overflow = true;
1294
+ fail("CHILD_PIPE_RETENTION_UNAVAILABLE");
1295
+ }
1296
+ });
1297
+ });
1298
+ return { completion: completion2, complete: () => eof && closed };
1299
+ };
1300
+ const stdout = drain(child.stdout), stderr = drain(child.stderr);
1301
+ const identity4 = (async () => {
1302
+ if (!child.pid) throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1303
+ const batch = await observer.inspect([process.pid, child.pid]);
1304
+ const parent = batch.processes.find(
1305
+ (fact2) => fact2.kind === "present" && fact2.identity.pid === process.pid
1306
+ );
1307
+ const fact = batch.processes.find(
1308
+ (fact2) => fact2.kind === "present" && fact2.identity.pid === child.pid
1309
+ );
1310
+ if (`${batch.bootSeconds}:${batch.bootMicroseconds}` !== boot || !parent || parent.kind !== "present" || parent.zombie || !sameProcess(darwinBirth(parent.identity), darwinBirth(supervisor.identity)) || !fact || fact.kind !== "present" || fact.zombie || fact.parentPid !== process.pid)
1311
+ throw new Error("PROCESS_OBSERVATION_UNAVAILABLE");
1312
+ return Object.freeze(darwinBirth(fact.identity));
1313
+ })();
1314
+ void identity4.catch(() => fail("CHILD_BIRTH_UNAVAILABLE"));
1315
+ let token = null;
1316
+ const completion = (async () => {
1317
+ const [out, err] = await Promise.all([stdout.completion, stderr.completion, terminal]);
1318
+ let birth = null;
1319
+ try {
1320
+ birth = await identity4;
1321
+ } catch {
1322
+ fail("CHILD_BIRTH_UNAVAILABLE");
1323
+ }
1324
+ if (!exitObserved || !closeObserved || !stdout.complete() || !stderr.complete())
1325
+ fail("CHILD_RETURN_UNCERTAIN");
1326
+ if (birth) {
1327
+ try {
1328
+ const batch = await observer.inspect([birth.pid]);
1329
+ if (`${batch.bootSeconds}:${batch.bootMicroseconds}` !== boot || batch.processes[0]?.kind !== "absent")
1330
+ fail("CHILD_NATIVE_RETURN_UNAVAILABLE");
1331
+ } catch {
1332
+ fail("CHILD_NATIVE_RETURN_UNAVAILABLE");
1333
+ }
1334
+ }
1335
+ if (state.firstCause === null && birth) {
1336
+ token = Object.freeze({ [returnBrand]: true });
1337
+ returns.set(token, state);
1338
+ state.pending = false;
1339
+ retained.delete(state);
1340
+ }
1341
+ return Object.freeze({
1342
+ exitCode,
1343
+ signal,
1344
+ firstCause: state.firstCause,
1345
+ stdout: out,
1346
+ stderr: err
1347
+ });
1348
+ })();
1349
+ const handle = Object.freeze({
1350
+ child,
1351
+ identity: () => identity4,
1352
+ completion: () => completion,
1353
+ returned: async () => {
1354
+ await completion;
1355
+ return token;
1356
+ },
1357
+ custody: () => Object.freeze({ pending: state.pending, firstCause: state.firstCause })
1358
+ });
1359
+ ownership.set(handle, state);
1360
+ return handle;
1361
+ }
1362
+ });
1363
+ }
1364
+
1365
+ // packages/browser/src/runtime/darwin-journal-observer.ts
1366
+ async function observeDarwinJournal(options) {
1367
+ let current = validateJournalSnapshot(options.initial);
1368
+ if (current.sequence !== 0 || current.root.kind !== "pending" || current.writer.kind !== "observer" || current.binding.bootScope.kind !== "observed" || !options.observer.children || options.exitingObserver && (!options.logicalManager || options.exitingObserver.pid !== process.pid || !sameProcess(options.exitingObserver, current.binding.manager)) || !Number.isFinite(options.endMonotonic) || options.continuousWindowMilliseconds !== void 0 && (!Number.isSafeInteger(options.continuousWindowMilliseconds) || options.continuousWindowMilliseconds < 100 || options.continuousWindowMilliseconds > 6e5) || !Number.isFinite(options.maxGap) || options.maxGap <= 0)
1369
+ return "uncertain";
1370
+ let currentWindowEnd = options.endMonotonic;
1371
+ let faultReported = false;
1372
+ let enumerationClosed = false;
1373
+ const reportFault = async () => {
1374
+ if (options.continuousWindowMilliseconds === void 0 || faultReported) return;
1375
+ faultReported = true;
1376
+ await options.onObservationFault?.();
1377
+ };
1378
+ const opened = await openJournalWriter({
1379
+ ...options.location,
1380
+ writer: current.writer,
1381
+ prior: { kind: "absent" }
1382
+ });
1383
+ if (opened.state !== "allocated") return "uncertain";
1384
+ let result = "uncertain";
1385
+ let refusalCause = "observer-lost";
1386
+ const gap = (next, cause, identity4 = null) => {
1387
+ const prior = next.gaps.find((value) => value.cause === cause);
1388
+ if (prior) prior.count = Math.min(Number.MAX_SAFE_INTEGER, prior.count + 1);
1389
+ else
1390
+ next.gaps.push({
1391
+ cause,
1392
+ identity: identity4,
1393
+ firstSequence: next.sequence,
1394
+ count: 1
1395
+ });
1396
+ next.firstCause ??= { cause, sequence: next.sequence };
1397
+ };
1398
+ const checkBoot = (batch) => current.binding.bootScope.kind === "observed" && current.binding.bootScope.value === `darwin-boot:${batch.bootSeconds}:${batch.bootMicroseconds}`;
1399
+ try {
1400
+ if ((await opened.writer.commitSnapshot(current)).state !== "durable-recorded")
1401
+ throw new Error("JOURNAL_UNCERTAIN");
1402
+ const owner = await options.observer.inspect([current.binding.manager.pid]);
1403
+ const ownerFact = owner.processes[0];
1404
+ if (!checkBoot(owner) || ownerFact?.kind !== "present" || ownerFact.zombie || !sameProcess(darwinBirth(ownerFact.identity), current.binding.manager)) {
1405
+ refusalCause = checkBoot(owner) ? "identity-unknown" : "boot-changed";
1406
+ throw new Error("OWNER_UNAVAILABLE");
1407
+ }
1408
+ await options.onEnrolled?.();
1409
+ const root = await options.root;
1410
+ const supervisor = options.rootSupervisor?.();
1411
+ const selectedRoot = supervisor ?? root;
1412
+ if (!root && options.endBrowser?.() && options.launchNotEntered?.()) {
1413
+ const ended = copyJournalData(current);
1414
+ ended.sequence++;
1415
+ ended.phase = "observation-ended";
1416
+ ended.root = { kind: "absent-before-launch" };
1417
+ ended.observationWindow = {
1418
+ ...current.observationWindow,
1419
+ startSequence: ended.sequence,
1420
+ checkpointSequence: ended.sequence,
1421
+ endSequence: ended.sequence
1422
+ };
1423
+ if ((await opened.writer.commitSnapshot(ended)).state !== "durable-recorded")
1424
+ throw new Error();
1425
+ current = validateJournalSnapshot(ended);
1426
+ result = "campaign-closed";
1427
+ } else if (!root) {
1428
+ refusalCause = "root-pending";
1429
+ throw new Error("ROOT_UNAVAILABLE");
1430
+ }
1431
+ if (root)
1432
+ for (; ; ) {
1433
+ const start = options.monotonicNow();
1434
+ if (!Number.isFinite(start) || start >= currentWindowEnd) {
1435
+ result = "retained";
1436
+ break;
1437
+ }
1438
+ const next = copyJournalData(current);
1439
+ next.sequence++;
1440
+ const window = {
1441
+ startSequence: next.sequence,
1442
+ checkpointSequence: next.sequence,
1443
+ endSequence: next.sequence,
1444
+ startMonotonic: start,
1445
+ endMonotonic: start
1446
+ };
1447
+ next.observationWindow = window;
1448
+ if (start - current.observationWindow.endMonotonic > options.maxGap)
1449
+ gap(next, "observer-lost");
1450
+ const batch = await options.observer.inspect([
1451
+ .../* @__PURE__ */ new Set([
1452
+ ...current.retainedIdentities.map((value) => value.identity.pid),
1453
+ ...options.logicalManager ? [options.logicalManager.pid] : []
1454
+ ])
1455
+ ]);
1456
+ const validBoot = checkBoot(batch);
1457
+ if (!validBoot) gap(next, "boot-changed");
1458
+ const facts = new Map(
1459
+ batch.processes.map((fact) => [
1460
+ fact.kind === "present" ? fact.identity.pid : fact.pid,
1461
+ fact
1462
+ ])
1463
+ );
1464
+ for (const retained2 of next.retainedIdentities) {
1465
+ const fact = facts.get(retained2.identity.pid);
1466
+ retained2.lastSeenSequence = next.sequence;
1467
+ if (!validBoot || !fact || fact.kind === "unknown") {
1468
+ retained2.lifecycle = "unknown";
1469
+ gap(next, "identity-unknown", retained2.identity);
1470
+ } else if (fact.kind === "absent") {
1471
+ retained2.lifecycle = "dead";
1472
+ retained2.currentParent = null;
1473
+ } else if (!sameProcess(darwinBirth(fact.identity), retained2.identity)) {
1474
+ retained2.lifecycle = "replacement";
1475
+ retained2.currentParent = null;
1476
+ } else if (fact.zombie) {
1477
+ const prior = current.retainedIdentities.find(
1478
+ (row) => sameProcess(row.identity, retained2.identity)
1479
+ );
1480
+ const parent = retained2.parent && facts.get(retained2.parent.pid);
1481
+ const parentKnown = parent?.kind === "absent" || parent?.kind === "present" && !parent.zombie && retained2.parent && sameProcess(darwinBirth(parent.identity), retained2.parent);
1482
+ if (retained2.role === "descendant" && retained2.association && retained2.parent && prior && (prior.lifecycle === "alive" || prior.lifecycle === "exited-unreaped") && parentKnown) {
1483
+ retained2.lifecycle = "exited-unreaped";
1484
+ retained2.currentParent = parent?.kind === "present" && fact.parentPid === parent.identity.pid ? retained2.parent : null;
1485
+ } else {
1486
+ gap(next, "custody-pending", retained2.identity);
1487
+ }
1488
+ } else if (retained2.lifecycle === "exited-unreaped") {
1489
+ retained2.lifecycle = "unknown";
1490
+ gap(next, "identity-unknown", retained2.identity);
1491
+ } else {
1492
+ retained2.lifecycle = "alive";
1493
+ const parent = facts.get(fact.parentPid);
1494
+ retained2.currentParent = parent?.kind === "present" ? darwinBirth(parent.identity) : null;
1495
+ }
1496
+ }
1497
+ const manager = next.retainedIdentities.find((value) => value.role === "manager");
1498
+ let ownerGone = manager.lifecycle === "dead" || manager.lifecycle === "replacement";
1499
+ if (options.logicalManager) {
1500
+ const ownerFact2 = facts.get(options.logicalManager.pid);
1501
+ ownerGone = ownerFact2?.kind === "absent" || ownerFact2?.kind === "present" && !sameProcess(darwinBirth(ownerFact2.identity), options.logicalManager);
1502
+ if (!ownerFact2 || ownerFact2.kind === "unknown" || ownerFact2.kind === "present" && ownerFact2.zombie)
1503
+ gap(next, "identity-unknown", options.logicalManager);
1504
+ }
1505
+ if (ownerGone) next.phase = "manager-lost";
1506
+ for (const parent of current.retainedIdentities.filter(
1507
+ (value) => value.lifecycle === "alive"
1508
+ )) {
1509
+ const now = next.retainedIdentities.find(
1510
+ (value) => sameProcess(value.identity, parent.identity)
1511
+ );
1512
+ if (next.gaps.length) break;
1513
+ if (now.lifecycle !== "alive") continue;
1514
+ const returnedRoot = options.originalRootReturned?.();
1515
+ if (returnedRoot && !sameProcess(returnedRoot, root)) {
1516
+ gap(next, "identity-unknown", root);
1517
+ break;
1518
+ }
1519
+ if (returnedRoot && current.root.kind === "attributed" && sameProcess(parent.identity, returnedRoot))
1520
+ continue;
1521
+ if (options.enumerationCloseRequested?.()) continue;
1522
+ let childFacts;
1523
+ if (parent.role === "manager") {
1524
+ if (current.root.kind === "attributed") continue;
1525
+ const before = facts.get(parent.identity.pid);
1526
+ const selected = await options.observer.inspect([selectedRoot.pid]);
1527
+ const afterBatch = await options.observer.inspect([parent.identity.pid]);
1528
+ const fact = selected.processes[0], after = afterBatch.processes[0];
1529
+ if (!checkBoot(selected) || !checkBoot(afterBatch) || before?.kind !== "present" || before.zombie || !sameProcess(darwinBirth(before.identity), parent.identity) || after?.kind !== "present" || after.zombie || !sameProcess(darwinBirth(after.identity), parent.identity) || fact?.kind !== "present" || fact.zombie || fact.parentPid !== parent.identity.pid || !sameProcess(darwinBirth(fact.identity), selectedRoot)) {
1530
+ gap(next, "association-missing", parent.identity);
1531
+ continue;
1532
+ }
1533
+ childFacts = [fact];
1534
+ } else {
1535
+ const children = await options.observer.children(parent.identity);
1536
+ if (!children.complete || !checkBoot(children)) {
1537
+ await options.onIncompleteChildren?.(parent.identity, children);
1538
+ gap(next, "association-missing", parent.identity);
1539
+ continue;
1540
+ }
1541
+ childFacts = children.processes;
1542
+ }
1543
+ for (const fact of childFacts) {
1544
+ if (fact.kind === "present" && fact.zombie) {
1545
+ const prior = current.retainedIdentities.find(
1546
+ (row) => sameProcess(row.identity, darwinBirth(fact.identity))
1547
+ );
1548
+ const retained2 = next.retainedIdentities.find(
1549
+ (row) => sameProcess(row.identity, darwinBirth(fact.identity))
1550
+ );
1551
+ if (prior && retained2?.lifecycle === "exited-unreaped" && retained2.role === "descendant" && retained2.parent && sameProcess(retained2.parent, parent.identity) && fact.parentPid === parent.identity.pid)
1552
+ continue;
1553
+ }
1554
+ if (fact.kind !== "present" || fact.zombie) {
1555
+ gap(next, "association-missing", parent.identity);
1556
+ continue;
1557
+ }
1558
+ const child = darwinBirth(fact.identity);
1559
+ if (parent.role === "manager" && !sameProcess(child, selectedRoot)) continue;
1560
+ if (next.retainedIdentities.some(
1561
+ (value) => processKey(value.identity) === processKey(child)
1562
+ ))
1563
+ continue;
1564
+ if (next.retainedIdentities.length >= 512) {
1565
+ gap(next, "capacity-exceeded");
1566
+ continue;
1567
+ }
1568
+ const relation = {
1569
+ ...window,
1570
+ endMonotonic: options.monotonicNow()
1571
+ };
1572
+ const association = {
1573
+ parentBefore: parent.identity,
1574
+ parentAfter: parent.identity,
1575
+ child,
1576
+ childParentPid: parent.identity.pid,
1577
+ window: relation,
1578
+ recordedSequence: next.sequence,
1579
+ parentDeathSequence: null
1580
+ };
1581
+ const isRoot = sameProcess(child, root);
1582
+ next.retainedIdentities.push({
1583
+ identity: child,
1584
+ role: isRoot ? "root" : "descendant",
1585
+ parent: parent.identity,
1586
+ association,
1587
+ currentParent: parent.identity,
1588
+ acquisitionEpoch: current.writer.epoch,
1589
+ firstSeenSequence: next.sequence,
1590
+ lastSeenSequence: next.sequence,
1591
+ relationWindow: relation,
1592
+ lifecycle: "alive"
1593
+ });
1594
+ if (isRoot) {
1595
+ next.root = { kind: "attributed", identity: child, association };
1596
+ if (next.phase === "allocated") next.phase = "observing";
1597
+ }
1598
+ }
1599
+ }
1600
+ const end = options.monotonicNow();
1601
+ window.endMonotonic = end;
1602
+ if (!Number.isFinite(end) || end < start || end >= currentWindowEnd || end - start > options.maxGap)
1603
+ gap(next, "observer-lost");
1604
+ const admittedGone = next.retainedIdentities.every(
1605
+ (value) => value.lifecycle === "dead" || value.lifecycle === "replacement" || options.exitingObserver && sameProcess(value.identity, options.exitingObserver) || options.endBrowser?.() && value.role === "manager" && value.lifecycle === "alive"
1606
+ ) && (!options.logicalManager || ownerGone || options.endBrowser?.());
1607
+ const gone = next.root.kind === "attributed" && admittedGone;
1608
+ if (gone) next.phase = "observation-ended";
1609
+ const commit = await opened.writer.commitSnapshot(next);
1610
+ if (commit.state !== "durable-recorded") {
1611
+ result = "uncertain";
1612
+ break;
1613
+ }
1614
+ current = validateJournalSnapshot(next);
1615
+ if (!enumerationClosed && options.enumerationCloseRequested?.()) {
1616
+ if (current.gaps.length || current.root.kind !== "attributed" || !current.retainedIdentities.some(
1617
+ (row) => row.role === "root" && row.lifecycle === "alive" && sameProcess(row.identity, root)
1618
+ ))
1619
+ throw new Error("JOURNAL_PRECLOSE_REFUSED");
1620
+ enumerationClosed = true;
1621
+ await options.onEnumerationClosed?.({
1622
+ sequence: current.sequence,
1623
+ monotonic: end,
1624
+ root: current.root.identity
1625
+ });
1626
+ }
1627
+ if (options.continuousWindowMilliseconds !== void 0) {
1628
+ if (current.gaps.length || !Number.isFinite(end) || end < start || end >= currentWindowEnd) {
1629
+ await reportFault();
1630
+ result = "retained";
1631
+ break;
1632
+ }
1633
+ const nextEnd = end + options.continuousWindowMilliseconds;
1634
+ if (!Number.isFinite(nextEnd) || nextEnd <= end) {
1635
+ await reportFault();
1636
+ result = "retained";
1637
+ break;
1638
+ }
1639
+ if (!gone && current.root.kind === "attributed")
1640
+ await options.onCheckpoint?.({
1641
+ sequence: current.sequence,
1642
+ monotonic: end,
1643
+ root: current.root.identity
1644
+ });
1645
+ currentWindowEnd = nextEnd;
1646
+ }
1647
+ if (current.gaps.length && admittedGone) {
1648
+ const managerFact = facts.get(current.binding.manager.pid);
1649
+ result = supervisor && gone && options.endBrowser?.() && managerFact?.kind === "present" && !managerFact.zombie && sameProcess(darwinBirth(managerFact.identity), current.binding.manager) ? "campaign-closed-gapped" : "retained";
1650
+ break;
1651
+ }
1652
+ if (gone) {
1653
+ result = options.exitingObserver ? "original-child-returned-observer-live" : options.endBrowser?.() ? "campaign-closed" : "recorded-gone";
1654
+ break;
1655
+ }
1656
+ await options.pause();
1657
+ }
1658
+ } catch {
1659
+ result = "uncertain";
1660
+ }
1661
+ if (result !== "recorded-gone" && result !== "original-child-returned-observer-live" && result !== "campaign-closed" && result !== "campaign-closed-gapped") {
1662
+ try {
1663
+ await reportFault();
1664
+ } catch {
1665
+ result = "uncertain";
1666
+ }
1667
+ const refusal = copyJournalData(current);
1668
+ refusal.sequence++;
1669
+ refusal.phase = "retained";
1670
+ refusal.observationWindow = {
1671
+ ...current.observationWindow,
1672
+ startSequence: refusal.sequence,
1673
+ checkpointSequence: refusal.sequence,
1674
+ endSequence: refusal.sequence
1675
+ };
1676
+ if (!refusal.gaps.length) gap(refusal, refusalCause);
1677
+ if ((await opened.writer.commitSnapshot(refusal)).state !== "durable-recorded")
1678
+ result = "uncertain";
1679
+ }
1680
+ const closed = await opened.writer.close();
1681
+ return closed.state === "closed" ? result : "uncertain";
1682
+ }
1683
+
1684
+ // packages/browser/src/runtime/darwin-journal-worker.ts
1685
+ var identity3 = z3.object({
1686
+ pid: z3.number().int().positive(),
1687
+ birth: z3.string().min(1).max(128)
1688
+ }).strict();
1689
+ var seedSchema = z3.object({
1690
+ kind: z3.literal("seed"),
1691
+ ownedLaunch: z3.boolean().default(false),
1692
+ logicalManager: identity3.optional(),
1693
+ initial: JournalSnapshotSchema,
1694
+ location: z3.object({
1695
+ parentDirectory: z3.string().max(4096),
1696
+ parentIdentity: z3.object({
1697
+ device: z3.string(),
1698
+ inode: z3.string(),
1699
+ mode: z3.number(),
1700
+ uid: z3.number(),
1701
+ type: z3.literal("directory")
1702
+ }).strict(),
1703
+ binding: JournalSnapshotSchema.shape.binding
1704
+ }).strict(),
1705
+ artifact: z3.object({
1706
+ path: z3.string().max(4096),
1707
+ sha256: z3.string().regex(/^[a-f0-9]{64}$/)
1708
+ }).strict(),
1709
+ duration: z3.number().positive().max(6e5),
1710
+ continuous: z3.boolean().default(false),
1711
+ maxGap: z3.number().positive().max(1e4)
1712
+ }).strict();
1713
+ var rootSchema = z3.object({
1714
+ kind: z3.literal("root"),
1715
+ identity: identity3,
1716
+ supervisor: identity3.optional()
1717
+ }).strict();
1718
+ var launchSchema = z3.object({
1719
+ kind: z3.literal("launch"),
1720
+ executable: z3.string().min(1).max(4096),
1721
+ cwd: z3.string().min(1).max(4096),
1722
+ argv: z3.array(z3.string().max(4096)).max(64)
1723
+ }).strict();
1724
+ var refuseSchema = z3.object({ kind: z3.literal("refuse-seed") }).strict();
1725
+ var returnedSchema = z3.object({
1726
+ kind: z3.literal("root-returned"),
1727
+ nonce: z3.string().min(1).max(128),
1728
+ identity: identity3
1729
+ }).strict();
1730
+ var prepareCloseSchema = z3.object({
1731
+ kind: z3.literal("prepare-close"),
1732
+ nonce: z3.string().min(1).max(128),
1733
+ identity: identity3
1734
+ }).strict();
1735
+ var endSchema = z3.object({ kind: z3.literal("end-browser"), launchEntered: z3.boolean() }).strict();
1736
+ var messages = z3.discriminatedUnion("kind", [
1737
+ z3.object({ kind: z3.literal("enrolled") }).strict(),
1738
+ z3.object({ kind: z3.literal("observation-fault") }).strict(),
1739
+ z3.object({
1740
+ kind: z3.literal("enumeration-closed"),
1741
+ nonce: z3.string().min(1).max(128),
1742
+ sequence: z3.number().int().positive().safe(),
1743
+ monotonic: z3.number().int().nonnegative().safe(),
1744
+ root: identity3
1745
+ }).strict(),
1746
+ z3.object({
1747
+ kind: z3.literal("checkpoint"),
1748
+ sequence: z3.number().int().positive().safe(),
1749
+ monotonic: z3.number().int().nonnegative().safe(),
1750
+ root: identity3
1751
+ }).strict(),
1752
+ z3.object({
1753
+ kind: z3.literal("complete"),
1754
+ result: z3.enum([
1755
+ "recorded-gone",
1756
+ "original-child-returned-observer-live",
1757
+ "campaign-closed-gapped",
1758
+ "campaign-closed",
1759
+ "retained",
1760
+ "uncertain"
1761
+ ])
1762
+ }).strict()
1763
+ ]);
1764
+ var originals = /* @__PURE__ */ new Set();
1765
+ async function startDarwinJournalWorker(options) {
1766
+ const seed = seedSchema.parse({
1767
+ kind: "seed",
1768
+ ownedLaunch: options.ownedLaunch ?? false,
1769
+ location: options.location,
1770
+ initial: options.initial,
1771
+ artifact: options.artifact,
1772
+ duration: options.duration,
1773
+ continuous: options.continuous ?? false,
1774
+ maxGap: options.maxGap
1775
+ });
1776
+ if (Buffer.byteLength(JSON.stringify(seed)) > 1048576) throw new Error("JOURNAL_UNAVAILABLE");
1777
+ const originalClock = process.hrtime.bigint.bind(process.hrtime);
1778
+ const monotonicNow = () => Number(originalClock() / 1000000n);
1779
+ if (seed.continuous && seed.ownedLaunch) throw new Error("CONTINUOUS_ROOT_UNSUPPORTED");
1780
+ const child = spawn3(process.execPath, [options.workerPath, "--private-darwin-journal-worker"], {
1781
+ shell: false,
1782
+ detached: false,
1783
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
1784
+ env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" }
1785
+ });
1786
+ originals.add(child);
1787
+ let failure = false, used = false, returnedSent = false, result = "uncertain";
1788
+ let acknowledge, refuse;
1789
+ const enrolled = new Promise((resolve, reject) => {
1790
+ acknowledge = () => resolve();
1791
+ refuse = reject;
1792
+ });
1793
+ void enrolled.catch(() => {
1794
+ });
1795
+ let sawEnrolled = false, sawComplete = false;
1796
+ let expectedRoot;
1797
+ let checkpoint;
1798
+ let acceptCheckpoint, rejectCheckpoint;
1799
+ const firstCheckpoint = new Promise((resolve, reject) => {
1800
+ acceptCheckpoint = resolve;
1801
+ rejectCheckpoint = reject;
1802
+ });
1803
+ void firstCheckpoint.catch(() => {
1804
+ });
1805
+ let closeRequested = false, closeAcknowledged = false;
1806
+ let resolveClose, rejectClose;
1807
+ const closeReady = new Promise((resolve, reject) => {
1808
+ resolveClose = resolve;
1809
+ rejectClose = reject;
1810
+ });
1811
+ void closeReady.catch(() => {
1812
+ });
1813
+ let closeSend;
1814
+ const fault = (reason) => {
1815
+ failure = true;
1816
+ refuse(reason);
1817
+ rejectCheckpoint(reason);
1818
+ rejectClose(reason);
1819
+ };
1820
+ const observationKnown = () => {
1821
+ if (failure || !sawEnrolled || sawComplete) return false;
1822
+ if (!seed.continuous) return true;
1823
+ if (!checkpoint) return false;
1824
+ const now = monotonicNow();
1825
+ if (!Number.isSafeInteger(now) || now < checkpoint.monotonic || now - checkpoint.monotonic > seed.maxGap) {
1826
+ fault(new Error("JOURNAL_OBSERVATION_STALE"));
1827
+ return false;
1828
+ }
1829
+ return true;
1830
+ };
1831
+ child.on("message", (value) => {
1832
+ const parsed = messages.safeParse(value);
1833
+ if (!parsed.success) {
1834
+ fault(new Error("JOURNAL_UNAVAILABLE"));
1835
+ return;
1836
+ }
1837
+ if (parsed.data.kind === "observation-fault") {
1838
+ fault(new Error("JOURNAL_OBSERVATION_REFUSED"));
1839
+ } else if (parsed.data.kind === "enumeration-closed") {
1840
+ const next = parsed.data;
1841
+ const now = monotonicNow();
1842
+ if (!closeRequested || closeAcknowledged || failure || sawComplete || !sawEnrolled || !expectedRoot || next.nonce !== seed.initial.binding.reservationNonce || !sameProcess(next.root, expectedRoot) || !Number.isSafeInteger(now) || next.monotonic > now || now - next.monotonic > seed.maxGap || checkpoint && (next.sequence <= checkpoint.sequence || next.monotonic < checkpoint.monotonic)) {
1843
+ fault(new Error("JOURNAL_PRECLOSE_REFUSED"));
1844
+ return;
1845
+ }
1846
+ closeAcknowledged = true;
1847
+ resolveClose();
1848
+ } else if (parsed.data.kind === "checkpoint") {
1849
+ const next = parsed.data;
1850
+ const now = monotonicNow();
1851
+ if (!seed.continuous || !sawEnrolled || sawComplete || failure || !expectedRoot || expectedRoot.pid !== next.root.pid || expectedRoot.birth !== next.root.birth || checkpoint && (!observationKnown() || next.sequence <= checkpoint.sequence || next.monotonic < checkpoint.monotonic) || !Number.isSafeInteger(now) || next.monotonic > now || now - next.monotonic > seed.maxGap) {
1852
+ fault(new Error("JOURNAL_CHECKPOINT_REFUSED"));
1853
+ return;
1854
+ }
1855
+ checkpoint = { sequence: next.sequence, monotonic: next.monotonic };
1856
+ acceptCheckpoint();
1857
+ } else if (parsed.data.kind === "enrolled") {
1858
+ if (sawEnrolled || sawComplete) {
1859
+ fault(new Error("JOURNAL_UNAVAILABLE"));
1860
+ return;
1861
+ }
1862
+ sawEnrolled = true;
1863
+ acknowledge();
1864
+ } else {
1865
+ if (!sawEnrolled || sawComplete) {
1866
+ fault(new Error("JOURNAL_UNAVAILABLE"));
1867
+ return;
1868
+ }
1869
+ sawComplete = true;
1870
+ if (seed.continuous && !checkpoint) fault(new Error("JOURNAL_CHECKPOINT_REFUSED"));
1871
+ rejectCheckpoint(new Error("JOURNAL_OBSERVATION_ENDED"));
1872
+ if (!closeAcknowledged) rejectClose(new Error("JOURNAL_PRECLOSE_REFUSED"));
1873
+ result = parsed.data.result;
1874
+ }
1875
+ });
1876
+ child.on("error", () => {
1877
+ fault(new Error("JOURNAL_UNAVAILABLE"));
1878
+ });
1879
+ const terminal = new Promise(
1880
+ (resolve) => child.once("close", (code) => {
1881
+ if (!sawComplete) fault(new Error("JOURNAL_UNAVAILABLE"));
1882
+ rejectCheckpoint(new Error("JOURNAL_OBSERVATION_ENDED"));
1883
+ if (!closeAcknowledged) rejectClose(new Error("JOURNAL_PRECLOSE_REFUSED"));
1884
+ resolve(code);
1885
+ })
1886
+ );
1887
+ const stderrChunks = [];
1888
+ const pipeReturns = [
1889
+ { eof: false, closed: false },
1890
+ { eof: false, closed: false }
1891
+ ];
1892
+ const drain = async (stream, duty) => {
1893
+ if (!stream) {
1894
+ fault(new Error("JOURNAL_PIPE_UNAVAILABLE"));
1895
+ return;
1896
+ }
1897
+ stream.once("error", (reason) => fault(reason));
1898
+ stream.once("end", () => {
1899
+ duty.eof = true;
1900
+ });
1901
+ stream.once("close", () => {
1902
+ duty.closed = true;
1903
+ if (!duty.eof) fault(new Error("JOURNAL_PIPE_UNAVAILABLE"));
1904
+ });
1905
+ try {
1906
+ let bytes = 0;
1907
+ for await (const chunk of stream) {
1908
+ bytes += Buffer.byteLength(chunk);
1909
+ if (bytes > 262144) fault(new Error("JOURNAL_PIPE_UNAVAILABLE"));
1910
+ else if (stream === child.stderr) stderrChunks.push(Buffer.from(chunk));
1911
+ }
1912
+ if (!stream.readableEnded || !duty.eof) throw new Error("JOURNAL_PIPE_UNAVAILABLE");
1913
+ } catch (reason) {
1914
+ fault(reason);
1915
+ throw reason;
1916
+ }
1917
+ };
1918
+ const streams = Promise.allSettled([
1919
+ drain(child.stdout, pipeReturns[0]),
1920
+ drain(child.stderr, pipeReturns[1])
1921
+ ]);
1922
+ const completion = (async () => {
1923
+ const [code, closed] = await Promise.all([terminal, streams]);
1924
+ const pipesReturned = closed.every((value) => value.status === "fulfilled") && pipeReturns.every((duty) => duty.eof && duty.closed);
1925
+ if (pipesReturned) originals.delete(child);
1926
+ return failure || code !== 0 || !pipesReturned || !sawComplete ? "uncertain" : result;
1927
+ })();
1928
+ const send = (value) => new Promise(
1929
+ (resolve, reject) => child.send(value, (error) => {
1930
+ if (error) {
1931
+ fault(error);
1932
+ reject(error);
1933
+ } else resolve();
1934
+ })
1935
+ );
1936
+ try {
1937
+ if (options.ownedLaunch) {
1938
+ const batch = await createDarwinProcessObserver(options.artifact).inspect([child.pid]);
1939
+ const self = batch.processes[0];
1940
+ if (self.kind !== "present" || self.zombie || self.parentPid !== process.pid || seed.initial.binding.bootScope.kind !== "observed" || seed.initial.binding.bootScope.value !== `darwin-boot:${batch.bootSeconds}:${batch.bootMicroseconds}`)
1941
+ throw new Error("SUPERVISOR_UNAVAILABLE");
1942
+ seed.logicalManager = { ...seed.initial.binding.manager };
1943
+ const actualSelf = darwinBirth(self.identity);
1944
+ seed.initial.binding.manager = actualSelf;
1945
+ seed.location.binding.manager = actualSelf;
1946
+ seed.initial.retainedIdentities[0].identity = actualSelf;
1947
+ }
1948
+ await send(seed);
1949
+ await enrolled;
1950
+ } catch (error) {
1951
+ try {
1952
+ if (child.connected) await send({ kind: "refuse-seed" });
1953
+ } catch {
1954
+ failure = true;
1955
+ }
1956
+ try {
1957
+ await completion;
1958
+ } catch {
1959
+ failure = true;
1960
+ }
1961
+ throw error;
1962
+ }
1963
+ return Object.freeze({
1964
+ child,
1965
+ isObservationKnown: observationKnown,
1966
+ location: seed.location,
1967
+ stderr: () => Buffer.concat(stderrChunks),
1968
+ completion,
1969
+ prepareClose() {
1970
+ if (closeSend) return closeSend;
1971
+ closeRequested = true;
1972
+ closeSend = Promise.resolve().then(async () => {
1973
+ if (failure || sawComplete || returnedSent || !expectedRoot)
1974
+ throw new Error("JOURNAL_PRECLOSE_REFUSED");
1975
+ await send(
1976
+ prepareCloseSchema.parse({
1977
+ kind: "prepare-close",
1978
+ nonce: seed.initial.binding.reservationNonce,
1979
+ identity: expectedRoot
1980
+ })
1981
+ );
1982
+ await closeReady;
1983
+ });
1984
+ void closeSend.catch(fault);
1985
+ return closeSend;
1986
+ },
1987
+ async rootReturned(root) {
1988
+ const original = identity3.parse(root);
1989
+ if (failure || returnedSent || !expectedRoot || !sameProcess(original, expectedRoot))
1990
+ throw new Error("JOURNAL_ROOT_RETURN_REFUSED");
1991
+ returnedSent = true;
1992
+ await send(
1993
+ returnedSchema.parse({
1994
+ kind: "root-returned",
1995
+ nonce: seed.initial.binding.reservationNonce,
1996
+ identity: original
1997
+ })
1998
+ );
1999
+ },
2000
+ async endBrowser(launchEntered) {
2001
+ await send({ kind: "end-browser", launchEntered });
2002
+ },
2003
+ async launchRoot(command) {
2004
+ if (!options.ownedLaunch || used) throw new Error("ROOT_ALREADY_ENROLLED");
2005
+ used = true;
2006
+ await send(launchSchema.parse({ kind: "launch", ...command }));
2007
+ },
2008
+ async enrollRoot(root, supervisor) {
2009
+ if (used || options.ownedLaunch) throw new Error("ROOT_ALREADY_ENROLLED");
2010
+ used = true;
2011
+ expectedRoot = identity3.parse(root);
2012
+ await send(
2013
+ rootSchema.parse({
2014
+ kind: "root",
2015
+ identity: expectedRoot,
2016
+ ...supervisor ? { supervisor } : {}
2017
+ })
2018
+ );
2019
+ if (seed.continuous) await firstCheckpoint;
2020
+ }
2021
+ });
2022
+ }
2023
+ function darwinMonotonicNow() {
2024
+ return Number(process.hrtime.bigint() / 1000000n);
2025
+ }
2026
+ async function runPrivateWorker() {
2027
+ let supervisor;
2028
+ let rootResolve;
2029
+ const root = new Promise((resolve) => {
2030
+ rootResolve = resolve;
2031
+ });
2032
+ let seedResolve;
2033
+ const seed = new Promise((resolve) => {
2034
+ seedResolve = resolve;
2035
+ });
2036
+ let launchResolve;
2037
+ const launch = new Promise((resolve) => {
2038
+ launchResolve = resolve;
2039
+ });
2040
+ let ended = false, launchNotEntered = false;
2041
+ let seedNonce;
2042
+ let enrolledRoot, returnedRoot;
2043
+ let enumerationCloseRequested = false;
2044
+ let seeded = false, rooted = false, invalid = false;
2045
+ const receive = (value) => {
2046
+ if (refuseSchema.safeParse(value).success) {
2047
+ invalid = true;
2048
+ seeded = true;
2049
+ seedResolve(null);
2050
+ rootResolve(null);
2051
+ launchResolve(null);
2052
+ return;
2053
+ }
2054
+ if (!seeded) {
2055
+ seeded = true;
2056
+ seedResolve(value);
2057
+ return;
2058
+ }
2059
+ const prepare = prepareCloseSchema.safeParse(value);
2060
+ if (prepare.success) {
2061
+ if (invalid || ended || enumerationCloseRequested || returnedRoot || !rooted || !enrolledRoot || !seedNonce || prepare.data.nonce !== seedNonce || !sameProcess(prepare.data.identity, enrolledRoot)) {
2062
+ invalid = true;
2063
+ return;
2064
+ }
2065
+ enumerationCloseRequested = true;
2066
+ return;
2067
+ }
2068
+ const returned = returnedSchema.safeParse(value);
2069
+ if (returned.success) {
2070
+ if (!rooted || !enrolledRoot || returnedRoot || !seedNonce || returned.data.nonce !== seedNonce || !sameProcess(returned.data.identity, enrolledRoot)) {
2071
+ invalid = true;
2072
+ return;
2073
+ }
2074
+ returnedRoot = Object.freeze({ ...returned.data.identity });
2075
+ return;
2076
+ }
2077
+ const end = endSchema.safeParse(value);
2078
+ if (end.success) {
2079
+ if (ended) {
2080
+ invalid = true;
2081
+ return;
2082
+ }
2083
+ ended = true;
2084
+ launchNotEntered = !end.data.launchEntered;
2085
+ if (launchNotEntered) {
2086
+ if (rooted) {
2087
+ invalid = true;
2088
+ return;
2089
+ }
2090
+ rootResolve(null);
2091
+ launchResolve(null);
2092
+ }
2093
+ return;
2094
+ }
2095
+ if (ended) {
2096
+ invalid = true;
2097
+ return;
2098
+ }
2099
+ const request = launchSchema.safeParse(value);
2100
+ if (!rooted && request.success) {
2101
+ rooted = true;
2102
+ launchResolve(request.data);
2103
+ return;
2104
+ }
2105
+ const parsed = rootSchema.safeParse(value);
2106
+ if (rooted || !parsed.success) {
2107
+ invalid = true;
2108
+ rootResolve(null);
2109
+ return;
2110
+ }
2111
+ rooted = true;
2112
+ supervisor = parsed.data.supervisor;
2113
+ enrolledRoot = Object.freeze({ ...parsed.data.identity });
2114
+ rootResolve(parsed.data.identity);
2115
+ };
2116
+ process.on("message", receive);
2117
+ const disconnected = () => {
2118
+ process.removeListener("message", receive);
2119
+ if (!seeded) seedResolve(null);
2120
+ if (!rooted) {
2121
+ rootResolve(null);
2122
+ launchResolve(null);
2123
+ }
2124
+ };
2125
+ process.once("disconnect", disconnected);
2126
+ if (!process.connected) disconnected();
2127
+ const send = (value) => new Promise((resolve, reject) => {
2128
+ if (!process.send) {
2129
+ reject(new Error("CHANNEL_UNAVAILABLE"));
2130
+ return;
2131
+ }
2132
+ process.send(value, (error) => error ? reject(error) : resolve());
2133
+ });
2134
+ let result;
2135
+ try {
2136
+ const value = seedSchema.parse(await seed);
2137
+ seedNonce = value.initial.binding.reservationNonce;
2138
+ if (value.initial.binding.bootScope.kind !== "observed" || value.initial.binding.bootScope.sourceIdentityDigest !== value.artifact.sha256)
2139
+ throw new Error("BOOT_SOURCE_UNAVAILABLE");
2140
+ const logicalManager = value.logicalManager ?? {
2141
+ ...value.initial.binding.manager
2142
+ };
2143
+ const observer = createDarwinProcessObserver(value.artifact);
2144
+ let ownedRoot = null;
2145
+ if (value.ownedLaunch) {
2146
+ const self = (await observer.inspect([process.pid])).processes[0];
2147
+ if (self.kind !== "present" || self.zombie) throw new Error("SUPERVISOR_UNAVAILABLE");
2148
+ const actualSelf = darwinBirth(self.identity);
2149
+ if (actualSelf.pid !== value.initial.binding.manager.pid || actualSelf.birth !== value.initial.binding.manager.birth || !value.logicalManager)
2150
+ throw new Error("SUPERVISOR_BINDING_MISMATCH");
2151
+ void (async () => {
2152
+ try {
2153
+ const command = launchSchema.parse(await launch);
2154
+ ownedRoot = await createDarwinOwnedChildLauncher({
2155
+ artifact: value.artifact,
2156
+ manager: logicalManager
2157
+ }).launch({
2158
+ executable: command.executable,
2159
+ argv: command.argv,
2160
+ cwd: command.cwd,
2161
+ env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" }
2162
+ });
2163
+ rootResolve(await ownedRoot.identity());
2164
+ } catch {
2165
+ invalid = true;
2166
+ rootResolve(null);
2167
+ }
2168
+ })();
2169
+ }
2170
+ const rootEnd = setTimeout(() => {
2171
+ rootResolve(null);
2172
+ launchResolve(null);
2173
+ }, value.duration);
2174
+ let reportedIncomplete = false;
2175
+ try {
2176
+ result = await observeDarwinJournal({
2177
+ location: value.location,
2178
+ initial: value.initial,
2179
+ root,
2180
+ rootSupervisor: () => supervisor,
2181
+ observer,
2182
+ endBrowser: () => ended,
2183
+ originalRootReturned: () => {
2184
+ if (invalid) throw new Error("JOURNAL_ROOT_RETURN_REFUSED");
2185
+ return returnedRoot;
2186
+ },
2187
+ enumerationCloseRequested: () => {
2188
+ if (invalid) throw new Error("JOURNAL_PRECLOSE_REFUSED");
2189
+ return enumerationCloseRequested;
2190
+ },
2191
+ onEnumerationClosed: (checkpoint) => send({ kind: "enumeration-closed", nonce: seedNonce, ...checkpoint }),
2192
+ launchNotEntered: () => launchNotEntered,
2193
+ ...value.ownedLaunch ? { logicalManager, exitingObserver: value.initial.binding.manager } : {},
2194
+ monotonicNow: darwinMonotonicNow,
2195
+ pause: () => new Promise((resolve) => setTimeout(resolve, 50)),
2196
+ endMonotonic: darwinMonotonicNow() + value.duration,
2197
+ ...value.continuous ? {
2198
+ continuousWindowMilliseconds: value.duration,
2199
+ onObservationFault: () => send({ kind: "observation-fault" }),
2200
+ onCheckpoint: (checkpoint) => send({ kind: "checkpoint", ...checkpoint })
2201
+ } : {},
2202
+ maxGap: value.maxGap,
2203
+ onEnrolled: () => send({ kind: "enrolled" }),
2204
+ onIncompleteChildren: async (parent, batch) => {
2205
+ if (reportedIncomplete) return;
2206
+ reportedIncomplete = true;
2207
+ const bytes = JSON.stringify({
2208
+ kind: "incomplete-native-children",
2209
+ parent,
2210
+ batch
2211
+ }) + "\n";
2212
+ await new Promise(
2213
+ (resolve, reject) => process.stderr.write(bytes, (error) => error ? reject(error) : resolve())
2214
+ );
2215
+ }
2216
+ });
2217
+ } finally {
2218
+ clearTimeout(rootEnd);
2219
+ }
2220
+ if (value.ownedLaunch) {
2221
+ const original = ownedRoot;
2222
+ if (!original || result !== "original-child-returned-observer-live") result = "uncertain";
2223
+ else if (!acceptsDarwinOwnedChildReturn(original, await original.returned()))
2224
+ result = "uncertain";
2225
+ }
2226
+ if (invalid) result = "uncertain";
2227
+ } catch {
2228
+ result = "uncertain";
2229
+ }
2230
+ if (process.connected) {
2231
+ try {
2232
+ await send({ kind: "complete", result });
2233
+ } catch {
2234
+ result = "uncertain";
2235
+ }
2236
+ process.disconnect();
2237
+ }
2238
+ process.exitCode = result === "uncertain" ? 1 : 0;
2239
+ }
2240
+ if (process.argv[2] === "--private-darwin-journal-worker") void runPrivateWorker();
2241
+ export {
2242
+ darwinMonotonicNow,
2243
+ startDarwinJournalWorker
2244
+ };