@diffra-ai/chord 0.0.0-stage → 0.2.3

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 (1334) hide show
  1. package/CHANGELOG.md +237 -0
  2. package/README.md +227 -2
  3. package/dist/context/index.d.ts +43 -0
  4. package/dist/context/index.d.ts.map +1 -0
  5. package/dist/context/index.js +112 -0
  6. package/dist/context/index.js.map +1 -0
  7. package/dist/contracts/accepts.d.ts +91 -0
  8. package/dist/contracts/accepts.d.ts.map +1 -0
  9. package/dist/contracts/accepts.js +145 -0
  10. package/dist/contracts/accepts.js.map +1 -0
  11. package/dist/contracts/contract.d.ts +238 -0
  12. package/dist/contracts/contract.d.ts.map +1 -0
  13. package/dist/contracts/contract.js +69 -0
  14. package/dist/contracts/contract.js.map +1 -0
  15. package/dist/contracts/declare.d.ts +144 -0
  16. package/dist/contracts/declare.d.ts.map +1 -0
  17. package/dist/contracts/declare.js +207 -0
  18. package/dist/contracts/declare.js.map +1 -0
  19. package/dist/contracts/evolve.d.ts +142 -0
  20. package/dist/contracts/evolve.d.ts.map +1 -0
  21. package/dist/contracts/evolve.js +216 -0
  22. package/dist/contracts/evolve.js.map +1 -0
  23. package/dist/contracts/fingerprint.d.ts +16 -0
  24. package/dist/contracts/fingerprint.d.ts.map +1 -0
  25. package/dist/contracts/fingerprint.js +61 -0
  26. package/dist/contracts/fingerprint.js.map +1 -0
  27. package/dist/contracts/history.d.ts +79 -0
  28. package/dist/contracts/history.d.ts.map +1 -0
  29. package/dist/contracts/history.js +3 -0
  30. package/dist/contracts/history.js.map +1 -0
  31. package/dist/contracts/host-kind.d.ts +58 -0
  32. package/dist/contracts/host-kind.d.ts.map +1 -0
  33. package/dist/contracts/host-kind.js +122 -0
  34. package/dist/contracts/host-kind.js.map +1 -0
  35. package/dist/contracts/index.d.ts +8 -0
  36. package/dist/contracts/index.d.ts.map +1 -0
  37. package/dist/contracts/index.js +7 -0
  38. package/dist/contracts/index.js.map +1 -0
  39. package/dist/contracts/internal.d.ts +12 -0
  40. package/dist/contracts/internal.d.ts.map +1 -0
  41. package/dist/contracts/internal.js +11 -0
  42. package/dist/contracts/internal.js.map +1 -0
  43. package/dist/contracts/names.d.ts +3 -0
  44. package/dist/contracts/names.d.ts.map +1 -0
  45. package/dist/contracts/names.js +13 -0
  46. package/dist/contracts/names.js.map +1 -0
  47. package/dist/contracts/params.d.ts +28 -0
  48. package/dist/contracts/params.d.ts.map +1 -0
  49. package/dist/contracts/params.js +55 -0
  50. package/dist/contracts/params.js.map +1 -0
  51. package/dist/contracts/schema.d.ts +144 -0
  52. package/dist/contracts/schema.d.ts.map +1 -0
  53. package/dist/contracts/schema.js +144 -0
  54. package/dist/contracts/schema.js.map +1 -0
  55. package/dist/contracts/snapshot.d.ts +16 -0
  56. package/dist/contracts/snapshot.d.ts.map +1 -0
  57. package/dist/contracts/snapshot.js +167 -0
  58. package/dist/contracts/snapshot.js.map +1 -0
  59. package/dist/data/args.d.ts +50 -0
  60. package/dist/data/args.d.ts.map +1 -0
  61. package/dist/data/args.js +83 -0
  62. package/dist/data/args.js.map +1 -0
  63. package/dist/data/errors.d.ts +80 -0
  64. package/dist/data/errors.d.ts.map +1 -0
  65. package/dist/data/errors.js +116 -0
  66. package/dist/data/errors.js.map +1 -0
  67. package/dist/data/failure.d.ts +31 -0
  68. package/dist/data/failure.d.ts.map +1 -0
  69. package/dist/data/failure.js +78 -0
  70. package/dist/data/failure.js.map +1 -0
  71. package/dist/data/index.d.ts +4 -0
  72. package/dist/data/index.d.ts.map +1 -0
  73. package/dist/data/index.js +5 -0
  74. package/dist/data/index.js.map +1 -0
  75. package/dist/data/internal.d.ts +7 -0
  76. package/dist/data/internal.d.ts.map +1 -0
  77. package/dist/data/internal.js +8 -0
  78. package/dist/data/internal.js.map +1 -0
  79. package/dist/data/params.d.ts +20 -0
  80. package/dist/data/params.d.ts.map +1 -0
  81. package/dist/data/params.js +31 -0
  82. package/dist/data/params.js.map +1 -0
  83. package/dist/data/principal.d.ts +28 -0
  84. package/dist/data/principal.d.ts.map +1 -0
  85. package/dist/data/principal.js +64 -0
  86. package/dist/data/principal.js.map +1 -0
  87. package/dist/data/validator.d.ts +12 -0
  88. package/dist/data/validator.d.ts.map +1 -0
  89. package/dist/data/validator.js +35 -0
  90. package/dist/data/validator.js.map +1 -0
  91. package/dist/delta/apply-immutable-trusted.d.ts +4 -0
  92. package/dist/delta/apply-immutable-trusted.d.ts.map +1 -0
  93. package/dist/delta/apply-immutable-trusted.js +126 -0
  94. package/dist/delta/apply-immutable-trusted.js.map +1 -0
  95. package/dist/delta/diff.d.ts +5 -0
  96. package/dist/delta/diff.d.ts.map +1 -0
  97. package/dist/delta/diff.js +435 -0
  98. package/dist/delta/diff.js.map +1 -0
  99. package/dist/delta/draft.d.ts +5 -0
  100. package/dist/delta/draft.d.ts.map +1 -0
  101. package/dist/delta/draft.js +2 -0
  102. package/dist/delta/draft.js.map +1 -0
  103. package/dist/delta/index.d.ts +120 -0
  104. package/dist/delta/index.d.ts.map +1 -0
  105. package/dist/delta/index.js +697 -0
  106. package/dist/delta/index.js.map +1 -0
  107. package/dist/delta/pending.d.ts +36 -0
  108. package/dist/delta/pending.d.ts.map +1 -0
  109. package/dist/delta/pending.js +143 -0
  110. package/dist/delta/pending.js.map +1 -0
  111. package/dist/delta/revision-validator.d.ts +7 -0
  112. package/dist/delta/revision-validator.d.ts.map +1 -0
  113. package/dist/delta/revision-validator.js +71 -0
  114. package/dist/delta/revision-validator.js.map +1 -0
  115. package/dist/delta/tracker.d.ts +38 -0
  116. package/dist/delta/tracker.d.ts.map +1 -0
  117. package/dist/delta/tracker.js +2175 -0
  118. package/dist/delta/tracker.js.map +1 -0
  119. package/dist/documents/address-source.d.ts +20 -0
  120. package/dist/documents/address-source.d.ts.map +1 -0
  121. package/dist/documents/address-source.js +44 -0
  122. package/dist/documents/address-source.js.map +1 -0
  123. package/dist/documents/definition.d.ts +92 -0
  124. package/dist/documents/definition.d.ts.map +1 -0
  125. package/dist/documents/definition.js +81 -0
  126. package/dist/documents/definition.js.map +1 -0
  127. package/dist/documents/documents.d.ts +129 -0
  128. package/dist/documents/documents.d.ts.map +1 -0
  129. package/dist/documents/documents.js +258 -0
  130. package/dist/documents/documents.js.map +1 -0
  131. package/dist/documents/fence.d.ts +9 -0
  132. package/dist/documents/fence.d.ts.map +1 -0
  133. package/dist/documents/fence.js +15 -0
  134. package/dist/documents/fence.js.map +1 -0
  135. package/dist/documents/handles.d.ts +81 -0
  136. package/dist/documents/handles.d.ts.map +1 -0
  137. package/dist/documents/handles.js +74 -0
  138. package/dist/documents/handles.js.map +1 -0
  139. package/dist/documents/index.d.ts +4 -0
  140. package/dist/documents/index.d.ts.map +1 -0
  141. package/dist/documents/index.js +3 -0
  142. package/dist/documents/index.js.map +1 -0
  143. package/dist/documents/internal.d.ts +9 -0
  144. package/dist/documents/internal.d.ts.map +1 -0
  145. package/dist/documents/internal.js +9 -0
  146. package/dist/documents/internal.js.map +1 -0
  147. package/dist/documents/keyed-slot.d.ts +139 -0
  148. package/dist/documents/keyed-slot.d.ts.map +1 -0
  149. package/dist/documents/keyed-slot.js +478 -0
  150. package/dist/documents/keyed-slot.js.map +1 -0
  151. package/dist/documents/line.d.ts +7 -0
  152. package/dist/documents/line.d.ts.map +1 -0
  153. package/dist/documents/line.js +14 -0
  154. package/dist/documents/line.js.map +1 -0
  155. package/dist/documents/persistence.d.ts +120 -0
  156. package/dist/documents/persistence.d.ts.map +1 -0
  157. package/dist/documents/persistence.js +156 -0
  158. package/dist/documents/persistence.js.map +1 -0
  159. package/dist/documents/residency.d.ts +31 -0
  160. package/dist/documents/residency.d.ts.map +1 -0
  161. package/dist/documents/residency.js +93 -0
  162. package/dist/documents/residency.js.map +1 -0
  163. package/dist/documents/slot.d.ts +112 -0
  164. package/dist/documents/slot.d.ts.map +1 -0
  165. package/dist/documents/slot.js +190 -0
  166. package/dist/documents/slot.js.map +1 -0
  167. package/dist/documents/transaction.d.ts +143 -0
  168. package/dist/documents/transaction.d.ts.map +1 -0
  169. package/dist/documents/transaction.js +445 -0
  170. package/dist/documents/transaction.js.map +1 -0
  171. package/dist/host/activity.d.ts +31 -0
  172. package/dist/host/activity.d.ts.map +1 -0
  173. package/dist/host/activity.js +40 -0
  174. package/dist/host/activity.js.map +1 -0
  175. package/dist/host/adapted.d.ts +63 -0
  176. package/dist/host/adapted.d.ts.map +1 -0
  177. package/dist/host/adapted.js +298 -0
  178. package/dist/host/adapted.js.map +1 -0
  179. package/dist/host/admission.d.ts +137 -0
  180. package/dist/host/admission.d.ts.map +1 -0
  181. package/dist/host/admission.js +290 -0
  182. package/dist/host/admission.js.map +1 -0
  183. package/dist/host/attempt.d.ts +417 -0
  184. package/dist/host/attempt.d.ts.map +1 -0
  185. package/dist/host/attempt.js +1490 -0
  186. package/dist/host/attempt.js.map +1 -0
  187. package/dist/host/backoff.d.ts +29 -0
  188. package/dist/host/backoff.d.ts.map +1 -0
  189. package/dist/host/backoff.js +69 -0
  190. package/dist/host/backoff.js.map +1 -0
  191. package/dist/host/ctx.d.ts +94 -0
  192. package/dist/host/ctx.d.ts.map +1 -0
  193. package/dist/host/ctx.js +200 -0
  194. package/dist/host/ctx.js.map +1 -0
  195. package/dist/host/deadline.d.ts +12 -0
  196. package/dist/host/deadline.d.ts.map +1 -0
  197. package/dist/host/deadline.js +40 -0
  198. package/dist/host/deadline.js.map +1 -0
  199. package/dist/host/dependencies.d.ts +97 -0
  200. package/dist/host/dependencies.d.ts.map +1 -0
  201. package/dist/host/dependencies.js +148 -0
  202. package/dist/host/dependencies.js.map +1 -0
  203. package/dist/host/destination.d.ts +48 -0
  204. package/dist/host/destination.d.ts.map +1 -0
  205. package/dist/host/destination.js +101 -0
  206. package/dist/host/destination.js.map +1 -0
  207. package/dist/host/events.d.ts +114 -0
  208. package/dist/host/events.d.ts.map +1 -0
  209. package/dist/host/events.js +191 -0
  210. package/dist/host/events.js.map +1 -0
  211. package/dist/host/facet.d.ts +106 -0
  212. package/dist/host/facet.d.ts.map +1 -0
  213. package/dist/host/facet.js +55 -0
  214. package/dist/host/facet.js.map +1 -0
  215. package/dist/host/follow.d.ts +52 -0
  216. package/dist/host/follow.d.ts.map +1 -0
  217. package/dist/host/follow.js +207 -0
  218. package/dist/host/follow.js.map +1 -0
  219. package/dist/host/host-data.d.ts +62 -0
  220. package/dist/host/host-data.d.ts.map +1 -0
  221. package/dist/host/host-data.js +229 -0
  222. package/dist/host/host-data.js.map +1 -0
  223. package/dist/host/host.d.ts +641 -0
  224. package/dist/host/host.d.ts.map +1 -0
  225. package/dist/host/host.js +1449 -0
  226. package/dist/host/host.js.map +1 -0
  227. package/dist/host/index.d.ts +20 -0
  228. package/dist/host/index.d.ts.map +1 -0
  229. package/dist/host/index.js +7 -0
  230. package/dist/host/index.js.map +1 -0
  231. package/dist/host/internal.d.ts +13 -0
  232. package/dist/host/internal.d.ts.map +1 -0
  233. package/dist/host/internal.js +11 -0
  234. package/dist/host/internal.js.map +1 -0
  235. package/dist/host/list.d.ts +52 -0
  236. package/dist/host/list.d.ts.map +1 -0
  237. package/dist/host/list.js +149 -0
  238. package/dist/host/list.js.map +1 -0
  239. package/dist/host/members.d.ts +58 -0
  240. package/dist/host/members.d.ts.map +1 -0
  241. package/dist/host/members.js +178 -0
  242. package/dist/host/members.js.map +1 -0
  243. package/dist/host/named-query.d.ts +67 -0
  244. package/dist/host/named-query.d.ts.map +1 -0
  245. package/dist/host/named-query.js +166 -0
  246. package/dist/host/named-query.js.map +1 -0
  247. package/dist/host/native.d.ts +64 -0
  248. package/dist/host/native.d.ts.map +1 -0
  249. package/dist/host/native.js +126 -0
  250. package/dist/host/native.js.map +1 -0
  251. package/dist/host/object.d.ts +388 -0
  252. package/dist/host/object.d.ts.map +1 -0
  253. package/dist/host/object.js +1527 -0
  254. package/dist/host/object.js.map +1 -0
  255. package/dist/host/old-work.d.ts +34 -0
  256. package/dist/host/old-work.d.ts.map +1 -0
  257. package/dist/host/old-work.js +52 -0
  258. package/dist/host/old-work.js.map +1 -0
  259. package/dist/host/parked.d.ts +23 -0
  260. package/dist/host/parked.d.ts.map +1 -0
  261. package/dist/host/parked.js +79 -0
  262. package/dist/host/parked.js.map +1 -0
  263. package/dist/host/presence.d.ts +34 -0
  264. package/dist/host/presence.d.ts.map +1 -0
  265. package/dist/host/presence.js +117 -0
  266. package/dist/host/presence.js.map +1 -0
  267. package/dist/host/query-reader.d.ts +80 -0
  268. package/dist/host/query-reader.d.ts.map +1 -0
  269. package/dist/host/query-reader.js +182 -0
  270. package/dist/host/query-reader.js.map +1 -0
  271. package/dist/host/read-declarations.d.ts +75 -0
  272. package/dist/host/read-declarations.d.ts.map +1 -0
  273. package/dist/host/read-declarations.js +152 -0
  274. package/dist/host/read-declarations.js.map +1 -0
  275. package/dist/host/readiness.d.ts +27 -0
  276. package/dist/host/readiness.d.ts.map +1 -0
  277. package/dist/host/readiness.js +134 -0
  278. package/dist/host/readiness.js.map +1 -0
  279. package/dist/host/ref-state.d.ts +53 -0
  280. package/dist/host/ref-state.d.ts.map +1 -0
  281. package/dist/host/ref-state.js +83 -0
  282. package/dist/host/ref-state.js.map +1 -0
  283. package/dist/host/reference-events.d.ts +51 -0
  284. package/dist/host/reference-events.d.ts.map +1 -0
  285. package/dist/host/reference-events.js +133 -0
  286. package/dist/host/reference-events.js.map +1 -0
  287. package/dist/host/reference-keys.d.ts +36 -0
  288. package/dist/host/reference-keys.d.ts.map +1 -0
  289. package/dist/host/reference-keys.js +168 -0
  290. package/dist/host/reference-keys.js.map +1 -0
  291. package/dist/host/reference-source.d.ts +77 -0
  292. package/dist/host/reference-source.d.ts.map +1 -0
  293. package/dist/host/reference-source.js +326 -0
  294. package/dist/host/reference-source.js.map +1 -0
  295. package/dist/host/reference.d.ts +377 -0
  296. package/dist/host/reference.d.ts.map +1 -0
  297. package/dist/host/reference.js +986 -0
  298. package/dist/host/reference.js.map +1 -0
  299. package/dist/host/reload-cycle.d.ts +16 -0
  300. package/dist/host/reload-cycle.d.ts.map +1 -0
  301. package/dist/host/reload-cycle.js +81 -0
  302. package/dist/host/reload-cycle.js.map +1 -0
  303. package/dist/host/retry-on.d.ts +28 -0
  304. package/dist/host/retry-on.d.ts.map +1 -0
  305. package/dist/host/retry-on.js +52 -0
  306. package/dist/host/retry-on.js.map +1 -0
  307. package/dist/host/revocation.d.ts +16 -0
  308. package/dist/host/revocation.d.ts.map +1 -0
  309. package/dist/host/revocation.js +27 -0
  310. package/dist/host/revocation.js.map +1 -0
  311. package/dist/host/root.d.ts +37 -0
  312. package/dist/host/root.d.ts.map +1 -0
  313. package/dist/host/root.js +68 -0
  314. package/dist/host/root.js.map +1 -0
  315. package/dist/host/route-admission.d.ts +24 -0
  316. package/dist/host/route-admission.d.ts.map +1 -0
  317. package/dist/host/route-admission.js +238 -0
  318. package/dist/host/route-admission.js.map +1 -0
  319. package/dist/host/route.d.ts +88 -0
  320. package/dist/host/route.d.ts.map +1 -0
  321. package/dist/host/route.js +247 -0
  322. package/dist/host/route.js.map +1 -0
  323. package/dist/host/routines.d.ts +78 -0
  324. package/dist/host/routines.d.ts.map +1 -0
  325. package/dist/host/routines.js +398 -0
  326. package/dist/host/routines.js.map +1 -0
  327. package/dist/host/sleep.d.ts +9 -0
  328. package/dist/host/sleep.d.ts.map +1 -0
  329. package/dist/host/sleep.js +40 -0
  330. package/dist/host/sleep.js.map +1 -0
  331. package/dist/host/staging.d.ts +100 -0
  332. package/dist/host/staging.d.ts.map +1 -0
  333. package/dist/host/staging.js +413 -0
  334. package/dist/host/staging.js.map +1 -0
  335. package/dist/host/tiling.d.ts +57 -0
  336. package/dist/host/tiling.d.ts.map +1 -0
  337. package/dist/host/tiling.js +269 -0
  338. package/dist/host/tiling.js.map +1 -0
  339. package/dist/host/unbound-clock.d.ts +23 -0
  340. package/dist/host/unbound-clock.d.ts.map +1 -0
  341. package/dist/host/unbound-clock.js +58 -0
  342. package/dist/host/unbound-clock.js.map +1 -0
  343. package/dist/host/unbound.d.ts +37 -0
  344. package/dist/host/unbound.d.ts.map +1 -0
  345. package/dist/host/unbound.js +88 -0
  346. package/dist/host/unbound.js.map +1 -0
  347. package/dist/host/uuid.d.ts +3 -0
  348. package/dist/host/uuid.d.ts.map +1 -0
  349. package/dist/host/uuid.js +38 -0
  350. package/dist/host/uuid.js.map +1 -0
  351. package/dist/index.d.ts +28 -0
  352. package/dist/index.d.ts.map +1 -0
  353. package/dist/index.js +21 -0
  354. package/dist/index.js.map +1 -0
  355. package/dist/jobs/definition.d.ts +96 -0
  356. package/dist/jobs/definition.d.ts.map +1 -0
  357. package/dist/jobs/definition.js +83 -0
  358. package/dist/jobs/definition.js.map +1 -0
  359. package/dist/jobs/index.d.ts +5 -0
  360. package/dist/jobs/index.d.ts.map +1 -0
  361. package/dist/jobs/index.js +3 -0
  362. package/dist/jobs/index.js.map +1 -0
  363. package/dist/jobs/internal.d.ts +3 -0
  364. package/dist/jobs/internal.d.ts.map +1 -0
  365. package/dist/jobs/internal.js +4 -0
  366. package/dist/jobs/internal.js.map +1 -0
  367. package/dist/jobs/job.d.ts +149 -0
  368. package/dist/jobs/job.d.ts.map +1 -0
  369. package/dist/jobs/job.js +387 -0
  370. package/dist/jobs/job.js.map +1 -0
  371. package/dist/jobs/persisted.d.ts +38 -0
  372. package/dist/jobs/persisted.d.ts.map +1 -0
  373. package/dist/jobs/persisted.js +95 -0
  374. package/dist/jobs/persisted.js.map +1 -0
  375. package/dist/jobs/records.d.ts +231 -0
  376. package/dist/jobs/records.d.ts.map +1 -0
  377. package/dist/jobs/records.js +871 -0
  378. package/dist/jobs/records.js.map +1 -0
  379. package/dist/jobs/run-states.d.ts +69 -0
  380. package/dist/jobs/run-states.d.ts.map +1 -0
  381. package/dist/jobs/run-states.js +228 -0
  382. package/dist/jobs/run-states.js.map +1 -0
  383. package/dist/jobs/run.d.ts +117 -0
  384. package/dist/jobs/run.d.ts.map +1 -0
  385. package/dist/jobs/run.js +204 -0
  386. package/dist/jobs/run.js.map +1 -0
  387. package/dist/jobs/running.d.ts +44 -0
  388. package/dist/jobs/running.d.ts.map +1 -0
  389. package/dist/jobs/running.js +117 -0
  390. package/dist/jobs/running.js.map +1 -0
  391. package/dist/jobs/stored.d.ts +63 -0
  392. package/dist/jobs/stored.d.ts.map +1 -0
  393. package/dist/jobs/stored.js +55 -0
  394. package/dist/jobs/stored.js.map +1 -0
  395. package/dist/json.d.ts +18 -0
  396. package/dist/json.d.ts.map +1 -0
  397. package/dist/json.js +124 -0
  398. package/dist/json.js.map +1 -0
  399. package/dist/link/binary.d.ts +4 -0
  400. package/dist/link/binary.d.ts.map +1 -0
  401. package/dist/link/binary.js +574 -0
  402. package/dist/link/binary.js.map +1 -0
  403. package/dist/link/channel.d.ts +78 -0
  404. package/dist/link/channel.d.ts.map +1 -0
  405. package/dist/link/channel.js +252 -0
  406. package/dist/link/channel.js.map +1 -0
  407. package/dist/link/errors.d.ts +7 -0
  408. package/dist/link/errors.d.ts.map +1 -0
  409. package/dist/link/errors.js +21 -0
  410. package/dist/link/errors.js.map +1 -0
  411. package/dist/link/index.d.ts +8 -0
  412. package/dist/link/index.d.ts.map +1 -0
  413. package/dist/link/index.js +8 -0
  414. package/dist/link/index.js.map +1 -0
  415. package/dist/link/internal.d.ts +9 -0
  416. package/dist/link/internal.d.ts.map +1 -0
  417. package/dist/link/internal.js +10 -0
  418. package/dist/link/internal.js.map +1 -0
  419. package/dist/link/ipc.d.ts +22 -0
  420. package/dist/link/ipc.d.ts.map +1 -0
  421. package/dist/link/ipc.js +64 -0
  422. package/dist/link/ipc.js.map +1 -0
  423. package/dist/link/link.d.ts +34 -0
  424. package/dist/link/link.d.ts.map +1 -0
  425. package/dist/link/link.js +87 -0
  426. package/dist/link/link.js.map +1 -0
  427. package/dist/link/message.d.ts +278 -0
  428. package/dist/link/message.d.ts.map +1 -0
  429. package/dist/link/message.js +179 -0
  430. package/dist/link/message.js.map +1 -0
  431. package/dist/link/part.d.ts +80 -0
  432. package/dist/link/part.d.ts.map +1 -0
  433. package/dist/link/part.js +165 -0
  434. package/dist/link/part.js.map +1 -0
  435. package/dist/link/text.d.ts +6 -0
  436. package/dist/link/text.d.ts.map +1 -0
  437. package/dist/link/text.js +383 -0
  438. package/dist/link/text.js.map +1 -0
  439. package/dist/link/values.d.ts +40 -0
  440. package/dist/link/values.d.ts.map +1 -0
  441. package/dist/link/values.js +121 -0
  442. package/dist/link/values.js.map +1 -0
  443. package/dist/link/websocket.d.ts +26 -0
  444. package/dist/link/websocket.d.ts.map +1 -0
  445. package/dist/link/websocket.js +91 -0
  446. package/dist/link/websocket.js.map +1 -0
  447. package/dist/node/app/app.d.ts +283 -0
  448. package/dist/node/app/app.d.ts.map +1 -0
  449. package/dist/node/app/app.js +598 -0
  450. package/dist/node/app/app.js.map +1 -0
  451. package/dist/node/app/archive.d.ts +44 -0
  452. package/dist/node/app/archive.d.ts.map +1 -0
  453. package/dist/node/app/archive.js +212 -0
  454. package/dist/node/app/archive.js.map +1 -0
  455. package/dist/node/app/blobs.d.ts +23 -0
  456. package/dist/node/app/blobs.d.ts.map +1 -0
  457. package/dist/node/app/blobs.js +64 -0
  458. package/dist/node/app/blobs.js.map +1 -0
  459. package/dist/node/app/data.d.ts +40 -0
  460. package/dist/node/app/data.d.ts.map +1 -0
  461. package/dist/node/app/data.js +47 -0
  462. package/dist/node/app/data.js.map +1 -0
  463. package/dist/node/app/ephemeral-sign-ins.d.ts +20 -0
  464. package/dist/node/app/ephemeral-sign-ins.d.ts.map +1 -0
  465. package/dist/node/app/ephemeral-sign-ins.js +69 -0
  466. package/dist/node/app/ephemeral-sign-ins.js.map +1 -0
  467. package/dist/node/app/ephemeral.d.ts +11 -0
  468. package/dist/node/app/ephemeral.d.ts.map +1 -0
  469. package/dist/node/app/ephemeral.js +34 -0
  470. package/dist/node/app/ephemeral.js.map +1 -0
  471. package/dist/node/app/files-copy.d.ts +13 -0
  472. package/dist/node/app/files-copy.d.ts.map +1 -0
  473. package/dist/node/app/files-copy.js +86 -0
  474. package/dist/node/app/files-copy.js.map +1 -0
  475. package/dist/node/app/files-entry.d.ts +4 -0
  476. package/dist/node/app/files-entry.d.ts.map +1 -0
  477. package/dist/node/app/files-entry.js +7 -0
  478. package/dist/node/app/files-entry.js.map +1 -0
  479. package/dist/node/app/files-index.d.ts +180 -0
  480. package/dist/node/app/files-index.d.ts.map +1 -0
  481. package/dist/node/app/files-index.js +535 -0
  482. package/dist/node/app/files-index.js.map +1 -0
  483. package/dist/node/app/files.d.ts +388 -0
  484. package/dist/node/app/files.d.ts.map +1 -0
  485. package/dist/node/app/files.js +368 -0
  486. package/dist/node/app/files.js.map +1 -0
  487. package/dist/node/app/folder-views.d.ts +21 -0
  488. package/dist/node/app/folder-views.d.ts.map +1 -0
  489. package/dist/node/app/folder-views.js +55 -0
  490. package/dist/node/app/folder-views.js.map +1 -0
  491. package/dist/node/app/index.d.ts +12 -0
  492. package/dist/node/app/index.d.ts.map +1 -0
  493. package/dist/node/app/index.js +15 -0
  494. package/dist/node/app/index.js.map +1 -0
  495. package/dist/node/app/info.d.ts +70 -0
  496. package/dist/node/app/info.d.ts.map +1 -0
  497. package/dist/node/app/info.js +37 -0
  498. package/dist/node/app/info.js.map +1 -0
  499. package/dist/node/app/invite.d.ts +5 -0
  500. package/dist/node/app/invite.d.ts.map +1 -0
  501. package/dist/node/app/invite.js +64 -0
  502. package/dist/node/app/invite.js.map +1 -0
  503. package/dist/node/app/layout.d.ts +36 -0
  504. package/dist/node/app/layout.d.ts.map +1 -0
  505. package/dist/node/app/layout.js +87 -0
  506. package/dist/node/app/layout.js.map +1 -0
  507. package/dist/node/app/owner.d.ts +31 -0
  508. package/dist/node/app/owner.d.ts.map +1 -0
  509. package/dist/node/app/owner.js +104 -0
  510. package/dist/node/app/owner.js.map +1 -0
  511. package/dist/node/app/pairing.d.ts +55 -0
  512. package/dist/node/app/pairing.d.ts.map +1 -0
  513. package/dist/node/app/pairing.js +183 -0
  514. package/dist/node/app/pairing.js.map +1 -0
  515. package/dist/node/app/secrets.d.ts +16 -0
  516. package/dist/node/app/secrets.d.ts.map +1 -0
  517. package/dist/node/app/secrets.js +72 -0
  518. package/dist/node/app/secrets.js.map +1 -0
  519. package/dist/node/app/sign-ins.d.ts +74 -0
  520. package/dist/node/app/sign-ins.d.ts.map +1 -0
  521. package/dist/node/app/sign-ins.js +222 -0
  522. package/dist/node/app/sign-ins.js.map +1 -0
  523. package/dist/node/app/tar.d.ts +24 -0
  524. package/dist/node/app/tar.d.ts.map +1 -0
  525. package/dist/node/app/tar.js +167 -0
  526. package/dist/node/app/tar.js.map +1 -0
  527. package/dist/node/app/uploads.d.ts +37 -0
  528. package/dist/node/app/uploads.d.ts.map +1 -0
  529. package/dist/node/app/uploads.js +157 -0
  530. package/dist/node/app/uploads.js.map +1 -0
  531. package/dist/node/app/users.d.ts +39 -0
  532. package/dist/node/app/users.d.ts.map +1 -0
  533. package/dist/node/app/users.js +62 -0
  534. package/dist/node/app/users.js.map +1 -0
  535. package/dist/node/app/worker.d.ts +18 -0
  536. package/dist/node/app/worker.d.ts.map +1 -0
  537. package/dist/node/app/worker.js +84 -0
  538. package/dist/node/app/worker.js.map +1 -0
  539. package/dist/node/compression.d.ts +7 -0
  540. package/dist/node/compression.d.ts.map +1 -0
  541. package/dist/node/compression.js +25 -0
  542. package/dist/node/compression.js.map +1 -0
  543. package/dist/node/http/admission.d.ts +64 -0
  544. package/dist/node/http/admission.d.ts.map +1 -0
  545. package/dist/node/http/admission.js +137 -0
  546. package/dist/node/http/admission.js.map +1 -0
  547. package/dist/node/http/authenticate.d.ts +21 -0
  548. package/dist/node/http/authenticate.d.ts.map +1 -0
  549. package/dist/node/http/authenticate.js +34 -0
  550. package/dist/node/http/authenticate.js.map +1 -0
  551. package/dist/node/http/cookies.d.ts +32 -0
  552. package/dist/node/http/cookies.d.ts.map +1 -0
  553. package/dist/node/http/cookies.js +70 -0
  554. package/dist/node/http/cookies.js.map +1 -0
  555. package/dist/node/http/file.d.ts +23 -0
  556. package/dist/node/http/file.d.ts.map +1 -0
  557. package/dist/node/http/file.js +94 -0
  558. package/dist/node/http/file.js.map +1 -0
  559. package/dist/node/http/headers.d.ts +37 -0
  560. package/dist/node/http/headers.d.ts.map +1 -0
  561. package/dist/node/http/headers.js +136 -0
  562. package/dist/node/http/headers.js.map +1 -0
  563. package/dist/node/http/http.d.ts +114 -0
  564. package/dist/node/http/http.d.ts.map +1 -0
  565. package/dist/node/http/http.js +524 -0
  566. package/dist/node/http/http.js.map +1 -0
  567. package/dist/node/http/incoming.d.ts +19 -0
  568. package/dist/node/http/incoming.d.ts.map +1 -0
  569. package/dist/node/http/incoming.js +31 -0
  570. package/dist/node/http/incoming.js.map +1 -0
  571. package/dist/node/http/index.d.ts +11 -0
  572. package/dist/node/http/index.d.ts.map +1 -0
  573. package/dist/node/http/index.js +12 -0
  574. package/dist/node/http/index.js.map +1 -0
  575. package/dist/node/http/node.d.ts +78 -0
  576. package/dist/node/http/node.d.ts.map +1 -0
  577. package/dist/node/http/node.js +291 -0
  578. package/dist/node/http/node.js.map +1 -0
  579. package/dist/node/http/request.d.ts +60 -0
  580. package/dist/node/http/request.d.ts.map +1 -0
  581. package/dist/node/http/request.js +118 -0
  582. package/dist/node/http/request.js.map +1 -0
  583. package/dist/node/http/response.d.ts +63 -0
  584. package/dist/node/http/response.d.ts.map +1 -0
  585. package/dist/node/http/response.js +202 -0
  586. package/dist/node/http/response.js.map +1 -0
  587. package/dist/node/http/router.d.ts +132 -0
  588. package/dist/node/http/router.d.ts.map +1 -0
  589. package/dist/node/http/router.js +267 -0
  590. package/dist/node/http/router.js.map +1 -0
  591. package/dist/node/http/upgrades.d.ts +62 -0
  592. package/dist/node/http/upgrades.d.ts.map +1 -0
  593. package/dist/node/http/upgrades.js +194 -0
  594. package/dist/node/http/upgrades.js.map +1 -0
  595. package/dist/node/plugins/base-inputs.d.ts +14 -0
  596. package/dist/node/plugins/base-inputs.d.ts.map +1 -0
  597. package/dist/node/plugins/base-inputs.js +33 -0
  598. package/dist/node/plugins/base-inputs.js.map +1 -0
  599. package/dist/node/plugins/build.d.ts +77 -0
  600. package/dist/node/plugins/build.d.ts.map +1 -0
  601. package/dist/node/plugins/build.js +577 -0
  602. package/dist/node/plugins/build.js.map +1 -0
  603. package/dist/node/plugins/css-modules.d.ts +13 -0
  604. package/dist/node/plugins/css-modules.d.ts.map +1 -0
  605. package/dist/node/plugins/css-modules.js +58 -0
  606. package/dist/node/plugins/css-modules.js.map +1 -0
  607. package/dist/node/plugins/discover.d.ts +67 -0
  608. package/dist/node/plugins/discover.d.ts.map +1 -0
  609. package/dist/node/plugins/discover.js +369 -0
  610. package/dist/node/plugins/discover.js.map +1 -0
  611. package/dist/node/plugins/evaluate.d.ts +33 -0
  612. package/dist/node/plugins/evaluate.d.ts.map +1 -0
  613. package/dist/node/plugins/evaluate.js +121 -0
  614. package/dist/node/plugins/evaluate.js.map +1 -0
  615. package/dist/node/plugins/index.d.ts +11 -0
  616. package/dist/node/plugins/index.d.ts.map +1 -0
  617. package/dist/node/plugins/index.js +13 -0
  618. package/dist/node/plugins/index.js.map +1 -0
  619. package/dist/node/plugins/install.d.ts +40 -0
  620. package/dist/node/plugins/install.d.ts.map +1 -0
  621. package/dist/node/plugins/install.js +215 -0
  622. package/dist/node/plugins/install.js.map +1 -0
  623. package/dist/node/plugins/plugins.d.ts +165 -0
  624. package/dist/node/plugins/plugins.d.ts.map +1 -0
  625. package/dist/node/plugins/plugins.js +268 -0
  626. package/dist/node/plugins/plugins.js.map +1 -0
  627. package/dist/node/plugins/runtime.d.ts +57 -0
  628. package/dist/node/plugins/runtime.d.ts.map +1 -0
  629. package/dist/node/plugins/runtime.js +92 -0
  630. package/dist/node/plugins/runtime.js.map +1 -0
  631. package/dist/node/plugins/stack.d.ts +16 -0
  632. package/dist/node/plugins/stack.d.ts.map +1 -0
  633. package/dist/node/plugins/stack.js +70 -0
  634. package/dist/node/plugins/stack.js.map +1 -0
  635. package/dist/node/plugins/testing.d.ts +58 -0
  636. package/dist/node/plugins/testing.d.ts.map +1 -0
  637. package/dist/node/plugins/testing.js +210 -0
  638. package/dist/node/plugins/testing.js.map +1 -0
  639. package/dist/node/plugins/watcher.d.ts +69 -0
  640. package/dist/node/plugins/watcher.d.ts.map +1 -0
  641. package/dist/node/plugins/watcher.js +622 -0
  642. package/dist/node/plugins/watcher.js.map +1 -0
  643. package/dist/node/surfaces/bundle.d.ts +40 -0
  644. package/dist/node/surfaces/bundle.d.ts.map +1 -0
  645. package/dist/node/surfaces/bundle.js +121 -0
  646. package/dist/node/surfaces/bundle.js.map +1 -0
  647. package/dist/node/surfaces/current.d.ts +17 -0
  648. package/dist/node/surfaces/current.d.ts.map +1 -0
  649. package/dist/node/surfaces/current.js +54 -0
  650. package/dist/node/surfaces/current.js.map +1 -0
  651. package/dist/node/surfaces/index.d.ts +6 -0
  652. package/dist/node/surfaces/index.d.ts.map +1 -0
  653. package/dist/node/surfaces/index.js +6 -0
  654. package/dist/node/surfaces/index.js.map +1 -0
  655. package/dist/node/surfaces/published.d.ts +27 -0
  656. package/dist/node/surfaces/published.d.ts.map +1 -0
  657. package/dist/node/surfaces/published.js +142 -0
  658. package/dist/node/surfaces/published.js.map +1 -0
  659. package/dist/node/surfaces/served.d.ts +17 -0
  660. package/dist/node/surfaces/served.d.ts.map +1 -0
  661. package/dist/node/surfaces/served.js +44 -0
  662. package/dist/node/surfaces/served.js.map +1 -0
  663. package/dist/node/surfaces/surface-build.d.ts +53 -0
  664. package/dist/node/surfaces/surface-build.d.ts.map +1 -0
  665. package/dist/node/surfaces/surface-build.js +105 -0
  666. package/dist/node/surfaces/surface-build.js.map +1 -0
  667. package/dist/node/surfaces/tui.d.ts +42 -0
  668. package/dist/node/surfaces/tui.d.ts.map +1 -0
  669. package/dist/node/surfaces/tui.js +59 -0
  670. package/dist/node/surfaces/tui.js.map +1 -0
  671. package/dist/node/surfaces/web.d.ts +82 -0
  672. package/dist/node/surfaces/web.d.ts.map +1 -0
  673. package/dist/node/surfaces/web.js +122 -0
  674. package/dist/node/surfaces/web.js.map +1 -0
  675. package/dist/node/tui/actions.d.ts +49 -0
  676. package/dist/node/tui/actions.d.ts.map +1 -0
  677. package/dist/node/tui/actions.js +195 -0
  678. package/dist/node/tui/actions.js.map +1 -0
  679. package/dist/node/tui/credentials.d.ts +17 -0
  680. package/dist/node/tui/credentials.d.ts.map +1 -0
  681. package/dist/node/tui/credentials.js +54 -0
  682. package/dist/node/tui/credentials.js.map +1 -0
  683. package/dist/node/tui/filter.d.ts +5 -0
  684. package/dist/node/tui/filter.d.ts.map +1 -0
  685. package/dist/node/tui/filter.js +79 -0
  686. package/dist/node/tui/filter.js.map +1 -0
  687. package/dist/node/tui/index.d.ts +6 -0
  688. package/dist/node/tui/index.d.ts.map +1 -0
  689. package/dist/node/tui/index.js +6 -0
  690. package/dist/node/tui/index.js.map +1 -0
  691. package/dist/node/tui/launcher.d.ts +40 -0
  692. package/dist/node/tui/launcher.d.ts.map +1 -0
  693. package/dist/node/tui/launcher.js +439 -0
  694. package/dist/node/tui/launcher.js.map +1 -0
  695. package/dist/node/tui/pipe.d.ts +18 -0
  696. package/dist/node/tui/pipe.d.ts.map +1 -0
  697. package/dist/node/tui/pipe.js +134 -0
  698. package/dist/node/tui/pipe.js.map +1 -0
  699. package/dist/node/tui/sandbox.d.ts +54 -0
  700. package/dist/node/tui/sandbox.d.ts.map +1 -0
  701. package/dist/node/tui/sandbox.js +431 -0
  702. package/dist/node/tui/sandbox.js.map +1 -0
  703. package/dist/node/workers/base.d.ts +30 -0
  704. package/dist/node/workers/base.d.ts.map +1 -0
  705. package/dist/node/workers/base.js +260 -0
  706. package/dist/node/workers/base.js.map +1 -0
  707. package/dist/node/workers/child.d.ts +4 -0
  708. package/dist/node/workers/child.d.ts.map +1 -0
  709. package/dist/node/workers/child.js +6 -0
  710. package/dist/node/workers/child.js.map +1 -0
  711. package/dist/node/workers/control.d.ts +83 -0
  712. package/dist/node/workers/control.d.ts.map +1 -0
  713. package/dist/node/workers/control.js +77 -0
  714. package/dist/node/workers/control.js.map +1 -0
  715. package/dist/node/workers/index.d.ts +4 -0
  716. package/dist/node/workers/index.d.ts.map +1 -0
  717. package/dist/node/workers/index.js +7 -0
  718. package/dist/node/workers/index.js.map +1 -0
  719. package/dist/node/workers/lock.d.ts +30 -0
  720. package/dist/node/workers/lock.d.ts.map +1 -0
  721. package/dist/node/workers/lock.js +180 -0
  722. package/dist/node/workers/lock.js.map +1 -0
  723. package/dist/node/workers/main.d.ts +46 -0
  724. package/dist/node/workers/main.d.ts.map +1 -0
  725. package/dist/node/workers/main.js +230 -0
  726. package/dist/node/workers/main.js.map +1 -0
  727. package/dist/node/workers/process.d.ts +43 -0
  728. package/dist/node/workers/process.d.ts.map +1 -0
  729. package/dist/node/workers/process.js +137 -0
  730. package/dist/node/workers/process.js.map +1 -0
  731. package/dist/node/workers/workers.d.ts +144 -0
  732. package/dist/node/workers/workers.d.ts.map +1 -0
  733. package/dist/node/workers/workers.js +723 -0
  734. package/dist/node/workers/workers.js.map +1 -0
  735. package/dist/output.d.ts +91 -0
  736. package/dist/output.d.ts.map +1 -0
  737. package/dist/output.js +362 -0
  738. package/dist/output.js.map +1 -0
  739. package/dist/react/hooks.d.ts +61 -0
  740. package/dist/react/hooks.d.ts.map +1 -0
  741. package/dist/react/hooks.js +119 -0
  742. package/dist/react/hooks.js.map +1 -0
  743. package/dist/react/index.d.ts +4 -0
  744. package/dist/react/index.d.ts.map +1 -0
  745. package/dist/react/index.js +4 -0
  746. package/dist/react/index.js.map +1 -0
  747. package/dist/react/stores.d.ts +9 -0
  748. package/dist/react/stores.d.ts.map +1 -0
  749. package/dist/react/stores.js +37 -0
  750. package/dist/react/stores.js.map +1 -0
  751. package/dist/registries/contribution.d.ts +50 -0
  752. package/dist/registries/contribution.d.ts.map +1 -0
  753. package/dist/registries/contribution.js +129 -0
  754. package/dist/registries/contribution.js.map +1 -0
  755. package/dist/registries/entries.d.ts +18 -0
  756. package/dist/registries/entries.d.ts.map +1 -0
  757. package/dist/registries/entries.js +42 -0
  758. package/dist/registries/entries.js.map +1 -0
  759. package/dist/registries/index.d.ts +3 -0
  760. package/dist/registries/index.d.ts.map +1 -0
  761. package/dist/registries/index.js +5 -0
  762. package/dist/registries/index.js.map +1 -0
  763. package/dist/registries/internal.d.ts +4 -0
  764. package/dist/registries/internal.d.ts.map +1 -0
  765. package/dist/registries/internal.js +5 -0
  766. package/dist/registries/internal.js.map +1 -0
  767. package/dist/registries/record.d.ts +115 -0
  768. package/dist/registries/record.d.ts.map +1 -0
  769. package/dist/registries/record.js +283 -0
  770. package/dist/registries/record.js.map +1 -0
  771. package/dist/registries/registry.d.ts +74 -0
  772. package/dist/registries/registry.d.ts.map +1 -0
  773. package/dist/registries/registry.js +14 -0
  774. package/dist/registries/registry.js.map +1 -0
  775. package/dist/registries/value.d.ts +48 -0
  776. package/dist/registries/value.d.ts.map +1 -0
  777. package/dist/registries/value.js +224 -0
  778. package/dist/registries/value.js.map +1 -0
  779. package/dist/remote/calls.d.ts +34 -0
  780. package/dist/remote/calls.d.ts.map +1 -0
  781. package/dist/remote/calls.js +75 -0
  782. package/dist/remote/calls.js.map +1 -0
  783. package/dist/remote/consumer.d.ts +59 -0
  784. package/dist/remote/consumer.d.ts.map +1 -0
  785. package/dist/remote/consumer.js +468 -0
  786. package/dist/remote/consumer.js.map +1 -0
  787. package/dist/remote/hold.d.ts +147 -0
  788. package/dist/remote/hold.d.ts.map +1 -0
  789. package/dist/remote/hold.js +653 -0
  790. package/dist/remote/hold.js.map +1 -0
  791. package/dist/remote/host-link.d.ts +81 -0
  792. package/dist/remote/host-link.d.ts.map +1 -0
  793. package/dist/remote/host-link.js +198 -0
  794. package/dist/remote/host-link.js.map +1 -0
  795. package/dist/remote/internal.d.ts +6 -0
  796. package/dist/remote/internal.d.ts.map +1 -0
  797. package/dist/remote/internal.js +6 -0
  798. package/dist/remote/internal.js.map +1 -0
  799. package/dist/remote/path.d.ts +105 -0
  800. package/dist/remote/path.d.ts.map +1 -0
  801. package/dist/remote/path.js +197 -0
  802. package/dist/remote/path.js.map +1 -0
  803. package/dist/remote/provider.d.ts +113 -0
  804. package/dist/remote/provider.d.ts.map +1 -0
  805. package/dist/remote/provider.js +787 -0
  806. package/dist/remote/provider.js.map +1 -0
  807. package/dist/remote/relay.d.ts +126 -0
  808. package/dist/remote/relay.d.ts.map +1 -0
  809. package/dist/remote/relay.js +334 -0
  810. package/dist/remote/relay.js.map +1 -0
  811. package/dist/remote/remote-object.d.ts +181 -0
  812. package/dist/remote/remote-object.d.ts.map +1 -0
  813. package/dist/remote/remote-object.js +683 -0
  814. package/dist/remote/remote-object.js.map +1 -0
  815. package/dist/remote/replica.d.ts +66 -0
  816. package/dist/remote/replica.d.ts.map +1 -0
  817. package/dist/remote/replica.js +148 -0
  818. package/dist/remote/replica.js.map +1 -0
  819. package/dist/sqlite/cloudflare.d.ts +54 -0
  820. package/dist/sqlite/cloudflare.d.ts.map +1 -0
  821. package/dist/sqlite/cloudflare.js +144 -0
  822. package/dist/sqlite/cloudflare.js.map +1 -0
  823. package/dist/sqlite/database.d.ts +40 -0
  824. package/dist/sqlite/database.d.ts.map +1 -0
  825. package/dist/sqlite/database.js +2 -0
  826. package/dist/sqlite/database.js.map +1 -0
  827. package/dist/sqlite/index.d.ts +4 -0
  828. package/dist/sqlite/index.d.ts.map +1 -0
  829. package/dist/sqlite/index.js +3 -0
  830. package/dist/sqlite/index.js.map +1 -0
  831. package/dist/sqlite/migrations.d.ts +10 -0
  832. package/dist/sqlite/migrations.d.ts.map +1 -0
  833. package/dist/sqlite/migrations.js +33 -0
  834. package/dist/sqlite/migrations.js.map +1 -0
  835. package/dist/sqlite/node.d.ts +49 -0
  836. package/dist/sqlite/node.d.ts.map +1 -0
  837. package/dist/sqlite/node.js +197 -0
  838. package/dist/sqlite/node.js.map +1 -0
  839. package/dist/sqlite/schema.d.ts +3 -0
  840. package/dist/sqlite/schema.d.ts.map +1 -0
  841. package/dist/sqlite/schema.js +10 -0
  842. package/dist/sqlite/schema.js.map +1 -0
  843. package/dist/state/batch.d.ts +64 -0
  844. package/dist/state/batch.d.ts.map +1 -0
  845. package/dist/state/batch.js +164 -0
  846. package/dist/state/batch.js.map +1 -0
  847. package/dist/state/derive.d.ts +56 -0
  848. package/dist/state/derive.d.ts.map +1 -0
  849. package/dist/state/derive.js +192 -0
  850. package/dist/state/derive.js.map +1 -0
  851. package/dist/state/framed.d.ts +43 -0
  852. package/dist/state/framed.d.ts.map +1 -0
  853. package/dist/state/framed.js +121 -0
  854. package/dist/state/framed.js.map +1 -0
  855. package/dist/state/index.d.ts +6 -0
  856. package/dist/state/index.d.ts.map +1 -0
  857. package/dist/state/index.js +4 -0
  858. package/dist/state/index.js.map +1 -0
  859. package/dist/state/internal.d.ts +7 -0
  860. package/dist/state/internal.d.ts.map +1 -0
  861. package/dist/state/internal.js +9 -0
  862. package/dist/state/internal.js.map +1 -0
  863. package/dist/state/native-source.d.ts +106 -0
  864. package/dist/state/native-source.d.ts.map +1 -0
  865. package/dist/state/native-source.js +240 -0
  866. package/dist/state/native-source.js.map +1 -0
  867. package/dist/state/watchable.d.ts +114 -0
  868. package/dist/state/watchable.d.ts.map +1 -0
  869. package/dist/state/watchable.js +156 -0
  870. package/dist/state/watchable.js.map +1 -0
  871. package/dist/state/writable.d.ts +32 -0
  872. package/dist/state/writable.d.ts.map +1 -0
  873. package/dist/state/writable.js +49 -0
  874. package/dist/state/writable.js.map +1 -0
  875. package/dist/store/adapter.d.ts +67 -0
  876. package/dist/store/adapter.d.ts.map +1 -0
  877. package/dist/store/adapter.js +118 -0
  878. package/dist/store/adapter.js.map +1 -0
  879. package/dist/store/allocator.d.ts +17 -0
  880. package/dist/store/allocator.d.ts.map +1 -0
  881. package/dist/store/allocator.js +30 -0
  882. package/dist/store/allocator.js.map +1 -0
  883. package/dist/store/applier.d.ts +8 -0
  884. package/dist/store/applier.d.ts.map +1 -0
  885. package/dist/store/applier.js +390 -0
  886. package/dist/store/applier.js.map +1 -0
  887. package/dist/store/apply-batch.d.ts +12 -0
  888. package/dist/store/apply-batch.d.ts.map +1 -0
  889. package/dist/store/apply-batch.js +83 -0
  890. package/dist/store/apply-batch.js.map +1 -0
  891. package/dist/store/archive.d.ts +36 -0
  892. package/dist/store/archive.d.ts.map +1 -0
  893. package/dist/store/archive.js +140 -0
  894. package/dist/store/archive.js.map +1 -0
  895. package/dist/store/backend.d.ts +10 -0
  896. package/dist/store/backend.d.ts.map +1 -0
  897. package/dist/store/backend.js +15 -0
  898. package/dist/store/backend.js.map +1 -0
  899. package/dist/store/catalog.d.ts +24 -0
  900. package/dist/store/catalog.d.ts.map +1 -0
  901. package/dist/store/catalog.js +17 -0
  902. package/dist/store/catalog.js.map +1 -0
  903. package/dist/store/claims.d.ts +23 -0
  904. package/dist/store/claims.d.ts.map +1 -0
  905. package/dist/store/claims.js +65 -0
  906. package/dist/store/claims.js.map +1 -0
  907. package/dist/store/column-set.d.ts +64 -0
  908. package/dist/store/column-set.d.ts.map +1 -0
  909. package/dist/store/column-set.js +96 -0
  910. package/dist/store/column-set.js.map +1 -0
  911. package/dist/store/columns.d.ts +93 -0
  912. package/dist/store/columns.d.ts.map +1 -0
  913. package/dist/store/columns.js +87 -0
  914. package/dist/store/columns.js.map +1 -0
  915. package/dist/store/engine.d.ts +182 -0
  916. package/dist/store/engine.d.ts.map +1 -0
  917. package/dist/store/engine.js +290 -0
  918. package/dist/store/engine.js.map +1 -0
  919. package/dist/store/evaluate.d.ts +17 -0
  920. package/dist/store/evaluate.d.ts.map +1 -0
  921. package/dist/store/evaluate.js +131 -0
  922. package/dist/store/evaluate.js.map +1 -0
  923. package/dist/store/export.d.ts +30 -0
  924. package/dist/store/export.d.ts.map +1 -0
  925. package/dist/store/export.js +221 -0
  926. package/dist/store/export.js.map +1 -0
  927. package/dist/store/expression.d.ts +254 -0
  928. package/dist/store/expression.d.ts.map +1 -0
  929. package/dist/store/expression.js +577 -0
  930. package/dist/store/expression.js.map +1 -0
  931. package/dist/store/host-column.d.ts +22 -0
  932. package/dist/store/host-column.d.ts.map +1 -0
  933. package/dist/store/host-column.js +36 -0
  934. package/dist/store/host-column.js.map +1 -0
  935. package/dist/store/host-data.d.ts +100 -0
  936. package/dist/store/host-data.d.ts.map +1 -0
  937. package/dist/store/host-data.js +397 -0
  938. package/dist/store/host-data.js.map +1 -0
  939. package/dist/store/import-migration.d.ts +19 -0
  940. package/dist/store/import-migration.d.ts.map +1 -0
  941. package/dist/store/import-migration.js +124 -0
  942. package/dist/store/import-migration.js.map +1 -0
  943. package/dist/store/import.d.ts +12 -0
  944. package/dist/store/import.d.ts.map +1 -0
  945. package/dist/store/import.js +279 -0
  946. package/dist/store/import.js.map +1 -0
  947. package/dist/store/index.d.ts +19 -0
  948. package/dist/store/index.d.ts.map +1 -0
  949. package/dist/store/index.js +16 -0
  950. package/dist/store/index.js.map +1 -0
  951. package/dist/store/json-column.d.ts +33 -0
  952. package/dist/store/json-column.d.ts.map +1 -0
  953. package/dist/store/json-column.js +62 -0
  954. package/dist/store/json-column.js.map +1 -0
  955. package/dist/store/jsonl.d.ts +9 -0
  956. package/dist/store/jsonl.d.ts.map +1 -0
  957. package/dist/store/jsonl.js +61 -0
  958. package/dist/store/jsonl.js.map +1 -0
  959. package/dist/store/live-query.d.ts +72 -0
  960. package/dist/store/live-query.d.ts.map +1 -0
  961. package/dist/store/live-query.js +162 -0
  962. package/dist/store/live-query.js.map +1 -0
  963. package/dist/store/open-query.d.ts +90 -0
  964. package/dist/store/open-query.d.ts.map +1 -0
  965. package/dist/store/open-query.js +201 -0
  966. package/dist/store/open-query.js.map +1 -0
  967. package/dist/store/outbox.d.ts +26 -0
  968. package/dist/store/outbox.d.ts.map +1 -0
  969. package/dist/store/outbox.js +80 -0
  970. package/dist/store/outbox.js.map +1 -0
  971. package/dist/store/page.d.ts +14 -0
  972. package/dist/store/page.d.ts.map +1 -0
  973. package/dist/store/page.js +26 -0
  974. package/dist/store/page.js.map +1 -0
  975. package/dist/store/query.d.ts +65 -0
  976. package/dist/store/query.d.ts.map +1 -0
  977. package/dist/store/query.js +193 -0
  978. package/dist/store/query.js.map +1 -0
  979. package/dist/store/read-plan.d.ts +74 -0
  980. package/dist/store/read-plan.d.ts.map +1 -0
  981. package/dist/store/read-plan.js +324 -0
  982. package/dist/store/read-plan.js.map +1 -0
  983. package/dist/store/read.d.ts +81 -0
  984. package/dist/store/read.d.ts.map +1 -0
  985. package/dist/store/read.js +113 -0
  986. package/dist/store/read.js.map +1 -0
  987. package/dist/store/reads.d.ts +79 -0
  988. package/dist/store/reads.d.ts.map +1 -0
  989. package/dist/store/reads.js +255 -0
  990. package/dist/store/reads.js.map +1 -0
  991. package/dist/store/refusal.d.ts +15 -0
  992. package/dist/store/refusal.d.ts.map +1 -0
  993. package/dist/store/refusal.js +36 -0
  994. package/dist/store/refusal.js.map +1 -0
  995. package/dist/store/rows.d.ts +96 -0
  996. package/dist/store/rows.d.ts.map +1 -0
  997. package/dist/store/rows.js +222 -0
  998. package/dist/store/rows.js.map +1 -0
  999. package/dist/store/schema.d.ts +25 -0
  1000. package/dist/store/schema.d.ts.map +1 -0
  1001. package/dist/store/schema.js +123 -0
  1002. package/dist/store/schema.js.map +1 -0
  1003. package/dist/store/skip.d.ts +26 -0
  1004. package/dist/store/skip.d.ts.map +1 -0
  1005. package/dist/store/skip.js +66 -0
  1006. package/dist/store/skip.js.map +1 -0
  1007. package/dist/store/sql.d.ts +78 -0
  1008. package/dist/store/sql.d.ts.map +1 -0
  1009. package/dist/store/sql.js +244 -0
  1010. package/dist/store/sql.js.map +1 -0
  1011. package/dist/store/step.d.ts +52 -0
  1012. package/dist/store/step.d.ts.map +1 -0
  1013. package/dist/store/step.js +59 -0
  1014. package/dist/store/step.js.map +1 -0
  1015. package/dist/store/store.d.ts +192 -0
  1016. package/dist/store/store.d.ts.map +1 -0
  1017. package/dist/store/store.js +863 -0
  1018. package/dist/store/store.js.map +1 -0
  1019. package/dist/store/table-changes.d.ts +35 -0
  1020. package/dist/store/table-changes.d.ts.map +1 -0
  1021. package/dist/store/table-changes.js +127 -0
  1022. package/dist/store/table-changes.js.map +1 -0
  1023. package/dist/store/table-evolve.d.ts +82 -0
  1024. package/dist/store/table-evolve.d.ts.map +1 -0
  1025. package/dist/store/table-evolve.js +208 -0
  1026. package/dist/store/table-evolve.js.map +1 -0
  1027. package/dist/store/table-handle.d.ts +69 -0
  1028. package/dist/store/table-handle.d.ts.map +1 -0
  1029. package/dist/store/table-handle.js +92 -0
  1030. package/dist/store/table-handle.js.map +1 -0
  1031. package/dist/store/table-history.d.ts +78 -0
  1032. package/dist/store/table-history.d.ts.map +1 -0
  1033. package/dist/store/table-history.js +43 -0
  1034. package/dist/store/table-history.js.map +1 -0
  1035. package/dist/store/table-migration.d.ts +28 -0
  1036. package/dist/store/table-migration.d.ts.map +1 -0
  1037. package/dist/store/table-migration.js +212 -0
  1038. package/dist/store/table-migration.js.map +1 -0
  1039. package/dist/store/table-writes.d.ts +125 -0
  1040. package/dist/store/table-writes.d.ts.map +1 -0
  1041. package/dist/store/table-writes.js +170 -0
  1042. package/dist/store/table-writes.js.map +1 -0
  1043. package/dist/store/table.d.ts +91 -0
  1044. package/dist/store/table.d.ts.map +1 -0
  1045. package/dist/store/table.js +133 -0
  1046. package/dist/store/table.js.map +1 -0
  1047. package/dist/store/text.d.ts +14 -0
  1048. package/dist/store/text.d.ts.map +1 -0
  1049. package/dist/store/text.js +51 -0
  1050. package/dist/store/text.js.map +1 -0
  1051. package/dist/store/writes.d.ts +5 -0
  1052. package/dist/store/writes.d.ts.map +1 -0
  1053. package/dist/store/writes.js +4 -0
  1054. package/dist/store/writes.js.map +1 -0
  1055. package/dist/surfaces/active-language.d.ts +20 -0
  1056. package/dist/surfaces/active-language.d.ts.map +1 -0
  1057. package/dist/surfaces/active-language.js +78 -0
  1058. package/dist/surfaces/active-language.js.map +1 -0
  1059. package/dist/surfaces/active-theme.d.ts +16 -0
  1060. package/dist/surfaces/active-theme.d.ts.map +1 -0
  1061. package/dist/surfaces/active-theme.js +47 -0
  1062. package/dist/surfaces/active-theme.js.map +1 -0
  1063. package/dist/surfaces/client.d.ts +106 -0
  1064. package/dist/surfaces/client.d.ts.map +1 -0
  1065. package/dist/surfaces/client.js +280 -0
  1066. package/dist/surfaces/client.js.map +1 -0
  1067. package/dist/surfaces/connection.d.ts +53 -0
  1068. package/dist/surfaces/connection.d.ts.map +1 -0
  1069. package/dist/surfaces/connection.js +161 -0
  1070. package/dist/surfaces/connection.js.map +1 -0
  1071. package/dist/surfaces/format.d.ts +5 -0
  1072. package/dist/surfaces/format.d.ts.map +1 -0
  1073. package/dist/surfaces/format.js +37 -0
  1074. package/dist/surfaces/format.js.map +1 -0
  1075. package/dist/surfaces/index.d.ts +15 -0
  1076. package/dist/surfaces/index.d.ts.map +1 -0
  1077. package/dist/surfaces/index.js +18 -0
  1078. package/dist/surfaces/index.js.map +1 -0
  1079. package/dist/surfaces/language.d.ts +53 -0
  1080. package/dist/surfaces/language.d.ts.map +1 -0
  1081. package/dist/surfaces/language.js +74 -0
  1082. package/dist/surfaces/language.js.map +1 -0
  1083. package/dist/surfaces/loaded.d.ts +42 -0
  1084. package/dist/surfaces/loaded.d.ts.map +1 -0
  1085. package/dist/surfaces/loaded.js +116 -0
  1086. package/dist/surfaces/loaded.js.map +1 -0
  1087. package/dist/surfaces/locale-choice.d.ts +26 -0
  1088. package/dist/surfaces/locale-choice.d.ts.map +1 -0
  1089. package/dist/surfaces/locale-choice.js +14 -0
  1090. package/dist/surfaces/locale-choice.js.map +1 -0
  1091. package/dist/surfaces/messages.d.ts +67 -0
  1092. package/dist/surfaces/messages.d.ts.map +1 -0
  1093. package/dist/surfaces/messages.js +112 -0
  1094. package/dist/surfaces/messages.js.map +1 -0
  1095. package/dist/surfaces/page-state.d.ts +14 -0
  1096. package/dist/surfaces/page-state.d.ts.map +1 -0
  1097. package/dist/surfaces/page-state.js +43 -0
  1098. package/dist/surfaces/page-state.js.map +1 -0
  1099. package/dist/surfaces/preference.d.ts +33 -0
  1100. package/dist/surfaces/preference.d.ts.map +1 -0
  1101. package/dist/surfaces/preference.js +72 -0
  1102. package/dist/surfaces/preference.js.map +1 -0
  1103. package/dist/surfaces/registered.d.ts +33 -0
  1104. package/dist/surfaces/registered.d.ts.map +1 -0
  1105. package/dist/surfaces/registered.js +51 -0
  1106. package/dist/surfaces/registered.js.map +1 -0
  1107. package/dist/surfaces/scripts.d.ts +86 -0
  1108. package/dist/surfaces/scripts.d.ts.map +1 -0
  1109. package/dist/surfaces/scripts.js +28 -0
  1110. package/dist/surfaces/scripts.js.map +1 -0
  1111. package/dist/surfaces/theme-choice.d.ts +32 -0
  1112. package/dist/surfaces/theme-choice.d.ts.map +1 -0
  1113. package/dist/surfaces/theme-choice.js +18 -0
  1114. package/dist/surfaces/theme-choice.js.map +1 -0
  1115. package/dist/surfaces/themes.d.ts +43 -0
  1116. package/dist/surfaces/themes.d.ts.map +1 -0
  1117. package/dist/surfaces/themes.js +110 -0
  1118. package/dist/surfaces/themes.js.map +1 -0
  1119. package/dist/surfaces/translations.d.ts +29 -0
  1120. package/dist/surfaces/translations.d.ts.map +1 -0
  1121. package/dist/surfaces/translations.js +57 -0
  1122. package/dist/surfaces/translations.js.map +1 -0
  1123. package/dist/surfaces/variant.d.ts +23 -0
  1124. package/dist/surfaces/variant.d.ts.map +1 -0
  1125. package/dist/surfaces/variant.js +18 -0
  1126. package/dist/surfaces/variant.js.map +1 -0
  1127. package/dist/sync/batch.d.ts +18 -0
  1128. package/dist/sync/batch.d.ts.map +1 -0
  1129. package/dist/sync/batch.js +125 -0
  1130. package/dist/sync/batch.js.map +1 -0
  1131. package/dist/sync/client.d.ts +169 -0
  1132. package/dist/sync/client.d.ts.map +1 -0
  1133. package/dist/sync/client.js +459 -0
  1134. package/dist/sync/client.js.map +1 -0
  1135. package/dist/sync/files.d.ts +46 -0
  1136. package/dist/sync/files.d.ts.map +1 -0
  1137. package/dist/sync/files.js +13 -0
  1138. package/dist/sync/files.js.map +1 -0
  1139. package/dist/sync/filesystem.d.ts +37 -0
  1140. package/dist/sync/filesystem.d.ts.map +1 -0
  1141. package/dist/sync/filesystem.js +205 -0
  1142. package/dist/sync/filesystem.js.map +1 -0
  1143. package/dist/sync/index.d.ts +8 -0
  1144. package/dist/sync/index.d.ts.map +1 -0
  1145. package/dist/sync/index.js +9 -0
  1146. package/dist/sync/index.js.map +1 -0
  1147. package/dist/sync/lines.d.ts +18 -0
  1148. package/dist/sync/lines.d.ts.map +1 -0
  1149. package/dist/sync/lines.js +46 -0
  1150. package/dist/sync/lines.js.map +1 -0
  1151. package/dist/sync/remote.d.ts +145 -0
  1152. package/dist/sync/remote.d.ts.map +1 -0
  1153. package/dist/sync/remote.js +59 -0
  1154. package/dist/sync/remote.js.map +1 -0
  1155. package/dist/sync/state.d.ts +17 -0
  1156. package/dist/sync/state.d.ts.map +1 -0
  1157. package/dist/sync/state.js +40 -0
  1158. package/dist/sync/state.js.map +1 -0
  1159. package/dist/telemetry-ingest/batch.d.ts +73 -0
  1160. package/dist/telemetry-ingest/batch.d.ts.map +1 -0
  1161. package/dist/telemetry-ingest/batch.js +110 -0
  1162. package/dist/telemetry-ingest/batch.js.map +1 -0
  1163. package/dist/telemetry-ingest/facet.d.ts +26 -0
  1164. package/dist/telemetry-ingest/facet.d.ts.map +1 -0
  1165. package/dist/telemetry-ingest/facet.js +100 -0
  1166. package/dist/telemetry-ingest/facet.js.map +1 -0
  1167. package/dist/telemetry-ingest/index.d.ts +5 -0
  1168. package/dist/telemetry-ingest/index.d.ts.map +1 -0
  1169. package/dist/telemetry-ingest/index.js +8 -0
  1170. package/dist/telemetry-ingest/index.js.map +1 -0
  1171. package/dist/telemetry-ingest/recorder.d.ts +50 -0
  1172. package/dist/telemetry-ingest/recorder.d.ts.map +1 -0
  1173. package/dist/telemetry-ingest/recorder.js +298 -0
  1174. package/dist/telemetry-ingest/recorder.js.map +1 -0
  1175. package/dist/telemetry-ingest/sender.d.ts +14 -0
  1176. package/dist/telemetry-ingest/sender.d.ts.map +1 -0
  1177. package/dist/telemetry-ingest/sender.js +64 -0
  1178. package/dist/telemetry-ingest/sender.js.map +1 -0
  1179. package/dist/telemetry-sqlite/index.d.ts +33 -0
  1180. package/dist/telemetry-sqlite/index.d.ts.map +1 -0
  1181. package/dist/telemetry-sqlite/index.js +113 -0
  1182. package/dist/telemetry-sqlite/index.js.map +1 -0
  1183. package/dist/telemetry-sqlite/node.d.ts +13 -0
  1184. package/dist/telemetry-sqlite/node.d.ts.map +1 -0
  1185. package/dist/telemetry-sqlite/node.js +27 -0
  1186. package/dist/telemetry-sqlite/node.js.map +1 -0
  1187. package/dist/telemetry-sqlite/schema.d.ts +9 -0
  1188. package/dist/telemetry-sqlite/schema.d.ts.map +1 -0
  1189. package/dist/telemetry-sqlite/schema.js +61 -0
  1190. package/dist/telemetry-sqlite/schema.js.map +1 -0
  1191. package/dist/telemetry-sqlite/store.d.ts +12 -0
  1192. package/dist/telemetry-sqlite/store.d.ts.map +1 -0
  1193. package/dist/telemetry-sqlite/store.js +121 -0
  1194. package/dist/telemetry-sqlite/store.js.map +1 -0
  1195. package/dist/telemetry.d.ts +1013 -0
  1196. package/dist/telemetry.d.ts.map +1 -0
  1197. package/dist/telemetry.js +518 -0
  1198. package/dist/telemetry.js.map +1 -0
  1199. package/dist/tui/bridge.d.ts +112 -0
  1200. package/dist/tui/bridge.d.ts.map +1 -0
  1201. package/dist/tui/bridge.js +9 -0
  1202. package/dist/tui/bridge.js.map +1 -0
  1203. package/dist/tui/channel.d.ts +44 -0
  1204. package/dist/tui/channel.d.ts.map +1 -0
  1205. package/dist/tui/channel.js +150 -0
  1206. package/dist/tui/channel.js.map +1 -0
  1207. package/dist/tui/frames.d.ts +5 -0
  1208. package/dist/tui/frames.d.ts.map +1 -0
  1209. package/dist/tui/frames.js +52 -0
  1210. package/dist/tui/frames.js.map +1 -0
  1211. package/dist/tui/index.d.ts +8 -0
  1212. package/dist/tui/index.d.ts.map +1 -0
  1213. package/dist/tui/index.js +8 -0
  1214. package/dist/tui/index.js.map +1 -0
  1215. package/dist/tui/runtime.d.ts +46 -0
  1216. package/dist/tui/runtime.d.ts.map +1 -0
  1217. package/dist/tui/runtime.js +101 -0
  1218. package/dist/tui/runtime.js.map +1 -0
  1219. package/dist/tui/scope.d.ts +62 -0
  1220. package/dist/tui/scope.d.ts.map +1 -0
  1221. package/dist/tui/scope.js +173 -0
  1222. package/dist/tui/scope.js.map +1 -0
  1223. package/dist/tui/terminal.d.ts +15 -0
  1224. package/dist/tui/terminal.d.ts.map +1 -0
  1225. package/dist/tui/terminal.js +37 -0
  1226. package/dist/tui/terminal.js.map +1 -0
  1227. package/dist/tui/theme.d.ts +17 -0
  1228. package/dist/tui/theme.d.ts.map +1 -0
  1229. package/dist/tui/theme.js +38 -0
  1230. package/dist/tui/theme.js.map +1 -0
  1231. package/dist/watch.d.ts +194 -0
  1232. package/dist/watch.d.ts.map +1 -0
  1233. package/dist/watch.js +383 -0
  1234. package/dist/watch.js.map +1 -0
  1235. package/dist/web/environment.d.ts +4 -0
  1236. package/dist/web/environment.d.ts.map +1 -0
  1237. package/dist/web/environment.js +37 -0
  1238. package/dist/web/environment.js.map +1 -0
  1239. package/dist/web/index.d.ts +5 -0
  1240. package/dist/web/index.d.ts.map +1 -0
  1241. package/dist/web/index.js +7 -0
  1242. package/dist/web/index.js.map +1 -0
  1243. package/dist/web/language.d.ts +7 -0
  1244. package/dist/web/language.d.ts.map +1 -0
  1245. package/dist/web/language.js +21 -0
  1246. package/dist/web/language.js.map +1 -0
  1247. package/dist/web/page.d.ts +42 -0
  1248. package/dist/web/page.d.ts.map +1 -0
  1249. package/dist/web/page.js +96 -0
  1250. package/dist/web/page.js.map +1 -0
  1251. package/dist/web/scripts.d.ts +23 -0
  1252. package/dist/web/scripts.d.ts.map +1 -0
  1253. package/dist/web/scripts.js +50 -0
  1254. package/dist/web/scripts.js.map +1 -0
  1255. package/dist/web/styles.d.ts +17 -0
  1256. package/dist/web/styles.d.ts.map +1 -0
  1257. package/dist/web/styles.js +218 -0
  1258. package/dist/web/styles.js.map +1 -0
  1259. package/dist/web/themes.d.ts +6 -0
  1260. package/dist/web/themes.d.ts.map +1 -0
  1261. package/dist/web/themes.js +31 -0
  1262. package/dist/web/themes.js.map +1 -0
  1263. package/docs/admission/design.md +178 -0
  1264. package/docs/benchmarks.md +1182 -0
  1265. package/docs/decisions.md +3760 -0
  1266. package/docs/dependencies/book.md +1671 -0
  1267. package/docs/dependencies/index.html +2641 -0
  1268. package/docs/dependencies/model.md +330 -0
  1269. package/docs/design.md +3691 -0
  1270. package/docs/durable-observers/book.md +432 -0
  1271. package/docs/durable-observers/index.html +517 -0
  1272. package/docs/events/spec.md +438 -0
  1273. package/docs/flow-control/book.md +333 -0
  1274. package/docs/flow-control/fold/index.html +265 -0
  1275. package/docs/flow-control/index.html +548 -0
  1276. package/docs/flow-control/window/index.html +228 -0
  1277. package/docs/guide-plugins-hosts/book.md +958 -0
  1278. package/docs/guide-plugins-hosts/index.html +952 -0
  1279. package/docs/host-keyed/spec.md +343 -0
  1280. package/docs/http-workers/book.md +378 -0
  1281. package/docs/http-workers/index.html +515 -0
  1282. package/docs/i18n/book.md +217 -0
  1283. package/docs/i18n/index.html +344 -0
  1284. package/docs/layer-1.md +311 -0
  1285. package/docs/layer-2.md +216 -0
  1286. package/docs/p3-features/README.md +6 -0
  1287. package/docs/p3-features/book.md +478 -0
  1288. package/docs/plugin-authoring.md +389 -0
  1289. package/docs/plugin-model/book.md +186 -0
  1290. package/docs/plugin-model/index.html +310 -0
  1291. package/docs/plugin-primer/book.md +273 -0
  1292. package/docs/plugin-primer/index.html +430 -0
  1293. package/docs/shared-holds/design.md +339 -0
  1294. package/docs/slice-1.md +236 -0
  1295. package/docs/slice-10.md +288 -0
  1296. package/docs/slice-11.md +114 -0
  1297. package/docs/slice-12.md +132 -0
  1298. package/docs/slice-13.md +121 -0
  1299. package/docs/slice-14-design.md +213 -0
  1300. package/docs/slice-14.md +861 -0
  1301. package/docs/slice-2.md +174 -0
  1302. package/docs/slice-3a.md +296 -0
  1303. package/docs/slice-3b.md +197 -0
  1304. package/docs/slice-4.md +146 -0
  1305. package/docs/slice-4a.md +418 -0
  1306. package/docs/slice-4b.md +208 -0
  1307. package/docs/slice-5.md +281 -0
  1308. package/docs/slice-6a.md +676 -0
  1309. package/docs/slice-6b.md +332 -0
  1310. package/docs/slice-7a.md +130 -0
  1311. package/docs/slice-7b/book.md +608 -0
  1312. package/docs/slice-7b/index.html +842 -0
  1313. package/docs/slice-7b.md +255 -0
  1314. package/docs/slice-7c.md +165 -0
  1315. package/docs/slice-8.md +194 -0
  1316. package/docs/slice-9.md +110 -0
  1317. package/docs/slices.md +380 -0
  1318. package/docs/store/book.md +670 -0
  1319. package/docs/store/index.html +861 -0
  1320. package/docs/store/walkthrough.md +193 -0
  1321. package/docs/theming/book.md +223 -0
  1322. package/docs/theming/index.html +371 -0
  1323. package/docs/tutorial/book.md +2170 -0
  1324. package/docs/tutorial/index.html +2112 -0
  1325. package/docs/tutorial/screens/click-after.png +0 -0
  1326. package/docs/tutorial/screens/click-before.png +0 -0
  1327. package/docs/tutorial/screens/edited.png +0 -0
  1328. package/docs/tutorial/screens/french.png +0 -0
  1329. package/docs/tutorial/screens/harbor.png +0 -0
  1330. package/docs/tutorial/screens/page.png +0 -0
  1331. package/docs/tutorial/screens/traces-ada.png +0 -0
  1332. package/docs/tutorial/screens/traces.png +0 -0
  1333. package/package.json +200 -5
  1334. package/src/delta/README.md +262 -0
package/docs/design.md ADDED
@@ -0,0 +1,3691 @@
1
+ # Chord v2: target design
2
+
3
+ The design of Chord v2 (`packages/chord/src`, the package's root export `@diffra-ai/chord`) and of how apps (the playground, p3) use it: **the one current statement of every rule** (owner,
4
+ 2026-10-24). Every decision is recorded in the decision log `packages/chord/docs/decisions.md` (the history and the
5
+ reasons, kept complete) and folded into this document in the same commit. Where a rule is built, the slice is named
6
+ (`slices.md`); the code follows this document. It replaces `apps/p2/docs/target-design.md`.
7
+
8
+ Marks: everything is decided unless marked **Decision needed** (problem with an example, then options; nothing in such
9
+ a block is settled; section 26 lists them all). **(carried over)** marks behaviour of today's Chord that v2 keeps
10
+ without a new decision. API names are working names.
11
+
12
+ Contents: 1 goals · 2 concepts · 3 hosts and links · 4 principals · 5 object types · 6 objects · 7 references · 8 ctx ·
13
+ 9 documents · 10 store and storage · 11 kinds of state · 12 derives · 13 natives · 14 routines · 15 jobs · 16 the facet
14
+ · 17 registries · 18 start data and platform bindings · 19 presence · 20 input into running work · 21 reload and rollout
15
+ · 22 wire · 23 optional components · 24 Durable integration · 25 apps: ownership and porting · 26 decisions needed · 27
16
+ versions and adapters · 28 building: slices · 29 telemetry · 30 cost model · 31 rejected
17
+
18
+ ---
19
+
20
+ ## 1. Goals and principles
21
+
22
+ 1. **Reload without restarts.** A plugin's new code takes over inside the running app: hosts keep running; data, open
23
+ connections and running work survive where they can. Reloads are explicit (a button or a command), never on save.
24
+ Base code (Chord, the app runtime) restarts the hosts.
25
+ 2. **Ownership.** Every thing has exactly one owning object, the smallest it belongs to. The owner holds the data,
26
+ enforces its rules in its methods and offers the operations others need. Nobody reaches past it.
27
+ 3. **Factories declare, Chord activates.** A factory is synchronous and only declares; Chord performs activation.
28
+ Handles a factory gets are valid for the object's whole life.
29
+ 4. **Natives only in objects.** OS-level values are opened and closed by the object that owns them, and reach other
30
+ plugins only through that owner's methods, state or registry entries.
31
+ 5. **Errors look like disconnects.** No request-id framework; consumers handle a failed call as they handle a dropped
32
+ link. References re-hold by themselves.
33
+ 6. **Tagged unions, always.** States, results and outcomes are discriminated by `kind`; each state carries exactly its
34
+ own fields.
35
+ 7. **Portable kernel.** A host is a logical identity plus an incarnation; facets may come pre-imported; values are
36
+ JSON plus bytes independent of the transport. Node first; Cloudflare Durable Objects and similar stay possible.
37
+ 8. **Context last.** Parameters are the required arguments, then the context (`ctx` or a Durable `Context`), then
38
+ optional arguments: `self.tx(fn, ctx)`, `handle.change(key, fn, ctx)`, `chord(fn, context)`, `job.start(args, ctx,
39
+ { key })` (owner, 2026-10-21).
40
+ 9. **Few concepts, no ceremony.** No special directories, no `defineNative`, no lints standing in for design.
41
+ 10. **Aligned with Durable** (owner, 2026-10-27): where Chord and Durable solve the same problem (commits, lines,
42
+ loads, storage errors, watches), they use the same rules and mechanisms.
43
+
44
+ ---
45
+
46
+ ## 2. Concepts
47
+
48
+ | Concept | What it is |
49
+ | --- | --- |
50
+ | host | one participant (a process, a tab, a DO): a logical identity plus an incarnation |
51
+ | link | a connection between two hosts |
52
+ | host kind / address | typed description of addressable hosts / one host of a kind (`Session({ id })`) |
53
+ | facet | a plugin's declarations for one host kind: the types it serves, its contributions; no state or behaviour of its own |
54
+ | object type | a contract: name, params (which instance), host address, members, version |
55
+ | object | one instance per (type, params, principal key); `local`: per (type, params) |
56
+ | principal | who calls; stamped by links, typed by the app |
57
+ | reference | what `get` returns; keeps its object alive; live and hydrated when awaited |
58
+ | event member | a JSON value an object emits (`self.events`), delivered once to the references bound to it before the emit (over a link, per wire hold: references sharing one get what arrives after they bound, §7), never kept; read with `ref.member.on(listener, ctx)`, a subscription (section 11) |
59
+ | document | a named JSON value an object owns, written in transactions |
60
+ | derive | a value computed from watchables |
61
+ | named query | a query a store offers under a name, its argument schema in the contract (`queries`, `self.queries`, section 11; slice 14) |
62
+ | live query | rows kept current by commits: the owner's own window (`self.query`), or a named query read by any object on the store's host (`self.liveQuery`) (section 11) |
63
+ | list | a named query a screen loads more of: pages between fixed bookmarks, tiled (`self.list`, section 11; slice 14) |
64
+ | column set | the columns of a table its contract declares for other plugins' conditions and joins (`defineColumns`, section 10; slice 14) |
65
+ | probe | one keyed statement by which a commit asks whether a written row can be in a read, before running the read again (section 10; slice 14) |
66
+ | admission | a remote type's, or a route's, decision before anything is built or started: a typed value for the factory, or a denial (sections 3, 6; slice 14) |
67
+ | native | an OS-level value opened with `self.open`; only in objects |
68
+ | routine | standing behaviour of an object: `self.on(source, fn)`, `self.onLive(fn)` |
69
+ | job | owned work a call starts that outlives it: intent, run, finish; optional state document per run |
70
+ | registry | an owner's extension point: one contribution per contributor, composed by the owner |
71
+ | shared store | a `local` object holding shared data once, behind per-principal `remote` views |
72
+ | `ctx` | per call: cancellation, principal, call-scoped references |
73
+ | revision | (server incarnation, sequence): the complete code set a host runs |
74
+
75
+ ---
76
+
77
+ ## 3. Hosts and links
78
+
79
+ ### Roles
80
+
81
+ A Node app has one shape:
82
+
83
+ ```
84
+ client client client browsers, TUIs: not addressable
85
+ └──────┼──────┘
86
+ server exactly one, addressable
87
+ ┌──────┼──────┐
88
+ worker worker worker addressable by a typed address, started on demand
89
+ ```
90
+
91
+ | Role | Addressable | Principal comes from | Lifecycle |
92
+ | --- | --- | --- | --- |
93
+ | client | no | authentication of its link | connects by itself |
94
+ | server | yes, one | its own declaration | runs |
95
+ | worker | yes, many | stamped by the parent | started on demand by the app |
96
+
97
+ Clients serve only `local` types (they are not addressable): a host without a principal or without an address refuses
98
+ to serve a remote type (a declaration error: `load` leaves that plugin out and reports it, a reload keeps it on its
99
+ old code; a remote object is owned by a principal of the host serving it, owner,
100
+ 2026-10-24; and placed by its host address, owner, 2026-10-29). No client providers for now (owner,
101
+ 2026-10-28): client-side capabilities (a camera, WebMCP tools) go through an owner's requests that clients answer
102
+ (section 20, the Questions service). A client's local
103
+ calls have no principal; what a client calls on the server is stamped with the client's authenticated principal.
104
+ Clients reach workers only through the server, which relays; workers reach each other through the server too. A
105
+ detached process (e.g. a terminal host) would be another child kind of the server. Things that are not hosts: a code
106
+ mode sandbox (a worker thread inside a worker), remote environment daemons (their own protocol, owned by an object),
107
+ the TUI sandbox behind its launcher (the launcher only passes frames). A Durable Object deployment is a mesh routed by
108
+ the edge (section 24 and the research note).
109
+
110
+ ### Host kinds and addresses
111
+
112
+ ```ts
113
+ export const Server = hostKind("server");
114
+ export const Session = hostKind("session", { id: str() }); // params like a contract's
115
+
116
+ export const Notes = remote("notes", {
117
+ version: 1,
118
+ params: { session: str() }, // flat record of required scalars
119
+ hostAddress: ({ session }) => Session({ id: session }), // a typed function of the params
120
+ variants: { … },
121
+ });
122
+ export const Catalog = remote("catalog", { hostAddress: () => Server(), … });
123
+ ```
124
+
125
+ - `hostKind(name, params?)` declares a kind of addressable host; its params follow the params policy of contracts
126
+ (section 5). `Session({ id: "S1" })` is an **address**: `{ kind, params, key }`, the key built like an identity key
127
+ (`session|S1`); two addresses are equal when their keys are. No host-name strings appear in app code.
128
+ - **`hostAddress`** (owner, 2026-10-21 as `placement`, renamed 2026-10-29) is a typed function of the params returning
129
+ the address of the host that serves the object, required on every `remote` contract (owner, 2026-10-29); `local`
130
+ contracts have none. It is not part of the contract fingerprint; a changed rule surfaces as a refusal (below).
131
+ - **`params`** (owner, 2026-10-21; was `input`) select the instance among objects of its type and are part of its
132
+ identity (section 5).
133
+ - **The caller computes the address** and sends it in the `hold`; a host that relays routes by that address alone and
134
+ never needs the contract or parses params. **The provider computes it again** from the params: a hold naming this
135
+ host whose params the provider's code places elsewhere (code skew) waits unbound `version` (`failed { waiting }`,
136
+ `invalid/host_address`, dependency model §1; slice 7a); a hold naming another host's address is relayed, never served
137
+ here (misrouted holds are never captured by a relay that serves the same name). These checks (and a relay's
138
+ `authorize`, and the provider's admission against its contract and accepted versions, §5) run when a new hold is
139
+ made; a reference joining a held remote object (§7) uses that hold without a new provider or relay admission or
140
+ snapshot, also while an old attempt drains after a reload; the consuming host still places and admits it (its
141
+ params, `hostAddress`, a route's `authorize`) before the lookup (decision "References share one wire hold").
142
+ - **Every reference is a request** (dependency model, slice 7a): it has one holder (an attempt, a call, outside code,
143
+ a link's peer) and ends only when its holder ends it (release, a call settling, a getter giving up, the peer's link
144
+ or origin closing, revocation, the host closing), never because its provider is missing, went away or does not fit.
145
+ A remote reference joining a held remote object (§7) is a holder of that object on this host; the provider sees one
146
+ hold (decision "References share one wire hold").
147
+ - **Where a reference made on a host, or a hold arriving on one of its links, goes**, by address alone (slice 4a;
148
+ slice 7a: no same-name check on the consumer's host):
149
+
150
+ | Case | Goes |
151
+ | --- | --- |
152
+ | a `local` type | here |
153
+ | a `remote` type whose host address (computed here from the params) is this host's address, served here or not | here |
154
+ | an arriving hold naming this host's address | here |
155
+ | the address (computed, or named by the hold) is of a kind this host has a route for | over that route's link (the address's params checked against the kind, then `authorize`) |
156
+ | otherwise (a remote type) | over the parent link; a hold that arrived *on* the parent link is never sent back to it: `unavailable` |
157
+ | no parent link: the host never had one | `unavailable` |
158
+ | no parent link: it is down (a drop) | waits on the parent path, `loading`, until the next link (design audit, 2026-10-27) |
159
+
160
+ A `hostAddress` or `authorize` that throws fails the request broken with that error; an address whose params fail
161
+ the kind's check is broken `invalid/host_address`.
162
+ - **The publication gate** (slice 7a): a hold arriving on its links before the host's first publication (`load`'s
163
+ batch of declarations) is not placed yet: it is `loading`, and the publication places it (a worker connects first,
164
+ W6). The gate lasts only for the synchronous setups, never for activation, so it cannot deadlock. **This host's own
165
+ requests before `load` is called** (`get`, `hold`, `registry`, a root's `ctx.get`) would wait for a publication
166
+ nobody started: they throw `not_ready` at once, "call `host.load` first"; a client host with nothing to load calls
167
+ `load([])` (decision "Mistakes that wait are reported at once" (a), 2026-11-03; footgun 1 of the p2 port).
168
+ - **Then the selected provider is checked** (here: served, the version and fingerprint, the params, the provider's
169
+ own host-address check; over a path: at the provider host). Version checks never look at a same-name registration
170
+ elsewhere. What the check finds:
171
+
172
+ | The check finds | The request |
173
+ | --- | --- |
174
+ | a fitting provider | bound (to the object here, or to the hold over a path) |
175
+ | not published yet | unbound `unpublished`: `loading` |
176
+ | nobody serves the name at its address (or serves it as the other kind) | unbound `not_served`: `failed { waiting }` (`unavailable` "X is not served here") |
177
+ | no fitting version, a fingerprint that differs at the same version, a host address the provider computes elsewhere | unbound `version`: `failed { waiting }` (`contract_mismatch`, `invalid/host_address`) |
178
+ | a registry served, but its first `compose` (or the reader's version mapping) threw | unbound `compose`: `failed { waiting }` (§17) |
179
+ | the path has no link (a drop, a route resolving) | on the path: `loading` |
180
+ | `authorize` refused, invalid params, a cycle | `failed { broken }`, never indexed |
181
+
182
+ The unbound reasons that wait for a name are indexed under it on the host that decided them: the consumer's host
183
+ for a request made there, the provider's host for a hold that arrived over a link (kept refused there; a `retry`
184
+ re-runs its start). A publication serving a name (`load`'s, or a reload's commit, which wakes only the requests of
185
+ the names it serves, slice 7b) wakes its requests, which run their check again
186
+ (a refused hold sends `loading`, then `bound` or `failed`); no new message kind. Index entries go when their request
187
+ ends (GC-tested). The consumer never re-holds a request by itself: no backoff, no polling.
188
+ - **A request waiting unbound is reported** (decision "Mistakes that wait are reported at once" (c), 2026-11-03): one
189
+ indexed with a cause after the publication (`not_served`, `version`: a reference made here, a hold refused here for a
190
+ name) and a registry value waited for while it has none (a parked `self.registry`, a `host.registry`: `not_served`,
191
+ `version`, `compose`; one wait per value, not per waiter) is reported once through `onError` after 5 s as
192
+ `unbound_long { waitingFor, error, since }` (`waitingFor` the type's name or `registry <name>`, `error` the cause,
193
+ `since` `Date.now()` time); it keeps waiting until its `readyTimeout` as before. One clock per host, one timer armed for
194
+ the earliest wait not reported yet (no timer per request); a wait that binds, ends or is woken leaves it, and one
195
+ woken and left unbound again starts anew. Reported on the host that decided it: a consumer whose hold a provider
196
+ host refused sees `failed { waiting }`, the provider host reports. Not `parked_long`, which reports an attempt
197
+ (an object) parked past its `readyTimeout` whatever its blocker (loading included); a `self.get` waiting unbound
198
+ gets both, `unbound_long` for the request after 5 s and `parked_long` for its object later.
199
+
200
+ ### The low-level host API
201
+
202
+ ```ts
203
+ // server.ts
204
+ const server = createHost<P>({ address: Server(), principal: { kind: "server" }, onError });
205
+ server.route(Session, {
206
+ authorize: (p, address) => p.kind === "owner" || p.kind === "server" || (p.kind === "guest" && p.session === address.params.id),
207
+ resolve: async (address, context) => {
208
+ const child = fork("worker.ts", [], { serialization: "advanced" }); // no `signal`: see below
209
+ child.send({ id: address.params.id, init: await initFor(address.params.id) }); // the app's own start message
210
+ return { link: ipcLink(child), principal: { kind: "worker", session: address.params.id }, trusted: true };
211
+ },
212
+ });
213
+ await server.load([{ name: "@app/core", facet: coreServerFacet(config) }, ...serverPlugins], ctx);
214
+
215
+ wss.on("connection", (ws, req) => { // an entry point: app or adapter code
216
+ const principal = authenticate(req);
217
+ if (!principal) return ws.close(4401);
218
+ server.accept(webSocketLink(ws), { principal }, ctx);
219
+ });
220
+ radius.onChannel((ws) => server.accept(webSocketLink(ws), { principal: { kind: "owner", access: "relay" } }, ctx));
221
+ ```
222
+
223
+ ```ts
224
+ // worker.ts: connect first (W6), then load; start data through the core facet (section 18)
225
+ const { id, init } = await startMessage(process);
226
+ const worker = createHost<P>({ address: Session({ id }), principal: { kind: "worker", session: id }, onError });
227
+ worker.connect(ipcLink(process), { principal: { kind: "server" }, trusted: true }, ctx); // stores may reference server types
228
+ await worker.load([{ name: "@app/core", facet: coreWorkerFacet(init) }, ...workerPlugins], ctx); // serves SessionInfo
229
+ await (await worker.get(Harness, {}, ctx)).resume(ctx); // tasks run only after every plugin loaded
230
+
231
+ // a browser tab
232
+ const tab = createHost<P>({ onError });
233
+ await tab.load(webPlugins, ctx);
234
+ tab.connect(webSocketLink(new WebSocket("/chord")), { principal: { kind: "server" } }, ctx);
235
+ const notes = await tab.get(Notes, { session: "S1" }, ctx); // tab → server → route(Session) → worker
236
+ ```
237
+
238
+ ```ts
239
+ // a test: everything in one process
240
+ server.route(Session, {
241
+ authorize: () => true,
242
+ resolve: async (address) => {
243
+ const [up, down] = memoryLinkPair();
244
+ const principal = { kind: "worker", session: address.params.id } as const;
245
+ const worker = createHost<P>({ address, principal, onError });
246
+ worker.connect(up, { principal: { kind: "server" } }, ctx); // W6: connect, load, resume
247
+ void worker.load([{ name: "@app/core", facet: coreWorkerFacet({ id: address.params.id }) }, ...workerPlugins], ctx);
248
+ return { link: down, principal };
249
+ },
250
+ });
251
+ ```
252
+
253
+ Do not pass `context.abortSignal` to `fork`: `host.close` aborts it, which kills the worker and makes Node emit an
254
+ `error` event that crashes an app without a handler. Chord closes the link at `host.close`; the worker exits when its
255
+ parent link closes. `resolve` returns the link before the worker has loaded (the worker connects first, W6): made
256
+ later, the link would leave the worker's `hello` unread and the heartbeat would close it during a long `load` (slice
257
+ 10's spec review; the deadlock once feared here does not happen: 7a's barrier ends its first pass on a wait on another
258
+ host). The workers component (§23) does this.
259
+
260
+ | Call | Meaning |
261
+ | --- | --- |
262
+ | `createHost<P>({ address?, principal?, ...options })` | with an address: addressable, serves only objects placed there, acts as `principal` on its own host; without: a client. `P` is the app's principal type |
263
+ | `load([{ name, facet }], context)` | facets with their plugin names (the plugin's `package.json` name, npm style: an invalid name is a programming error, `load` throws before it changes anything; a duplicate is refused and listed in `failed`); runs every facet's setup, publishes all of them in one batch (types and registries served, registries composed once, contributions; requests waiting for the publication are placed after it; a registry with contributions and no provider is reported `registry_undeclared`), then waits for the start barrier (section 21: the first outcomes of its host-lifetime objects, slice 7a); a plugin whose setup throws is left out and reported (`load` resolves with `{ failed: [{ plugin, error }] }`, decision "Per plugin at startup and reload"); runs once. Loaders are adapters; base code passes its core facet the same way |
264
+ | `reload([{ name, facet }], context)` | the complete new plugin set after `load` (a facet passed as the same object is an unchanged plugin): staging, then one commit, then every object of a changed or removed plugin takes its fate; resolves with a report (a plugin whose new code fails keeps its old code, listed in `failed`); an invalid plugin name throws before anything changes; one at a time (section 21, slice 7b) |
265
+ | `connect(link, { principal, trusted?, codec? }, context)` | the link to the parent, at most one open; once it closed (a drop), `connect` takes the next, and every remote reference over the parent is held again on it. `principal` = who the parent is |
266
+ | `accept(link, { principal, trusted?, codec? }, context)` | a link from a child; holds and calls on it act as `principal` |
267
+ | `route(Kind, { authorize, resolve, admit? }, context)` | how to reach hosts of a kind (below); called before `load`, once per kind; work arriving on its links runs under `context`; returns a `RouteHandle`: `retry(address)` resolves the address again (D10b), `suspend(address)` stops resolving it until `retry` (R1) |
268
+ | `get(Type, params, context, { readyTimeout? })` | a reference once its object is live, waiting through `loading`, `failed { transient }` and `failed { waiting }` up to its `readyTimeout` (section 7); before `load` it rejects `not_ready` at once |
269
+ | `hold(Type, params, context, { readyTimeout? })` | a reference at once that follows its object until released (section 7); before `load` it throws `not_ready` |
270
+ | `close(context)` | closes the links (children, routes, then the parent), then ends every object at once and tears them down, the last to go live first (reason `close`); rejects with an `AggregateError` of the native closes that threw |
271
+ | `revoke(r, context)` | revocation (section 4; slice 4b) |
272
+ | `root(fn, context, { principal? })` | a call scope for code outside objects (a Durable hook, a CLI, an HTTP request): `fn` gets a handler's `ctx`, sealed when `fn` settles, `context` aborts or the host closes (slice 8 D3, section 8); an omitted `principal` acts as the host, an explicit `undefined` runs anonymous (slice 10) |
273
+ | `registry(R, context, { readyTimeout? })` | registry `R`'s composed value for code outside objects once it is usable; while it has none it waits up to its `readyTimeout`, then rejects with the last error (slice 8, 7a, section 17); before `load` it rejects `not_ready` at once |
274
+
275
+ **Options of `createHost`:** `address`, `principal`, `principalKey` (section 4; the same function on every host),
276
+ `telemetry` (section 29), `onError`, `closeTimeout`, `readyTimeout`, `heartbeat: { ping?, close? }`, `callWindow` (the
277
+ call window it announces on untrusted links, 10,000) and `eventWindow` (its own `event` messages unacknowledged per link
278
+ and origin, 32; below, "Flow control"); later `revokedBy`
279
+ (section 4, slice 4b) and `store` (section 10, slice 6a: the store, opened by the app with `openStore(backend, ctx)`
280
+ and closed by the app with `store.close(ctx)` after `host.close`; the host never closes it). **`onError`** receives everything that fails in the
281
+ background, as a tagged `HostError`: `listener_error` (a watch listener threw), `delivery_failed` (a frame delivery
282
+ threw), `activation_failed { object, failure }`, `close_failed { object, native, error }`, `close_timeout { object,
283
+ native }`, `drain_timeout { object }`, `protocol_error { error }`, `resolve_failed { address, error }`; later routine
284
+ errors (slice 5), `derive_failed { object, member?, error }` (a derive's compute threw, once per failure episode, slice 6a), the registries' `registry_conflict { registry, message, plugins }`, `registry_failed { registry, error }`, `contribution_failed { registry, plugin, type?, error }` and `contribution_refused { registry, plugin, type?, version }` (each once per episode, slice 8), `object_failed { object, failure }` (a live object failing, slice 6a, `broken`; `transient` when a `self.follow` source failed, slice 6b R4; `failure` where the value is a `FailureCause`, `error` otherwise, 2026-10-27), `job_interrupted { object, job, id, restarts }` (a persisted run ended at the restart limit, slice 6b D6), `parked_long { object, waitingFor, state, since }` (an attempt parked longer than its `readyTimeout`, whatever its blocker, once per parking episode: a diagnostic of a ring across hosts started at the same moment or a long wait, slice 7a, audit A11, §6), the reports of mistakes that would otherwise look like slowness (decision "Mistakes that wait are reported at once", 2026-11-03): `registry_undeclared { registry, plugins }` (at a publication, or when a host-lifetime object's contributions enter, a registry with contributions and no provider here, naming its contributing plugins; again only once they change), `unbound_long { waitingFor, error, since }` (a request waiting unbound after the publication, below) and `transaction_cancelled { object, error }` (§8), and `storage_failed { error }`
285
+ (slice 6a), which every app must handle: Chord never ends the process,
286
+ the app exits with its own code for its supervisor or reopens.
287
+
288
+ **Timeouts** are host options; no fixed numbers in the code. Two host timeouts (C13, owner, 2026-10-22):
289
+
290
+ | Timeout | Bounds | Host default | Override |
291
+ | --- | --- | --- | --- |
292
+ | `closeTimeout` | a native's `close` (then reported as a possible leak; the rest continues); the drain of an ending object's running handlers (callers are rejected at once) | 30 s | per native: `self.open(open, close, { closeTimeout })` |
293
+ | `readyTimeout` | an activation attempt's own steps (its wait for the previous instance's teardown included; paused while the attempt is parked on its dependencies, slice 7a); a getter's whole wait; how long a call made while its reference is loading waits (the park deadline) | 60 s | per `get`/`hold`/`registry`: `{ readyTimeout }` |
294
+
295
+ The park deadline's per-type override is not built (only if a real case needs it). Timeouts of later slices belong to
296
+ their mechanisms: a restart's old attempt is bounded by `reloadDrainTimeout` (default 5 s, at most `closeTimeout`;
297
+ section 21), a job `finish` backs off 1 s to 60 s, provider-side `linger` is per type; a reload has no install timeout
298
+ (it takes the app's context, slice 7b); a per-type drain override only if a case needs it (section 26). A route's `resolve` is bounded by the app.
299
+
300
+ - **Incarnations** are minted by Chord (uuidv7, code copied from diffra-ai, no dependency), never passed in, and carried
301
+ in the link handshake (`hello`): the other side sees a restart as a new incarnation of the same identity;
302
+ references to it re-hold.
303
+ - **Entry points vary** (loopback or tunnel WebSocket servers, Radius dialing out and delivering channels, a DO edge,
304
+ memory), so the kernel has no `listen`; each entry point authenticates and calls `accept`. Radius no longer needs to
305
+ pose as a loopback request with a secret header.
306
+ - **App code, not Chord:** starting processes, init data, authentication, keep-alive decisions. Helpers come only when
307
+ apps repeat the same code.
308
+ - Compared with today's Chord: same shape (`createHost`, `connect`, `accept`, `route`, `load`); gone are string host
309
+ names and prefix parsing, app-managed generations, the duplicate `upstream` option, `opaque` runtime objects and the
310
+ loader inside the kernel.
311
+ - **Worker keep-alive** works as in p2: the worker counts, the app's supervisor decides. **`host.activity`** (slice 4b;
312
+ owner, 2026-10-24) is a JSON `Watchable` of `{ references, calls, jobs, lingering }`: holds arriving over links,
313
+ method calls running on this host, running jobs, provider-side lingering objects. Counters are kept where the work
314
+ happens; a change marks it dirty and it is published at most once per microtask turn with changes. A hold placed
315
+ here counts from its arrival to its end, bound or not (one waiting for a missing provider keeps the worker alive;
316
+ slice 7a); a hold this host relays counts at its destination; same-host bindings do not count.
317
+ `host.references` (§19) lists bound holders only: same-host bindings and arriving wire holds. Several references of a
318
+ consuming host sharing one hold (§7) are one entry there and one count here, until that hold ends. Core code
319
+ reports it plus Durable tasks (the core `Harness`); the server's supervisor stops the worker when all are zero for
320
+ the idle time (p2: 5 minutes, checked every second). Chord provides the counts, no idle logic.
321
+
322
+ ### Routes
323
+
324
+ ```ts
325
+ host.route(Session, {
326
+ authorize(principal: P, address: Address<typeof Session>): boolean;
327
+ resolve(address: Address<typeof Session>, context: Context):
328
+ Promise<{ link: Link; principal: P; trusted?: boolean; codec?: Codec; opened?(incarnation: string): void }>;
329
+ admit?(principal: P, address: Address<typeof Session>, self: AdmitSelf): Watchable<Admission<null>>; // slice 14
330
+ });
331
+ ```
332
+
333
+ - **`authorize`** runs for every hold routed over the route, with the hold's principal (section 4), before anything
334
+ starts; `false` fails the hold broken `forbidden`.
335
+ - **`resolve`** runs at most once at a time per address: the first hold starts it, later holds wait for the same
336
+ link. The returned principal is stamped on that link; `trusted` and `codec` as for `accept`. Its `context` is
337
+ aborted only when the host closes; a link it returns after that is closed at once. A `resolve` whose holds were all
338
+ released meanwhile finishes and its link is kept (a worker start that produced a link finishes even if its first
339
+ requester left). A `resolve` that never settles is the app's (it bounds its own `fork`); getters still time out.
340
+ `opened(incarnation)`, when returned, is called once at the link's handshake with the incarnation of the host at
341
+ the other end (its calls' `ctx.incarnation`), before anything else that host sent is handled and before this host
342
+ sends on the link (the workers component records it in its state, §23); never for a link that closes before its
343
+ handshake.
344
+ - **Failure and re-resolve** (slice 10 R2, owner, 2026-10-30; replaces the per-address backoff): a route has no
345
+ timer. A rejected `resolve` (reported `resolve_failed`) or a returned link already closed fails the route's holders
346
+ with its error (`failed`, not an endless `loading`); the route resolves again only for a new hold (a reference
347
+ joining a held remote object on such an address, §7, counts as one), on
348
+ `RouteHandle.retry(address)`, or once after the address's link dropped while holds exist (a drop of a healthy link
349
+ recovers at once; whether a crashed worker comes back is the `resolve`'s answer). `RouteHandle.suspend(address)`
350
+ (R1) stops resolving an address (its holders stay `loading`) until `retry`; a reference made meanwhile holds on its
351
+ own and fails `unavailable` (it joins no held object, §7). A network route that wants to reconnect
352
+ keeps its own policy in its `resolve`. The workers component answers a failed address's `resolve` with its stored
353
+ failure at once: workers never restart by themselves (§23).
354
+ - **A route's admission** (slice 14, `slice-14.md` §2.3; `host/route-admission.ts`): with `admit`, the route asks
355
+ before anything starts. One decision per (principal key, address) with holds on the route, asked after
356
+ `authorize`, shared by those holds, released with the last. `admit` declares what it reads as a type's admission
357
+ does (§6: references, registries, derives, live queries; they act as the host) and returns a watchable of
358
+ `allow(null)` or `deny(reason)`. Before its first allow a hold is `loading` and **nothing is resolved or
359
+ forwarded** for its principal (a `resolve` already running for another principal finishes). **`deny`:** the
360
+ principal's holds to that address show `failed { denied }`; the relay releases them upstream and rejects their
361
+ calls in flight and waiting `forbidden/revoked`; a hold of this host's own drops its replicas. A later allow
362
+ shows them `loading` at once (the caller has access again: not "no access" through the fence and a host's
363
+ start) and forwards them again (the fence, "Relays"). A decision is told only when nothing it reads changed
364
+ while it was settled (a settle is asynchronous: a denial arriving in it is never answered with the allow read
365
+ before, which would start a host). A source that only loads keeps the last decision; **a failed or ended
366
+ source** (a decision that throws when read included) fails the holds held back `failed { waiting }` and leaves the
367
+ ones bound on the address's link alone, however often it fails. **A new link fails closed** (owner, 2026-11-15):
368
+ a hold is forwarded on a new link only under an allow that can be read then; when the link drops, or while the
369
+ next one is on its way, the holds forwarded under the last allow are taken back (`failed { waiting }` on the
370
+ source, nothing resolved for them) until the source recovers. A new link is new work at the address's host,
371
+ perhaps its start. A throwing `admit` fails the hold `broken`; a hold of
372
+ a type placed behind the route itself fails `invalid/cycle` (it would wait on itself). **Its `admit` reads only
373
+ contracts the app's API owns:** a route is base code, it never reloads and keeps the contract tokens it was
374
+ built with, so a plugin's own contract, bumped without `accepts`, would fail every decision until a restart; a
375
+ plugin serves the contract. `RouteHandle.retry(address)` resolves nothing while every hold of the address is
376
+ denied or undecided; a new link of the route forwards a hold only under its current decision. A route's decision
377
+ lives with its holds on the routing host and takes no fate in a reload; its references follow the reference
378
+ rules (§7).
379
+ - Chord closes a route link itself only at `host.close`, on the heartbeat and on a protocol error; stopping idle
380
+ workers is the app's (`host.activity`, the workers component, §23).
381
+ - Work arriving on a route's links runs under the context given to `host.route(Kind, options, context)` (slice 4b).
382
+
383
+ ### Links
384
+
385
+ - **A link is delivery only:** an ordered, bidirectional channel of `Uint8Array` messages; adapters only move bytes
386
+ and close both ends. Session recovery is the adapter's policy. Implementations (slices 3a, 4a):
387
+ - `memoryLinkPair()`: delivers with `queueMicrotask` (no Node APIs); closing one end closes the peer a microtask
388
+ later.
389
+ - `ipcLink(port)` over a Node IPC channel (`fork` with `serialization: "advanced"`, or `process` in the child),
390
+ typed structurally (no Node import in Chord). A `Uint8Array` crosses as one message; other messages on the
391
+ channel (the app's start message) are skipped. It listens from the moment it is made and queues until its
392
+ listener is set. `send` returning `false` is backpressure, not failure; a thrown `send`, an error callback or
393
+ `disconnect` closes the link once; listeners are removed on close.
394
+ - `webSocketLink(socket)` over a WebSocket (`ws` in Node, the browser's), typed structurally: one binary frame per
395
+ message, `binaryType = "arraybuffer"`; messages sent while the socket connects are buffered until `open`; a socket
396
+ closing or closed already gives a closed link; `close`, `error` and a text frame close it. The transport's
397
+ `maxPayload` stays its hard cap (code 1009 closes the connection).
398
+ - **One link object per link carries both directions** (slice 4a): the channel (handshake, codec, checks,
399
+ heartbeat), a **provider side per origin** (holds and calls the peer sent, its own or those of a relay's downstream
400
+ link, by the peer's ids) and a **consumer side** (holds and calls this host's own references sent, by its own
401
+ counters). Message kinds are directional, so each goes to its side. A link carries nothing until a hold or call
402
+ (W6).
403
+ - **Roles:** `parent` (made by `connect`), `child` (`accept`), `route` (`resolve`). The role decides whose principal a
404
+ hold acts as (section 4). **Trusted links** are an explicit option (`trusted: true` on `accept`, `connect` and in
405
+ `resolve`'s result; default untrusted; never inferred from the link kind; owner, 2026-10-23). Trust decides two
406
+ things: the `MESSAGE` schema check (skipped; framing, the codec's decode, `checkParams`, `checkArgs` and Delta decoding
407
+ still run) and the call window (none announced, below; decision "Call windows only for untrusted links"). Trust never
408
+ grants the principal fields (they are read only on the parent link).
409
+ - **Remote objects belong to a path:** the parent, or a route address. Each new link of a path holds every remote
410
+ object of that path again (with new hold ids); a closed link drops its tables and the objects go `loading`.
411
+ - **Heartbeat on every link kind, in the protocol layer** (owner, 2026-10-23): each link keeps a `lastReceived`
412
+ timestamp (every received message; sends do not count); the host runs one interval timer for all its links (none per
413
+ message). A link silent for 15 s sends `ping` (after its handshake); the peer answers `pong` at once, never queued
414
+ behind the window. A link silent for 30 s, the handshake included, is closed (its references go `loading`). Both
415
+ numbers are host options (`heartbeat`). The heartbeat detects a silent transport (TCP does not notice a sleeping
416
+ laptop), not a peer that answers pings but withholds acks (bounded by the window and the pending cap instead). A
417
+ handler that blocks the event loop longer than 30 s gets its links closed (documented). Time this process did not
418
+ run (a tick at least one interval late: a sleep, a blocked event loop) is no silence: each link's silence stays
419
+ what it was before, at least `ping`, so an open link pings at once (decision "A pause of the process is no
420
+ silence").
421
+ - **Flow control: an ack-clocked window per origin** (owner, 2026-10-23; per origin 2026-10-24). Per (link, origin), at
422
+ most **K = 2** of the provider's own `bound` and `state` messages are unacknowledged; only these two kinds count
423
+ (everything else is control, never queued behind them; `event` messages have a window of their own, below). The consumer sends `ack` (with the message's origin) after
424
+ applying each, after its batch; an `ack` crossing nothing in flight is ignored. While the window is full:
425
+ - each touched hold member keeps its ops in its **pending queue** (section 11: raw, never mutated, folded through
426
+ the leaf index, at most 10,000 ops, then only "replace with the current value"); when an `ack` frees a slot, one
427
+ `state` message carries every waiting hold's entry, its members' pending ops encoded once (or `[["r", value]]`
428
+ after an overflow), all reflecting the latest commit, still atomic for the consumer. So a slow consumer gets
429
+ coarser updates, never stale ones (measured: a `bufferedAmount` cap alone left state 9.4 s old behind kernel and
430
+ proxy buffers; acks kept it 0.0 s old);
431
+ - a hold that binds waits for a slot; its snapshot and subscription are taken in one synchronous step when its
432
+ `bound` is sent; bindings and waiting state take turns when both wait, so neither starves;
433
+ - a hold whose object leaves `live` while its `bound` waits goes back to pending (D1, owner, 2026-10-24; built in
434
+ slice 7b with the reload, which makes a live object leave `live`); so does a bound one, unbound (§7, §22);
435
+ - **a call's answer follows its state** (decision "A call's answer follows its state", owner, 2026-11-05): before
436
+ the provider sends a call's `result` or `error` (its own, or one it forwards as a relay), it sends the origin's
437
+ waiting state (every hold with pending ops, one `state` message), past the window if it is full. So when the call
438
+ settles at the consumer, every change the answering host committed before answering is applied there, and an
439
+ optimistic value (React's `useOptimistic`, `TuiScope.optimistic`) is replaced by the real one, never by the old.
440
+ Trace: window full (`bound`, `state` unacknowledged), a call commits (its ops wait), its `result`: the provider
441
+ sends `state` (the waiting ops), then `result`; without the rule the result overtook its own commit and the page
442
+ showed the old value until the next `ack`. A message past the window is counted and acknowledged like any other
443
+ (once, in order; the window opens only when fewer than K are in flight again); there is at most one per answer, and
444
+ its consumer acknowledges it before it sends the call that answer frees a slot for, so running calls and messages
445
+ past the window stay within N per origin together. Nothing extra is sent when nothing waits (the common path: a
446
+ free window sent the commit's `state` already). Bindings waiting for a slot are not sent past it: their `bound`
447
+ carries the latest state when it goes (a hold rebinding after a restart's old attempt ended shows its old values until then).
448
+ Not covered: changes committed after the answer (a method that returns before its effect lands) or on another host
449
+ that does not relay the answer.
450
+ Not built, by decision: a byte window, credit messages, snapshot admission or debt, an adapter `backlog()` API,
451
+ `reset` from anyone.
452
+ - **Calls: a call window N** announced in `hello`: how many concurrent calls a side accepts **per origin** (decision
453
+ "Call windows only for untrusted links", owner, 2026-11-11): on a link it was not given as trusted, the host option
454
+ `callWindow` (default 10,000); on a trusted link none (`hello.calls` absent), so the app's own hosts never queue calls
455
+ behind each other. A side sends no call before the peer's `hello` ("no hello yet" is a state of its own, apart from
456
+ "no window"); a side whose peer announced no window sends its calls at once. A host sends at most N of its own calls
457
+ per link in flight; further calls wait in the link's **call queue**, one FIFO, sent in order as replies free slots;
458
+ nothing is refused for being "too many" (K16). The window bounds calls in flight, not calls waiting to be sent: a
459
+ caller's queue is the caller's (an app's latest-only outbox for motion, `events/spec.md` §7). A slot is freed once
460
+ per call: by its `result` or `error`, its `abort` (when sent, at the caller; when received, at the provider), its
461
+ hold's `release`, `gone`, its origin's `closed` or the link closing. A call still queued when its hold rebinds
462
+ (`loading`) is rejected `unavailable` (it may name a method of the old variant); one already sent is answered by the
463
+ provider (a `loading` unbind keeps it, below). A provider seeing more than N running calls of one origin closes the
464
+ link (protocol error), one that announced none never closes it for running calls; a call naming a hold it does not
465
+ know is ignored before it is counted (Q1). **There is no limit on
466
+ calls in progress per link** (owner, 2026-11-03; Chord v1's `maxCalls` had no counterpart): the call window N per origin
467
+ and the part limits (section 22) are the bounds; 200 concurrent calls over one socket all run, N at a time in
468
+ flight. A per-link N, if ever needed, must bound a relay's forwarding too (relays honour each upstream window: below).
469
+ - **Events: an event window per origin** (decision "Events: fire-and-forget members", owner, 2026-11-11). Per (link,
470
+ origin) the emitting host leaves at most `eventWindow` (default 32) of its own `event` messages unacknowledged; one
471
+ that finds it full at an event flush (section 11) **drops** that origin's entries of the flush (counted
472
+ `chord.events.dropped { reason: "window" }`), as they are visited, before a value is encoded or an entry built for
473
+ them (the window cannot change during a flush; a value admitted for another origin or link is encoded once and its
474
+ part reused); nothing is queued for later, so the provider holds no backlog for a slow
475
+ consumer (what is already sent may still sit in transport and proxy buffers: a consumer whose path crosses W workers
476
+ and the server may have (W + 1) × `eventWindow` in flight). The consumer sends `ack { events: n }` (n at least 1: the
477
+ `event` messages of that origin it **consumed** since its last such ack: inflated, a browser's asynchronous inflate
478
+ included, parsed, and its entries delivered or deliberately dropped; never on transport receipt), at most one per
479
+ origin per inbound turn (coalesced in a microtask after the first message it consumed, so after the event flush that
480
+ delivered it). An `ack` with `events` acknowledges events only, never combined with a state ack: state's window and
481
+ its variant fence are untouched, and events flow while the state window is full, and the reverse. **Event tickets:**
482
+ per link and origin the provider side keeps a FIFO of the `event` messages it sent and not yet had acknowledged,
483
+ each with its sender, `local` (this host's emits) or the upstream link a relay forwarded it from; `ack { events: n }`
484
+ consumes exactly the first n: a `local` one frees a slot of the event window, a relayed one is returned to its
485
+ upstream link as `ack { origin, events }` (summed per link); a ticket of an upstream link that closed is consumed and
486
+ returned nowhere. A provider side's record is retired only when it has no holds, no calls, no state messages and no
487
+ event tickets in flight (or its link or origin closes). Late samples are the app's to discard by its own timeline.
488
+ - Holds are not limited by count (authorization and params checks protect them); size limits are a separate check
489
+ (section 22). Byte-heavy traffic (terminals) uses separate channels (section 23), so a large state message never
490
+ holds up keystrokes.
491
+
492
+ ### Relays (slice 4a; decision "Relay flow control per origin", owner, 2026-10-24)
493
+
494
+ A host that receives a hold it cannot serve (the table above: a route or the parent) **relays** it: it holds
495
+ it again on that link (upstream) with the arriving hold's principal and incarnation, and forwards between the two
496
+ without parsing payloads. The provider keeps the window, the pending queues and the calls per origin; the relay never
497
+ drops, folds or resets.
498
+
499
+ - **Origins:** the relay gives each downstream origin (a downstream link, and the origin its messages carry when that
500
+ link is itself a relay's) a number, one counter per host, never reused; 0 is a host's own work. Every message
501
+ upstream for that origin carries `origin`; the provider keys holds, calls, windows and acks by (link, origin, id), and
502
+ its answers carry the origin back. `origin` is read only on parent and route links, where a relay's messages
503
+ arrive (a worker may relay a child's hold to its parent); on a child link it is a protocol error (decision "Origins
504
+ only from relays", 2026-10-31); a per-origin record goes once it has no holds, calls or messages in flight;
505
+ principals and incarnations stay parent-only.
506
+ - **Ids are not renumbered:** an upstream hold has the downstream hold's id under the origin's number; calls the same.
507
+ Two tabs (two holds) of one principal are two upstream holds, each with its own encoders (R1). **A hold released
508
+ by a route's denial is forwarded again, under its id, only behind a fence** (slice 14): on the allow the relay
509
+ sends a `ping` and forwards the hold after that ping's `pong`. A link is ordered and a peer answers a `ping` after
510
+ everything it sent before it, so every reply of the released hold has arrived, and was dropped (state messages
511
+ still acknowledged, an `event` message forwarded with what is left of it), before the hold exists again. The
512
+ channel counts pings and pongs, so a liveness `pong` in transit ends no fence; a denial before the `pong` ends
513
+ it, and a lost link forwards under the current decision on the next one. **The fence relies on `resolve`
514
+ returning the link to the final provider that serves the address,** as the route contract requires: an
515
+ intermediate relay would answer the `ping` before the final provider's old replies have drained through it.
516
+ - **Nothing is parsed:** the relay routes by the hold's address and authorizes it; params, arguments, results,
517
+ snapshots and ops travel as opaque parts. Cost per message: decode the envelope, swap the origin, encode the
518
+ envelope; parts copied once into the outgoing buffer.
519
+ - **What the relay keeps:** per relayed hold, its upstream link and its original `hold` message (params copied once),
520
+ which routes `call`, `abort`, `retry` and `release` upstream at once and holds again on the next link; per
521
+ downstream origin, the FIFO of the sender of each `bound`/`state` message in flight, its event tickets, the set of
522
+ upstream links it relayed to, and per upstream link the queue of its relayed calls past that link's window.
523
+ - **Forwarding up:** `hold`, `call`, `abort`, `retry`, `release` with the origin's number; a hold waiting for its
524
+ route is sent when the link exists; a `release` before that drops it. With no upstream link a call is answered
525
+ `unavailable` (it crossed the `loading` notice). **Relays honour each upstream window** (decision "Call windows only
526
+ for untrusted links"): a downstream origin's calls go upstream under that origin; when the upstream link announced a
527
+ window, the origin's relayed calls past it wait in a FIFO per (upstream link, origin) and go as answers free slots
528
+ (the consumer side's window logic), a new call never overtaking the origin's queue (none announced: at once). Queued
529
+ relayed calls follow the relay's own queued calls' lifecycle: when the relayed hold gets `loading`, its unsent calls
530
+ are rejected `unavailable` (they carry the old variant's method indexes) and its forwarded ones are kept; on
531
+ `failed` or `gone` its unsent calls are rejected with that cause; before the relay forwards the downstream's `ack` of
532
+ a new `bound` upstream (which ends the provider's decoding by the old indexes), it rejects every call of that hold
533
+ still in its queue `unavailable` (one that crossed the `loading` notice carries the old indexes; calls arriving after
534
+ that ack were made with the new binding, which a consumer's ack precedes: it acknowledges a `bound` before its
535
+ reference sends the calls parked while it rebound). `abort` takes a waiting call out unsent (a forwarded one is aborted
536
+ upstream, then its slot frees), `release` is forwarded upstream first, then the hold's waiting calls are dropped and
537
+ its forwarded ones free their slots (a call of another hold that takes one reaches the upstream after the release,
538
+ which ends the forwarded ones there: else an honest finite-window upstream counts one call too many and closes the
539
+ link), `closed` and an upstream drop end them as the relay's own; a queue entry is removed before its slot is counted
540
+ free.
541
+ - **Forwarding down:** a message from upstream with an origin goes to that origin's provider side, which forwards it
542
+ with its own origin (none for a tab), ids and parts unchanged. **A link answers only for what was relayed over it**
543
+ (owner, 2026-10-24): every entry of a `bound` or `state`, every `failed`, `loading` and `gone` by its hold, every
544
+ `result` and `error` by its call is checked against the relay's table; an answer for a hold or call not relayed over
545
+ the link it came from is dropped (Q1: also one crossing a release). A `bound` or `state` left with some entries is
546
+ forwarded with those; left with none, it is acknowledged to that link at once. A message for an origin from a link
547
+ the origin relayed nothing to is ignored whole. A `result` or `error` forwarded goes after the relay's own waiting
548
+ state for that origin (the rule above: a worker's answer whose effect the worker pushed to the server arrives after
549
+ that server state); the upstream host sent its own waiting state before its answer, and the relay forwarded that at
550
+ once.
551
+ - **Events** (decision "Events: fire-and-forget members"): a relay forwards an upstream `event` message at once, never
552
+ dropping it for congestion. A link answers only for what was relayed over it: entries of holds not relayed over the
553
+ link they came from (released, rebound, from an old upstream link) are filtered out and the message is forwarded with
554
+ what is left, also with no entries, its ticket naming its upstream link. A relay never acknowledges an `event`
555
+ message itself: an early ack of a filtered message would consume an upstream ticket of an earlier message still
556
+ unconsumed downstream (two senders behind an upstream relay), so the downstream's acks, in order, stay the only credit.
557
+ - **Acks:** the relay forwards each upstream `bound`/`state` at once and returns its `ack` to the upstream link that
558
+ sent it when the downstream acknowledges it (the senders FIFO). A tab served by W workers may have 2W messages in
559
+ flight (plus the relay's own 2), each worker's window bounding its own. A slow tab stalls only its origin at each
560
+ worker; other tabs are other origins. Measured: a slow tab through the relay catches up like a direct one (a 60 s
561
+ stall: 0.38 s, 23.7 KiB at 64 KiB/s; before the rework, 24 s and three full snapshots).
562
+ - **Upstream drop:** the relay sends `loading { hold }` downstream for every relayed hold on the dropped link, fails
563
+ their relayed calls in flight or waiting for its window `unavailable` (never resent), re-resolves and holds again upstream from the kept
564
+ message (same id, same origin); the new `bound` is forwarded. Acks for messages of the dropped link still in flight
565
+ downstream go nowhere.
566
+ - **Downstream drop:** the origin's provider side ends: its served holds are released, its relayed holds forgotten,
567
+ and every upstream link it relayed to gets one `closed { origin }`, which releases the origin's holds and aborts its
568
+ calls there; the origin's number is never used again; messages crossing it are dropped.
569
+ - **`gone`** from upstream is forwarded; the relayed hold is forgotten. Relays never make a `gone`.
570
+
571
+ ### Recovery
572
+
573
+ - After a drop the consumer re-holds every hold of the path over the new link and receives snapshots (a `bound` on a
574
+ bound hold replaces its replicas in one batch, another variant allowed); calls in flight fail like on a disconnect;
575
+ calls made meanwhile park (section 7).
576
+ - A slow connection never ends an object: nothing releases a hold for falling behind (the reference count is unchanged).
577
+ - A link drop is a departure (section 19).
578
+
579
+ ### Values
580
+
581
+ - **JSON plus `Uint8Array` leaves**, with a bytes schema type, defined independently of the transport. Every link
582
+ carries the same `Message` through its codec (section 22); parts are encoded at their origin; byte segments travel
583
+ raw, never base64. Same-host calls (no link) pass values by reference.
584
+ - Schemas are plain JSON Schema built with `@diffra-ai/schema` (decision "The schema switch") and must
585
+ describe data (no callbacks, no native types, no runtime codecs); `format` is an annotation, never checked. Method arguments are
586
+ validated at the provider for every caller against closed schemas (section 5, R7, Q12, Q15); results and state are
587
+ never validated (section 30). Values are immutable by convention once handed over (Delta's rule): nobody mutates a
588
+ value it got, and nothing is copied or frozen to enforce it. There is no development mode (R9): one behavior
589
+ everywhere.
590
+
591
+ ---
592
+
593
+ ## 4. Principals
594
+
595
+ - The app defines its principal type `P`: JSON, every variant with a `kind`, a type alias (not an interface),
596
+ unversioned (owner, 2026-10-22): Chord never persists principals, base code changes every host at once, links stamp
597
+ them. Objects persist a projection with its own schema, never the principal (p2: chat's `Author { kind, id, name }`).
598
+ p2: `owner` (`access: "local" | "relay" | "device"`), `guest` (`session`, `mode`, grant revision), `server`,
599
+ `worker` (`session`). p3: `owner`, `person`, `worker`, `server` (p3's decisions "The principal is identity only" and "Persons, guests
600
+ and links": no guest kind; what a person may reach is data, read by admissions).
601
+ - **Links stamp principals.** A caller's own data never sets its principal.
602
+ - **The principal key** maps a principal to its object identity (`principalKey`, default canonical JSON; cached per
603
+ principal object; the same function on every host). It should include connection provenance and grant revision, so
604
+ a revoked grant's objects are distinct from a new grant's **(carried over)**.
605
+ - **Principals on holds** (slice 4a; owner, 2026-10-23): a `hold` carries `principal?` and `incarnation?`. The receiver
606
+ uses them **only on its parent link**; everywhere else they are ignored and the link's principal and peer
607
+ incarnation apply (a tab cannot claim to be the owner; a relay overwrites what a client sent). Calls carry neither: a
608
+ call runs as its hold's principal and with its hold's incarnation (refines R1/Q13, which stamped calls too). What a
609
+ host sends in those fields when it holds over a route link (towards a child that honours them):
610
+
611
+ | The reference was made by | `principal` | `incarnation` |
612
+ | --- | --- | --- |
613
+ | `host.get` / `host.hold` | the host's own | this host's |
614
+ | `ctx.get` in a handler | the handler's `ctx.principal` (the caller's) | the handler's `ctx.incarnation` |
615
+ | `self.get` in a remote object | that object's principal | this host's |
616
+ | `self.get` in a local object or a facet | the host's own | this host's |
617
+ | a relayed hold | the arriving hold's principal | the arriving hold's incarnation |
618
+
619
+ So a guest's call on the server whose handler `ctx.get`s a worker type reaches the worker as the guest and gets the
620
+ guest's variant; two references with different principals are two remote objects. A server object that acts as
621
+ itself towards a worker takes the reference with `self.get` in its own object or in a server root (`host.root`,
622
+ acting as the host), never with the method's `ctx.get` (owner, 2026-11-03; p2's footgun 7): the owner calls
623
+ `Search.rebuildIndex`, whose `ctx.get(IndexScan, { session })` reaches the worker as the owner, and a worker
624
+ factory checking `principal.kind === "server"` refuses it.
625
+ - **Upward is a boundary:** a worker's hold of a server type goes over its parent link, and the server ignores
626
+ principal fields from a child, so it acts as the worker, whoever the worker's handler serves. A worker that acts for
627
+ a user towards the server passes the user as data and the server object decides.
628
+ - **The caller's incarnation** (R20, Q13): `ctx.incarnation` is the incarnation of the host where the call started
629
+ (from the handshake, or from the hold's field on a parent link), next to `ctx.principal`, not part of the principal
630
+ or its key, never sent as data by apps; it is this host's own for local calls (section 25 uses it as a fence).
631
+ - **Revocation** (slice 4b) is a typed app function, not field matching:
632
+
633
+ ```ts
634
+ type Revocation = { grant: string } | { device: string } | { session: string };
635
+ const server = createHost<P, Revocation>({
636
+ address: Server(), principal: { kind: "server" }, onError,
637
+ revokedBy: (p): Revocation[] =>
638
+ p.kind === "guest" ? [{ grant: p.grant }, { session: p.session }]
639
+ : p.kind === "owner" && p.access === "device" ? [{ device: p.device }]
640
+ : [],
641
+ });
642
+ server.revoke({ grant: "g1" }, ctx);
643
+ ```
644
+
645
+ `host.revoke(r)` ends every object and closes every child link whose principal `p` has `r` in `revokedBy(p)` (compared by
646
+ canonical JSON of each value `revokedBy` returns, computed once per principal; never the host's own principal), and propagates `r` to the children as a `revoke` message on its route links,
647
+ honoured only on a child's parent link, where each applies its own `revokedBy` (the same app code; nothing is
648
+ replayed to a child connected later). Holders of a revoked object get `gone` with `forbidden/revoked` (owner,
649
+ 2026-10-24: a reason of its own, so a UI can say "access revoked"); holds still waiting for `load` are ended too.
650
+ Order: the `revoke` message goes out on the route links before the revoked child links close, so a worker's objects
651
+ end `forbidden/revoked`, not `released` by the tab's `closed`. Revocation ends a principal's objects at
652
+ once, whatever references or jobs remain (R11); their jobs get the abort signal and the normal `closeTimeout`.
653
+ There is no re-stamping: a changed grant (mode `write` → `read`) is a revocation of the old one; the client
654
+ reconnects and authenticates anew, and its references re-hold. Reconnecting never restores revoked authority. Work
655
+ started on behalf of a revoked principal in a shared store stops when its reconciling routine runs (R10's window,
656
+ accepted; section 25); there is no revocation hook.
657
+ - `local` objects have no principal in their identity; their handlers and references act as the host (section 5).
658
+
659
+ ---
660
+
661
+ ## 5. Object types
662
+
663
+ ```ts
664
+ export const Notes = remote("notes", { version, hostAddress, params, variants });
665
+ export const NoteStore = local("notes.store", { version, params, members });
666
+ ```
667
+
668
+ | | `remote` | `local` |
669
+ | --- | --- | --- |
670
+ | reachable from | any host, across links | its own host only |
671
+ | identity | (type, params, principal key) | (type, params) |
672
+ | principals, variants | yes | no |
673
+ | factory | `(params, principal, self)` returning `{ variant, members }`; `(params, principal, admitted, self)` for a type with an admission | `(params, self)` returning the members |
674
+ | arguments | validated once at the provider for every caller (compiled closed schema, R7, Q12); unknown fields rejected; passed by reference on the same host | validated the same way (Q15), never copied |
675
+ | results | not validated; passed by reference on the same host | not validated, not copied |
676
+ | members | state (JSON), methods (JSON plus bytes) and events (JSON) | plain-data state, methods and events (`event(schema)`); no `opaque`, no callbacks |
677
+ | `ctx.principal` in methods | the caller | the host's principal (none on a client); references a local object makes act as the host |
678
+
679
+ ```ts
680
+ variants: {
681
+ editor: { state: { notes: NotesSchema }, methods: { add: method(AddArgs, NoteId), remove: method(RemoveArgs) } },
682
+ reader: { state: { notes: PublicNotesSchema } },
683
+ },
684
+ // the factory chooses one variant per object (slice 3a, C15):
685
+ host.serve(Notes, ({ session }, principal, self) =>
686
+ principal.kind === "owner" ? { variant: "editor", members: { notes, add, remove } } : { variant: "reader", members: { notes: publicNotes } });
687
+ ```
688
+
689
+ - **Admission** (slice 14): a remote contract may declare `admission: schema`, the JSON value its factory is handed
690
+ about a caller (`AdmittedOf<C>`). It selects the variant and the members, nothing else; it is not part of the
691
+ fingerprint and is never validated at runtime (its own fingerprint is what a reload's staging compares).
692
+ `evolve`'s `admission(schema)` replaces it (the last edit of a version). `local` types have none. Section 6.
693
+ - **Names** (owner, 2026-10-27): object type names, host kind names, document (`defineState`) and job (`defineJob`)
694
+ names use `[a-z0-9@/._~-]`, lowercase, checked at declaration (they become SQL table names in the store, joined with `:`).
695
+ - **Keyed state members** (owner, 2026-10-26; `local` contracts only): `members: { notes: keyed(NoteSchema) }`; the
696
+ provider returns a keyed document handle; a consumer on the same host takes `ref.notes.at(key)` in its factory (a
697
+ counted pin: the key stays loaded while the consumer lives) or `ref.notes.watch(key, ctx)`/`get(key, ctx)` anywhere;
698
+ an absent key reads `initial()`, a retirement arrives as the `retired` flag (a derive over it carries the flag on).
699
+ Across links, a view per entity (`NoteView { session, id }`) is held as an ordinary remote object.
700
+ **Named queries** (slice 14; `local` contracts only): `members: { sessions: queries(SessionRow, { visible:
701
+ argsSchema, one: argsSchema }) }`; the provider returns what `self.queries` gave; a consumer on the same host reads
702
+ one with `self.liveQuery`, `self.count` or `page` (section 11).
703
+ **Host-keyed members** (decision "Documents and table rows can belong to a host", 2026-11-09; spec
704
+ `host-keyed/spec.md` §1): `keyed(schema, Session)` keys the member by addresses of a host kind; its implementation is
705
+ a handle of a definition keyed by that kind (`keyed: Session`; another key kind fails the activation), the
706
+ reference's member takes addresses (`ref.meta.at(Session({ id }))`, checked and encoded to the canonical key), and
707
+ the kind's name joins the member's normal form (`{ keyed, key }`; string-keyed members keep their fingerprints). A
708
+ changed key kind is a change `accepts` can only refuse (a value mapping cannot map keys).
709
+ - **Methods:** `method()` (no arguments, no result), `method(args)`, `method(args, result)`, `method(undefined,
710
+ result)`. A method without arguments omits them in the API (`ref.bump(ctx)`, implemented as `bump: async (ctx) =>
711
+ …`); `null` is their internal and wire form (owner, 2026-10-22).
712
+ - **Implementations** (owner, 2026-10-22): a state member is a JSON `Watchable` the factory returns (a document handle,
713
+ a derive, a reference member, `constant(...)`), never a getter; a method is a function `(args, ctx)` or `(ctx)`; an
714
+ event member is an `EventSource<T>` of the attempt's own (`self.events<T>()`) or a reference's `EventMember<T>`
715
+ (re-exposed). Activation checks what the factory returned (plugin code): exactly the variant's members, methods as
716
+ functions, state members as JSON watchables (a `NativeWatchable` or anything else fails the object `broken` naming
717
+ the member, Q14), event members as one of those Chord-made values (anything else, another attempt's source included,
718
+ fails it `broken` naming the member).
719
+ - **Event members** (decision "Events: fire-and-forget members", owner, 2026-11-11): the third member kind, a JSON value
720
+ an object emits, delivered once to each reference that was bound to the object before the emit and still is when the
721
+ event is sent, never folded, never kept, never sent to a later holder, dropped for a holder that cannot keep up. Over
722
+ a link the provider's holder is the wire hold: references of one host sharing it (§7) get what arrives at their host
723
+ after each bound, also an event emitted before it that was still in transit (decision "References share one wire
724
+ hold"). A remote variant lists them under `events` (`variants: { player: { state, events: { paddle: Paddle }, methods } }`), a
725
+ local contract marks them in its flat members with `event(schema)`, as `keyed(schema)` marks a keyed member. Their
726
+ schemas describe JSON only (no `bytes()`) and may differ per variant (redaction). Types: `EventMember<T>` (the read
727
+ side, `on(listener, ctx): Promise<EventSubscription>`; references expose only it, never `emit`), `EventSource<T>`
728
+ (the owner's, adds `emit(value)`), `EventSubscription` (`stop()`); a listener gets `{ value, at }`. Delivery, wire and
729
+ versions: sections 11, 22 and 27.
730
+ - **Reserved member names:** `then`, `release`, `state`, `retry` and `variant` are refused at declaration (a reference
731
+ has them; `then` would make an awaited reference thenable).
732
+ - **Compatibility (strict, like documents; R6):** a hold carries only the consumer's contract `version` and
733
+ fingerprint, never a description. The provider binds when both equal its current ones, or (slice 7b) when the
734
+ version is one it accepts and the fingerprint equals the one computed from its own history (section 27). Every
735
+ contract change, additive ones included, bumps `version`. Anything else leaves the request unbound `version`:
736
+ `failed { waiting }` with `contract_mismatch` (slice 7a: not the consumer's fault; a publication that fits wakes it,
737
+ §3). The fingerprint covers params, variants and members, not the host address. A consumer whose contract does not
738
+ fit waits on its own request; the provider object and its other bindings are not affected.
739
+ - **Variants:** a member name has the same kind (state, keyed, method or event) in every variant that has it and for the
740
+ whole history, and a method the same signature (arguments and result) in every variant; state and event schemas may
741
+ differ per variant (redaction). Enforced at
742
+ the type level in `remote(...)` and at declaration at runtime. A remote factory returns one variant, `{ variant,
743
+ members }`; `ref.variant` is the discriminant (section 7). Calls are checked against the binding's variant
744
+ (`invalid/member` outside it).
745
+ - **Params** (owner, 2026-10-21/22): a flat record of required fields, each `str()`, `int()`, `bool()` or `oneOf(...)`
746
+ of string literals, constraints allowed (`str({ pattern })`, `int({ min: 0 })`); no defaults, optional, nested or
747
+ unknown fields. Checked for every caller with one compiled closed-object diffra-schema check (a missing or extra field
748
+ fails `invalid/params`). The identity key is the field values in declared order, each escaped, joined with `|`.
749
+ Params are never copied or frozen: the object keeps the caller's object, immutable by convention.
750
+ - **Arguments (R7, Q12, Q15):** always validated with the provider's schema, whoever the caller is (trusted code is
751
+ not type-checked code: plugins are bundled without type checks), never with a schema a peer sent; object schemas are
752
+ closed (`obj()` sets `additionalProperties: false`), so an unknown field fails `invalid/args` instead of being
753
+ stripped; nothing is copied or mutated; arguments have no defaults (optional fields are `opt()`, handlers write
754
+ `args.limit ?? 50`). Same-host arguments are not checked for plain data (no prototype or getter checks): callers pass
755
+ plain data by convention. Provider schemas compile lazily at first use, cached in `WeakMap`s keyed by the schema
756
+ owner; accepted versions' validators also on first use. Bytes are leaves (`instanceof Uint8Array`, optional length
757
+ bound), never walked. Results and state are not validated.
758
+ - **Providers** (`bindProvider(Type, accepts)`, L1): runs `checkAccepts` once per load and reload and keeps the
759
+ validated mappings; per call `checkArgs(provider, method, raw, boundVersion, context)` returns a tagged value,
760
+ `{ kind: "method"; args; result? }` (current-shape arguments and, for an old-version caller, the result mapping back)
761
+ or `{ kind: "call"; args; call }` (the provider's own replacement of a removed method, invoked by Chord, slice 7b). The
762
+ binding is held only by the served type's registration and by calls in flight (GC-tested; no global strong cache).
763
+ - **Errors** (L1, slice 3a): `ChordError` with a code and, for some codes, a reason, a closed union that is part of the
764
+ link protocol (adding one bumps the protocol version; a receiver rejects unknown reasons; a test pins the list):
765
+ `invalid` (`args`, `params`, `member`, `host_address`, `reentrant`, `read_after_bulk`, `cycle`), `contract_mismatch`
766
+ (`updating`), `forbidden` (`revoked`), `gone`, `not_ready`, `released` (`ended`, `closed`, `settled`, `version`, `discarded`; none for a holder's own release), `too_large` (`part`), `unavailable` (`locked`,
767
+ `park_timeout`, `busy`, `storage_failed`, `undeclared`: a registry no plugin serves here, slice 8), `aborted`. A failed check names diffra-schema's JSON Pointer path ("unknown field", "missing", else
768
+ diffra-schema's message; `~` and `/` in keys escaped as `~0`, `~1`). Plugins throw `PluginError(code, message,
769
+ details?)` for codes of their own; anything else crosses a link as the plugin code `internal` with its message, never
770
+ a stack or a cause; plugin errors never use Chord's codes. An error rebuilt from the wire is not copied and only its
771
+ envelope is checked; a malformed envelope is a protocol error. Chord's root exports `invalid` and `forbidden`, which an
772
+ app's API re-exports, so a plugin throws a decided `ChordError` (decision "Tutorial gaps" (4)).
773
+ - **Methods return data,** never objects; an object is handed out as its address and the receiver does `ctx.get`.
774
+ - **No callbacks as arguments,** on either kind: behaviour goes through registries, multi-step work through jobs,
775
+ input through flows, runtime services through core objects. Real schemas instead of `Type.Unsafe`.
776
+
777
+ ---
778
+
779
+ ## 6. Objects
780
+
781
+ ### Lifecycle
782
+
783
+ ```
784
+ (get) → [admitting] → activating (parked on its dependencies → own steps) → live → ending → ended
785
+ │ └→ failed (backoff) → activating …
786
+ └→ failed (denied): parked until its admission allows
787
+ live → failed (a runtime failure of the owner, slice 6a: broken, by reload or retry only)
788
+ live → admitting (its admission changed: sealed at once, slice 14)
789
+ ```
790
+
791
+ - **One object per identity.** The first `get` runs the factory; later gets share the object.
792
+ - **Lifetime follows from kind and params (Q-A, owner, 2026-10-21):** there is no `lifetime` option and no lazy flag.
793
+ A `local` type with empty params lives as long as the host: started eagerly at host start, never ended by reference
794
+ count (it may hold persisted data, P3, and contribute to registries, R21). Every other `local` type and every
795
+ `remote` type lives while referenced (`linger` keeps it briefly after the last reference). No remote object has host
796
+ lifetime: its identity includes the principal, and long-lived parts belong in a local shared store. Below,
797
+ "host-lifetime object" means a `local` object with empty params. Running and finishing job runs keep their
798
+ object alive as a count, not as references, while an attempt is live or activating ("Slice 6a small items" (12)); when
799
+ the count reaches zero with no holders, the object ends (§15).
800
+ - **Activation** (one fresh attempt each time, bounded by `readyTimeout`, its wait for the previous instance's
801
+ teardown included): an attempt of an admitted type first runs its `admit` ("Admission" below); the factory runs; singleton documents take `initial()` and, on the object's first activation,
802
+ persisted documents load and its tables' definitions are checked and migrated (slice 6a; the deadline paused during
803
+ eager migration work); its requests are made (`self.get`, `self.registry`, keyed pins), and the attempt is
804
+ **parked** until every one is live and hydrated (below; the deadline paused); then its own steps run under the
805
+ deadline: natives open one after another, followed sources attach, the returned members are checked (section 5),
806
+ derives compute; routines start (slice 5). The object goes live when all of that succeeded. Calls wait behind its
807
+ **gate** until then.
808
+ - **The seal fence** (owner, 2026-10-26): every attempt has a seal token (a job run invocation its own, for its state
809
+ changes and outcome). After the seal, new work through the attempt's handles is refused at use (`self.tx`, `ctx.get`,
810
+ a job or routine start); commits are checked when they enter the store's commit step (sealed: rejected `released`,
811
+ nothing written) and at adopt (sealed during the SQL: durable, adopted into the object's documents, its staged job
812
+ changes adopted into the object too: decision "Second spec review: the majority" (3)); at the seal a transaction not yet in the step is aborted and the line released, a started step
813
+ finishes before teardown completes; cleanup (references, presence, activity counts) still runs.
814
+ - **Ending** (slice 1, 2): new calls are rejected; every caller of a running call gets `released` at once; the
815
+ handler keeps running in the background under an aborted context and its `self.tx` throws `released` (a running
816
+ method can change nothing after the end). Each call runs under a context aborted by its caller and by the object's
817
+ end (one controller per attempt, linked until the call settles; a caller's cancellation aborts only its own call); a
818
+ call whose caller context is already aborted is rejected before its handler runs. Then the **drain** waits for the
819
+ handlers' own promises, bounded by `closeTimeout` (`drain_timeout` reported), natives close in reverse order,
820
+ documents are dropped, derives detached, and references released last (closes may use them). Routines stop and jobs
821
+ follow their rules (slice 5).
822
+ - **A live object can fail** (owner, 2026-10-26): a runtime failure of the owner (a `migrate` failing on access, a
823
+ stored version newer than the code) seals the live attempt and makes the object `failed` (`broken`): calls reject
824
+ with the cause, state members keep their last values, natives close, documents stay on the object; recovery by
825
+ reload or `ref.retry()`; live dependents stay live. Its references keep following every member (its own and
826
+ re-exposed ones) until the commits admitted before the seal adopted and published once, then take their last values
827
+ (audit A10, 2026-10-30: one rule, as restarts), and a retry's factory waits for that.
828
+ - **Parked on its dependencies** (dependency model §3, slice 7a; supersedes R18's dependency deadline and backoff): a
829
+ dependency is what an attempt declares and needs before it goes live: `self.get` (local or remote), `self.registry`,
830
+ keyed pins (`at(key)` on another object's keyed member); `self.follow` is the attempt's own step, not a dependency.
831
+ While any dependency is not live (and hydrated), the attempt is parked and its object shows:
832
+
833
+ | Its dependencies | The object shows |
834
+ | --- | --- |
835
+ | any `loading`, none failed | `loading` |
836
+ | any `failed` | `failed { waiting }`, `retryAt` undefined, error `unavailable` "waiting for X: <root cause>" (X the first failed one in declaration order, the root cause found through its message's "waiting for …: "; always these two, so a ring of waiting attempts settles after one round; within 500 characters, X's label clipped first, fix round 1) |
837
+ | one failed with `invalid/cycle` (a dependent off the ring) or `forbidden` (an `authorize` that refused it: authority, M§3.6) | `broken` with that error: nothing heals it but `ref.retry()` or a reload |
838
+ | one `ended` (revoked, its host closed) | `broken` with that error: the request cannot come back |
839
+ | one denied by an admission (slice 14; checked before the `forbidden` row) | `failed { denied }` with that error: it stays parked and goes on when the dependency is admitted; no `parked_long` |
840
+
841
+ **Nothing times out while parked:** no dependency deadline, no backoff (only `parked_long`'s diagnostic report, below); the attempt's `readyTimeout` deadline is paused
842
+ (as eager migrations pause it) and resumes with the budget left; the identity backoff stays for the object's own
843
+ `transient` failures only. **Wakes:** the parked attempt checks again at every change of a dependency (live,
844
+ loading, failed, a new cause compared by value, ended, and its first outcome, below), coalesced per object after the
845
+ batch that caused them (a change while it checks or loads pinned keys is remembered); it never re-runs its factory.
846
+ A parked attempt keeps its documents, declarations, requests and seal token, and holds no natives. **The dependency
847
+ check is the boundary:** once all are live (and the pinned keys loaded), the own steps run; a dependency that leaves
848
+ `live` afterwards changes nothing (R18 after live: the object goes live; its calls through that reference meet its
849
+ state). **Retry passes on:** `ref.retry()` (or a `retry` message) on an object parked `failed { waiting }` passes on
850
+ to its failed dependencies (audit A5, 2026-10-30): on one host one retry's walk keeps a visited set, so a diamond
851
+ retries a shared dependency once; across links the `retry` message carries a hop budget (`hops`, 16 from the first
852
+ host, one less per host, dropped at 0), so a waiting ring across hosts passes it round until the budget runs out
853
+ (starting no attempt) and a diamond across hosts may retry a shared dependency twice (harmless). A `broken` or
854
+ `transient` one starts an attempt, a parked one passes it on, a request waiting unbound in an index is left as it is
855
+ (an event wakes it), a refused hold over a link re-runs its start. A `retryOn` wake while parked does nothing. When
856
+ a parked object's last reference goes, it ends at once (it is not live: no `linger`) and releases its requests.
857
+ `broken` is only for an object's own code, cycles and authority; no failure keeps references (the R18 retry trigger
858
+ is gone: parking replaces it).
859
+ - **Dependency cycles are rejected (Q5):** every object instance has a uuidv7 instance id, minted at its first
860
+ attempt; an object that restarts gets a new one, so an old chain never matches (slice 4b, the first user; D4,
861
+ owner, 2026-10-24). On one host, at
862
+ `self.get(B)` during A's activation Chord follows the waiting edges of activating objects from B; reaching A is a
863
+ cycle. Across hosts, a hold made during an activation carries the activation chain of instance ids in its header
864
+ (bounded; ignored from untrusted links): the provider rejects the hold when the instance being activated is in the
865
+ chain (slice 4b; on one host slice 1; at most 32 entries; locally created objects inherit the activating chain). A
866
+ cycle fails the activation `broken invalid/cycle` with the cycle as cause ("A → B → A"), and every other activating
867
+ object on it the same way; no references are kept. A dependency failing with `invalid/cycle` makes its dependent
868
+ **broken** with the same error (owner, 2026-10-24: it would wait on a ring that never heals); dependents that are not
869
+ on the cycle break too, and a reload or `ref.retry()` recovers them. The walk on one host follows the waiting edges
870
+ of activating and parked attempts (exact). Checked again after a reload. Cost: O(chain) per declared reference,
871
+ only during activation.
872
+ **The gap: rings across hosts started at the same moment** (owner, 2026-10-29: no probe): a chain is fixed when its
873
+ object is created, so a cycle entering an object already activating is not detected. Example: A on the server and B
874
+ on a worker start at the same moment, A declares B and B declares A; the holds carry `[A]` and `[B]`, neither finds
875
+ the other, and without a dependency deadline both stay parked. It is made visible: an attempt parked longer than its
876
+ `readyTimeout`, whatever its blocker (audit A11, 2026-10-30), is reported once per parking episode as
877
+ `parked_long { object, waitingFor, state, since }` (`waitingFor` the blocker's label, `state` `loading` or `failed`); nothing fails or retries. A cycle is a plugin bug; **the guide's four
878
+ rules** for plugin authors and agents (host README): (1) a factory declares only what the object needs, never a type
879
+ that needs it back; (2) back-references and occasional lookups go into methods and routines (`ctx.get`); (3) data
880
+ flows up through state and registries, not mutual `self.get`; (4) host-lifetime objects on the server never declare
881
+ worker types in their factory.
882
+ - **Failed:** a broken part fails the whole object: a throwing factory, document hydration or `migrate`, a failed
883
+ open, a derive that throws on its first computation during activation. After the object is live, a throwing derive
884
+ fails only its own member (`broken`, W1). The cause is tagged and decided by Chord from where it failed:
885
+
886
+ ```ts
887
+ cause: { kind: "transient"; error: ChordError } // the object's own effect failed (an open, a follow): backoff
888
+ | { kind: "broken"; error: ChordError } // its own code (factory, derive, hydration, migrate), a cycle, authority
889
+ | { kind: "waiting"; error: ChordError } // not its fault (slice 7a): no provider, no fitting version, a
890
+ // dependency failed; retryAt undefined, woken by an event
891
+ | { kind: "denied"; error: ChordError } // its admission, a dependency's or a route's refused the caller
892
+ // (slice 14): no backoff, woken by the decision
893
+ ```
894
+
895
+ Only an `open` may choose `broken` itself (`throw broken(error)`, e.g. invalid configuration). **Transient** causes
896
+ get a **backoff per identity** (1 s doubling to 60 s; a map holding no object, so a failed object is collected after
897
+ its last reference while its window runs; concurrent gets share one attempt; success resets). **Broken** ones are
898
+ retried only by a trigger. Triggers (for both): `ref.retry()`, a plugin reload (slice 7b, §21) and wake signals the factory
899
+ declares with `self.retryOn(...readables)` (slice 8; anywhere in the factory: the factory specifies, Chord installs
900
+ the watches before natives open, so a failed open still has them). Every trigger works like `ref.retry()`: the
901
+ backoff window is skipped, an attempt starts now, holders are told `loading`. `retryOn` sources must live independently of the
902
+ attempt (registry values); a reference's member is a type error. A facet cannot fail
903
+ after `load`: its setup only declares (a throwing setup leaves its plugin out of `load`, reported in `load`'s
904
+ `failed`; decision "Per plugin at startup and reload"; owner, 2026-10-26, 2026-10-30).
905
+
906
+ ### Admission (slice 14; `slice-14.md` §2; `host/admission.ts`)
907
+
908
+ A factory is synchronous: it cannot read data about its caller before it builds the caller's object. A remote
909
+ type's **admission** does.
910
+
911
+ ```ts
912
+ export const Transcript = remote("transcript", { version: 1, params: { session: str() },
913
+ hostAddress: ({ session }) => Session({ id: session }),
914
+ admission: obj({ mode: oneOf("read", "write") }), // the value's schema: not in the wire fingerprint
915
+ variants: { viewer: { … }, participant: { … } } });
916
+ host.serve(Transcript, (params, principal, admitted, self) =>
917
+ admitted.mode === "read" ? { variant: "viewer", members: … } : { variant: "participant", members: … },
918
+ { admit: ({ session }, principal, self) =>
919
+ self.derive([self.get(SessionAnswer, { session, person: principal.id }).mode], ([mode]) =>
920
+ mode === "none" ? deny("no access") : allow({ mode })) });
921
+ ```
922
+
923
+ - **Remote types only.** `admission` without `admit`, the reverse, or either on a `local` type is a declaration
924
+ error. `admit`'s `self` (`AdmitSelf`) has `get` (and `at(key)` on what it gets), `registry`, `derive` and
925
+ `liveQuery`, nothing else: an admission decides and owns nothing. The value is plain JSON, small and rarely
926
+ changing (a mode, a role); `deny`'s reason reaches the denied caller.
927
+ - **Admit.** An attempt of an admitted type runs `admit` before its factory, one microtask after its start, and
928
+ parks on its requests with the existing parking. The admission phase does not wait for the previous attempt's
929
+ teardown; only the factory does.
930
+ - **Decide.** With every request live and hydrated the decision is read: `deny` parks the attempt and the object
931
+ shows `failed { kind: "denied", error: forbidden(reason) }`; `allow(value)` runs the factory with `value`. A
932
+ value that is neither breaks the attempt.
933
+ - **Watch.** From its allow on the attempt follows the decision and its sources through the host's publication: a
934
+ change takes effect in the flush of the batch that changed it, also while the attempt opens its natives and on
935
+ an old attempt that drains for a reload.
936
+
937
+ | What happens | The attempt | Calls running on it | Holders |
938
+ | --- | --- | --- | --- |
939
+ | an equal value (canonical JSON) | nothing | | |
940
+ | a source is loading: its provider restarts, a link is down | **keeps its last decision** | go on | unchanged |
941
+ | another allowed value | sealed, a new attempt admits | rejected `unavailable` | `loading`, then `bound` |
942
+ | `deny` | sealed, the new attempt parks denied | rejected `forbidden/revoked` | `failed { denied }`, in that flush |
943
+ | a source failed or ended; reading the decision throws | sealed, the new attempt parks on the source | rejected `unavailable` | `failed { waiting }` |
944
+
945
+ No drain on a seal: callers are rejected at once and the sealed attempt publishes nothing more (a commit admitted
946
+ before the cut stays durable). Its teardown runs in the background, as any ending's; the next factory waits for
947
+ it. A call that crossed a seal on the wire waits at the gate and runs on the next attempt under its value.
948
+ **Two limits, accepted:** a source whose successor fails or parks after a reload seals every object that reads
949
+ it; a source whose new contract the readers' version does not fit (`contract_mismatch`) is failed, not loading,
950
+ so in a rollout, server first, every admitted object on a worker is sealed until that worker's step. **Admission
951
+ sources `accept` their previous version.**
952
+ - **A rebuild keeps the admission's requests** until a later attempt's admission bound its own: a source held only
953
+ by admissions never ends across a rebuild.
954
+ - **What a denial removes.** The denied object's references and replicas hold no value: a read throws `forbidden`,
955
+ a watch gets one `failed` call, `ref.variant` is `undefined`, a derive over a member fails as a member until the
956
+ next allow; over a link the consumer drops its replicas. **Data already delivered to application code is not
957
+ retracted** (a `WatchHandle`'s `value`, a rendered value, a method's answer): a UI hides what `ref.state` says is
958
+ denied.
959
+ - **A failed admitted object follows its admission** (code review 1): an object whose factory broke, or that
960
+ failed live, still shows a denial at once, `failed { denied }` in place of its failure, with no value kept and
961
+ its holders out of presence; its failed factory is not run for that. Another allowed value retries it, as a
962
+ wake signal does; a source that fails meanwhile changes nothing.
963
+ - **Dependents** of a denied object show `denied` and heal with it (the parked table above). `ref.retry()` on a
964
+ denied object only passes on to the admission's failed dependencies.
965
+ - **No jobs in an admitted object** (`self.job` there is a declaration error, in staging too). Work for a person
966
+ lives in a `local` store, carries the person in its arguments, and asks the person's access again on every run.
967
+ - **Linger:** a lingering object without holders whose decision changes ends. Presence: §19. Staging: §21.
968
+
969
+ ### The factory principle
970
+
971
+ ```ts
972
+ host.serve(NoteStore, ({ session }, self) => {
973
+ const notes = self.state(NoteDoc); // section 9
974
+ const index = self.state(Index);
975
+ const count = self.derive([index], ([i]) => i.ids.length); // section 12
976
+ const watcher = self.open(async (context) => watch(dir, { signal: context.abortSignal }), (w) => w.close()); // section 13
977
+ self.onLive(async (ctx) => { for (;;) { await sleep(HOUR, ctx); await cleanup(ctx); } }); // section 14
978
+ const imports = self.job(ImportJob, { run, finish }); // section 15
979
+ self.contribute(Http, { routes: { … } }); // section 17
980
+ const info = self.get(SessionInfo, {}); // start data, section 18
981
+ const catalog = self.get(Catalog, {}); // section 7
982
+ return { index, count, add: …, startImport: … };
983
+ });
984
+ ```
985
+
986
+ - Synchronous and declarative: no awaits, no side effects; async work happens in activation (opens), in calls, in
987
+ routines and jobs. What must be read about the caller before it runs is the admission's (above); `self.job` is
988
+ not declared in an admitted type's factory.
989
+ - **`self.events<T>()`** (decision "Events: fire-and-forget members") declares an event source of the attempt, in any
990
+ factory (local or remote, any params: events are never persisted); in staging it returns an inert handle. It belongs
991
+ to the attempt: an `emit` after the attempt's seal throws `released` (the seal fence). A restarting object's old
992
+ attempt emits until its seal (section 21).
993
+ - Handles stay valid for their attempt's life (owner, 2026-10-26: documents and the line belong to the object; each
994
+ attempt's handles carry its seal token and definition version); nothing is "read at use" or re-fetched.
995
+ - On a reload the factory runs again: in staging against a recording `self` (declarations only), then for real; every
996
+ live object restarts (same documents; its running calls and the calls they cause finish on the old attempt, the new
997
+ factory runs once that drained), objects of a removed type end and their holders wait (section 21).
998
+
999
+ ### Pattern: shared store, per-principal views
1000
+
1001
+ ```
1002
+ NoteStore {S1} local shared store: the stored notes, once
1003
+ ▲ self.get ▲
1004
+ Notes {S1} as owner Notes {S1} as read-only guest
1005
+ variant "editor" variant "reader": derives a filtered view
1006
+ ```
1007
+
1008
+ Heavy or shared parts (a Durable watch, a prompt watcher, a sandbox, a store) live once in a `local` shared store;
1009
+ per-principal `remote` views get it and expose what their principal may see. Authority is the view's; the store is
1010
+ trusted and acts for the host. Views of the same variant read one value from the store (a redaction is computed once,
1011
+ not per guest; section 12). Any plugin uses this pattern with the same primitives; base code is not special.
1012
+
1013
+ **Worker-wide native owners:** the facet cannot `self.get` a type it serves, so an owner of a per-session native (an
1014
+ inbox watcher, a sandbox) is a `local` object with empty params (host lifetime) that reads its session from the core's start
1015
+ data (`self.get(SessionInfo, {})`, read in its opener). Paths are derived by the plugin from generic start data (the
1016
+ data directory), never provided per plugin.
1017
+ Such an object cannot `self.get` a session-scoped object in its factory (the session is known only after activation):
1018
+ it gets one with `ctx.get` in a routine or method (R22). A `get` with params computed after activation is added only
1019
+ if a real case needs it.
1020
+
1021
+ **Natives that follow a relocation:** the native is a stable manager (`self.open` once); a routine on the session
1022
+ location switches its internal resource (the watched directory) and bumps a generation, so late events from the old
1023
+ location are dropped.
1024
+
1025
+ ---
1026
+
1027
+ ## 7. References
1028
+
1029
+ | Where | API | Released |
1030
+ | --- | --- | --- |
1031
+ | a factory | `self.get(Type, params)` | when the object ends |
1032
+ | a call | `await ctx.get(Type, params, { readyTimeout? })` | when the handler settles |
1033
+ | outside | `await host.get(Type, params, context, { readyTimeout? })` / `host.hold(Type, params, context, { readyTimeout? })` | `release()` |
1034
+
1035
+ - **`host.get`** (and `ctx.get`, `host.registry`) resolves with a reference once its object is live and **hydrated**
1036
+ (every state member of its variant has a value). It waits while the reference is `loading`, `failed { transient }`
1037
+ or `failed { waiting }`, up to its `readyTimeout` (default 60 s, the caller's choice), then rejects with the last
1038
+ cause; only `failed { broken }` and `failed { denied }` (slice 14) reject at once (owner, 2026-10-29, decision
1039
+ "Getters wait through `waiting`"). A
1040
+ getter that gives up releases its reference. **`host.hold`** returns a reference at once that follows its object
1041
+ until released (loading, live, failed and retried as its object is, loading again while its link is down) and never
1042
+ rejects; only invalid params throw (checked at once: design audit 7, 2026-10-27), and a use before `load` (`not_ready`,
1043
+ §3). A type not served where it goes is `failed { waiting }` (§3; slice 7a), reported `unbound_long` after 5 s. Its `variant` is `undefined` until its first binding (slice 3b). A UI holds and shows
1044
+ `ref.state`; code that needs the object now gets it, with the patience it passes. There is no `state: false` option
1045
+ (C8) and no `optional` flag.
1046
+ - **Narrowing by variant:** `ref.variant` is the discriminant (C15: no `inVariant`/`expectVariant`); `RefIn<C, V>`
1047
+ narrows to some variants (strict unions, never weakened). A UI reads a held reference's variant through its
1048
+ binding (`useVariant`, `TuiScope.variant`, §23), which follows the reference's state: the variant is `undefined`
1049
+ until it binds, changes with an admission's other allowed value, and stays the last one while it loads.
1050
+ - **References are the only indirection** (owner, 2026-10-29; supersedes 6a's member source per object and 7b's
1051
+ hand-over): a consumer's watches and derives over `ref.member` attach through the reference's member, which passes
1052
+ the subscription straight through to the object's own document or derive (no extra hop, no copy: the commit's value
1053
+ and ops by reference). When what the reference points at changes (a new object instance after a factory re-run:
1054
+ reload, retry, restart; a new object after its type was removed and served again; another variant), the reference
1055
+ moves its subscriptions to the new one and sends one frame, a diff from the last value (consumers' derives recompute,
1056
+ a failed one heals; a member the new variant lacks fails `invalid/member`). While it points at nothing, its members
1057
+ keep their last values (a pointer, no copy): while loading (a restart's successor not live yet, a retry) its watches
1058
+ get no call (`ref.state` says `loading`); while failed (a live failure, its version refused, its type
1059
+ removed, a failed dependency) they get one `failed` call with the cause's error and stay open (decision "Failures are
1060
+ watch calls"); a reference that never had a value reads `not_ready` while loading and its failure's error while failed, and its
1061
+ watches wait for its first values. A member the new variant lacks is not a failed reference: it fails `invalid/member`
1062
+ (reads throw it, watches get one `failed` call) until a later variant brings it back. Keyed watches and pins
1063
+ re-pin on each new instance the same way (a key keeps its last value until the new instance has loaded it); a
1064
+ dependent's factory pin is still loaded before the dependent goes live. Once hydrated, a reference has last values for every state member of its bound variant, read or not: when it
1065
+ detaches it takes them at its version from the outgoing instance (through that instance's mapping for an older
1066
+ version), keeping no node of it. After a `failed` call, the next good value arrives as `[["r", value]]` even when
1067
+ unchanged; a watch opened while failed starts at the last value and gets the failure once. No source, mapping,
1068
+ document handle or pin of an instance outlives it through a reference: a detached reference keeps only plain last
1069
+ values and its failure; releasing it drops them and its bindings; stopping a keyed watch drops its pin. A host-keyed member of a
1070
+ reference (§5) takes addresses of its kind, checked and turned into canonical keys before its reads and pins. Derives over a failed reference member compute on its last value (a contribution built on it stays); only the
1071
+ member's own watches get the `failed` call, and `ref.state` shows the failure (owner, 2026-10-29). A re-exposed member is
1072
+ the re-exposing object's reference member, followed the same way. Over a link the same rule: the replica keeps its
1073
+ last values readable while its hold is failed. Nothing outlives its object instance and nothing is handed between
1074
+ objects. A reference joining a shared remote object (below) does not acquire another reference's last value: "seen"
1075
+ means a value this reference received while live. Joining an object that is not live (loading, failed), it has
1076
+ seen no member; joining a live one, it has not seen the members failed or missing from the bound variant. Until a
1077
+ value arrives for such a member after the join (read or not, while its watches exist or not), the member shows no
1078
+ last value (a watch on it rejects with its error, as on a fresh failed snapshot; holding and vanishing keep none);
1079
+ from then on its own last-value rules apply, across later failures, rebinds and a private retry.
1080
+ - **References across a reload** (slice 7b §6): a reference is never ended by a code change. Its object restarted: it
1081
+ follows the old instance while that serves its version, then the new instance (above; a hold over a link gets a fresh `bound`, §22). Its version no longer accepted, or a member of it refused (`contract_mismatch`): it leaves the object and waits
1082
+ unbound (`failed { waiting }`) with its last values; the object and its other holders stay. Its type removed: it
1083
+ waits unbound `not_served` with its last values; a publication that serves the name again binds it to the next
1084
+ object (a new object: its in-memory documents start over from `initial()`, persisted ones load again). On a removal
1085
+ the references take their last values at the seal: a commit admitted at that moment is stored and loaded by the next
1086
+ object, but not in the last values they show while they wait (accepted: deferring it would need new state on the
1087
+ waiting path, owner, 2026-10-29) (one frame, watches and derives heal, keyed pins re-pin, parked calls flush or reject, presence lists it
1088
+ again). A reference of an older version a provider accepts reads its state members through the object instance's
1089
+ shared mapping for its version (and keyed members per key), and its calls are mapped forwards and their results
1090
+ back, or run the provider's replacement of a removed method (`checkArgs`). A reference knows its version from the
1091
+ contract token it was made with; one made by outside code keeps the token its caller passed (Chord reloads no caller
1092
+ code).
1093
+ - **Members:** each state member of a reference is a watchable of the provider's member (a replica over a link);
1094
+ watches taken through a reference belong to it and end when it is released. Methods are functions (`ref.add(args,
1095
+ ctx)`, `ref.bump(ctx)`). Event members are `EventMember<T>`s (decision "Events: fire-and-forget members"):
1096
+ `ref.paddle.on(listener, ctx)` installs a subscription at once, bound or not, and resolves (it rejects `released` for
1097
+ a released reference and the context's abort reason for an aborted one); it lives until `stop()`, the context's abort
1098
+ or the reference's release. It receives events while the reference is bound to an instance whose variant has the
1099
+ member and shows it live: none while `loading` or failed, none while bound to a variant without it (no failure call:
1100
+ an event has no value to fail), and again when a later binding has it. When the reference moves to a new instance
1101
+ (above) its subscriptions move with it, from that binding's counter value (section 11): nothing missed is replayed.
1102
+ Events need no hydration (an event-only contract binds live). An event member is not a `Watchable`: no derive or
1103
+ `on` source, no state member.
1104
+ - **Remote references of one host share a hold** (decision "References share one wire hold", owner, 2026-11-09 and
1105
+ 2026-11-12): an eligible reference to a remote object this host holds for the same type, version, fingerprint,
1106
+ params, address (the one its placement computed) and caller (its principal's JSON as the wire carries it, and its
1107
+ incarnation) joins that hold's remote object, with no message: live at once if it is live (values from its
1108
+ replicas), else loading or failed as it is. Each keeps its own release, state, watches, subscriptions, parked calls
1109
+ and calls; the hold ends with the last reference (no linger, D8: a reference after it holds anew, also in the same
1110
+ turn). Releasing one of several cancels its own calls: its queued ones leave unsent, its sent ones are aborted
1111
+ (newest first, so a relay drops a later call still waiting upstream before an earlier abort frees a slot for it); the
1112
+ provider sees `aborted`, the caller `released`. `self.get` references (their holds carry the dependent's chain, Q5)
1113
+ and relayed holds (R1) stay separate; a reference on a suspended route address holds on its own; one finding the
1114
+ key's object failed `waiting` over a link (refused there: a new hold is a new request, and a relay's failed route
1115
+ resolves again for it) holds anew; a broken remote object leaves the index for good (also after it recovers); a
1116
+ private retry after `too_large/part` (below) is never indexed. Within one commit, the watch callbacks of several
1117
+ references sharing a replica run in subscription order, not hold order. No hold survives its last reference.
1118
+ - **`ref.state`** is a `NativeWatchable` (slice 3b) of a tagged value; watches get each new state:
1119
+
1120
+ ```ts
1121
+ | { kind: "loading" } | { kind: "live" }
1122
+ | { kind: "failed"; cause: FailureCause; retryAt: number | undefined } // retryAt: a transient cause's backoff;
1123
+ // undefined for broken and waiting
1124
+ | { kind: "ended"; error: ChordError } // released by its holder, or its object ended
1125
+ ```
1126
+
1127
+ | Situation | Calls | Values |
1128
+ | --- | --- | --- |
1129
+ | link drop | park until reconnect | readable (`loading`) |
1130
+ | object loading or restarting | park until live | readable (`loading`) |
1131
+ | unbound (not served, another version) or parked on a failed dependency | reject at once with the cause | `failed { waiting }` (slice 7a) |
1132
+ | object `failed` | reject at once with the cause | `failed` with cause and `retryAt` |
1133
+ | denied (slice 14) | reject at once with `forbidden` | none: reference members and replicas hold no value; what application code already has stays with it |
1134
+
1135
+ - A failed reference stays alive: while held, Chord retries a `transient` failure per the backoff and wakes a
1136
+ `waiting` one at the event it waits for; `ref.retry()` tries at once (a Retry button; over a link the `retry
1137
+ { hold, hops }` message, which also re-runs a refused hold's start: the host address, binding; design audit 2026-10-27;
1138
+ on a parked object it passes on to the failed dependencies, §6); success goes `loading`, then `live`. A retry of a
1139
+ shared hold the provider refused restarts it for every reference sharing it; after `too_large/part` the retrying
1140
+ reference alone moves to a new private remote object, placed anew, keeping its own watches, subscriptions, calls and
1141
+ last values (the others stay failed until they retry). A provider
1142
+ tells a pending hold's consumer each failure (`failed`, with the rest of its backoff window for a transient one),
1143
+ each new cause of an object parked on a failed dependency, and the next attempt (`loading`).
1144
+ - **Parked calls** (slice 3b): calls made while the reference is loading are queued in order, each waiting at most the
1145
+ reference's `readyTimeout` from the moment it was made (never renewed), then fail `unavailable/park_timeout`; they
1146
+ are sent in order when it goes live (a new call never overtakes them) and rejected with the cause when it fails.
1147
+ Otherwise a call ends only through its caller's signal; there is no per-call deadline.
1148
+ - Calls already sent when a link drops fail `unavailable` and are not resent; calls running on an instance that ends
1149
+ fail and are not resent. **Releasing a reference rejects the calls made through it** (`released`), locally and over
1150
+ links (slice 3a); releasing one of several references sharing a hold aborts its sent calls (`abort`, the provider
1151
+ sees `aborted`) and drops its queued ones, the last release sends `release` as before. A consumer receiving `gone(h)`
1152
+ rejects its own pending calls on `h` (Q1).
1153
+ - References survive link drops: one owner of a host's remote references holds them again on every new link of their
1154
+ path; a re-hold may bind another variant (slice 3b).
1155
+ - **Consumers** handle a failed call as they handle a disconnect (error shown, user retries); Chat's own submission
1156
+ `requestId` stays an app concern.
1157
+
1158
+ - **Optional dependencies** are registries owned by the dependent, not optional references: ports contributes its
1159
+ forwards to `radius.forwards`; without ports the table is empty and radius works.
1160
+
1161
+ - **Authority** is decided before the factory by the type's admission where it depends on data (§6, slice 14), in
1162
+ the factory where the principal alone decides, in a method where it depends on the call's arguments, and by a
1163
+ route's `authorize` and admission before a host is reached (§3). An object for an address that carries authority
1164
+ (`LoginFlow { id }`) may exist; what a caller can see and do is decided by its view.
1165
+
1166
+ ---
1167
+
1168
+ ## 8. `ctx`
1169
+
1170
+ Every handler gets a `ctx` (a `Context`): `telemetry` (the current span, section 29), `abortSignal` (the caller
1171
+ cancelled or the object ended; there is no per-call deadline), `principal` (the caller as its link stamped it; on a
1172
+ local object's handler the host's principal, none on a client), `incarnation` (the calling host's, section 4), and
1173
+ `get(Type, params, { readyTimeout? })` (references as the caller sees them, released when the handler settles; a
1174
+ `get` after that throws `released`), and `trace(name, attributes, fn)`: `fn` in a child span of `ctx.telemetry` with a
1175
+ child `ctx` (the same principal, incarnation, signal and `get`, its references the handler's), so calls inside are
1176
+ parented under it; a throw marks the span failed (`trace_failed`) and is rethrown; without an adapter that records,
1177
+ `fn` gets `ctx` itself (slice 9; round-3 cut C11 kept, as this section already stated it); in a job's `run` also `jobId`
1178
+ and `state` (slice 5). Pass `ctx` to everything you wait
1179
+ on. Code outside objects gets a `ctx` from `host.root` (slice 8). Durable's `Context` is the same module
1180
+ (`../context`); bridging is explicit. No code versions, no request ids. A method's `ctx` is also a node of its **call
1181
+ chain** (the attempt the method runs on, then the chain of the call that made it): during a reload it tells old work
1182
+ from new (section 21), so a root opened inside a method takes the method's `ctx` (`withoutAbortSignal(ctx)`), never a
1183
+ fresh context.
1184
+
1185
+ **Await what you start in a root or a handler** (decision "Mistakes that wait are reported at once" (e), owner,
1186
+ 2026-11-03; footgun 10 of the p2 port). What is started with a context ends with it: a root's scope seals when `fn`
1187
+ settles, a handler's context aborts when its caller cancels or its object ends, an attempt's at its seal. A document
1188
+ change or transaction (`handle.change`, `retire`, `self.tx`, `job.start`) that did not commit because its context
1189
+ ended first (it waited on its object's line, or `fn` returned before it committed) rejects with that context's abort
1190
+ reason, and is also reported through `onError` as `transaction_cancelled { object, error }` (`error` the abort
1191
+ reason, naming the scope that ended): an empty `catch` cannot hide a change that never happened.
1192
+ `host.root(async (ctx) => { void handle.change(fn, ctx).catch(() => {}); }, context)` loses the change and reports it;
1193
+ `await handle.change(fn, ctx)` inside `fn` commits it. Only the cancelled path pays (the check runs where the
1194
+ transaction failed); Chord's own transactions run under contexts that never abort.
1195
+
1196
+ **Contexts are required** (owner, 2026-10-22): every function that takes a context requires it, as the parameter after
1197
+ the required ones (context last); optional only on error-reporting paths. A getter that cannot take one (a lazy derive
1198
+ read) uses its owner's.
1199
+
1200
+ **Call-scoped natives** (a native that lives exactly as long as one call: a temporary SSH session for a directory
1201
+ listing, a file handle for a download) are opened and closed inside the method with `try/finally`; there is no
1202
+ `ctx.open`:
1203
+
1204
+ ```ts
1205
+ list: async ({ path }, ctx) => {
1206
+ const session = await ssh.open(config, ctx.abortSignal);
1207
+ try { return await session.readDir(path, ctx.abortSignal); }
1208
+ finally { session.close(); }
1209
+ },
1210
+ ```
1211
+
1212
+ ---
1213
+
1214
+ ## 9. Documents
1215
+
1216
+ ### Definition and handles
1217
+
1218
+ ```ts
1219
+ const Settings = defineState("settings", {
1220
+ schema: SettingsSchema,
1221
+ version: 1,
1222
+ initial: () => ({ theme: "dark" }),
1223
+ persist: true, // default: in memory
1224
+ checkpointWhen: () => true, // required for persisted documents; small: a base per write
1225
+ });
1226
+ const Draft = defineState("draft", {
1227
+ schema: DraftSchema,
1228
+ version: 2,
1229
+ migrate: (old, from) => ({ body: old.text }), // pure
1230
+ initial: () => ({ body: "" }),
1231
+ keyed: true, // many per object
1232
+ persist: true,
1233
+ checkpointWhen: (value, ops, info) => info.deltasSinceBase > 50,
1234
+ });
1235
+
1236
+ host.serve(DraftStore, (_, self) => { // local, empty params: may persist (P3)
1237
+ const settings = self.state(Settings); // THE settings document
1238
+ const drafts = self.state(Draft); // all Draft documents of this object
1239
+ return {
1240
+ settings, // a singleton handle is an exposable Watchable
1241
+ get: ({ conversation }, ctx) => drafts.get(conversation, ctx),
1242
+ save: ({ conversation, body }, ctx) =>
1243
+ self.tx(async (tx) => {
1244
+ const d = await tx.draft(drafts, conversation);
1245
+ d.body = body;
1246
+ return d.body.length;
1247
+ }, ctx),
1248
+ drop: ({ conversation }, ctx) => self.tx(async (tx) => tx.retire(drafts, conversation), ctx),
1249
+ };
1250
+ });
1251
+ ```
1252
+
1253
+ - **Ownership:** a document belongs to exactly one object identity, and so does its line (owner, 2026-10-26: across the
1254
+ object's attempts, retries, failures and native restarts; an attempt keeps only its natives, routines, derives and
1255
+ seal token) (persisted ones across restarts; in-memory ones for
1256
+ the object's life, across reloads and native restarts). Facets have no documents (owner, 2026-10-26: C16).
1257
+ Others see it only through exposed members. References to other objects are stored as data (addresses).
1258
+ - **Singleton** (no `keyed`): loaded at activation, kept in memory while the object lives; `handle.value` is
1259
+ synchronous; the handle is an exposable `Watchable`.
1260
+ - **Keyed:** addressed by a short key local to the object, loaded on demand; `await handle.get(key, ctx)` reads (creates
1261
+ nothing); `for await (const key of handle.keys(ctx))` pages keys (both take a context, owner, 2026-10-26) (indexed per owner and definition, also in memory). No
1262
+ live key list: keyed documents are read by key. A collection shown live is a table with a named query, read as
1263
+ a list (section 11; slice 14); a small one may still be a singleton (an object holding a list or map). Methods
1264
+ returning pages stay for jobs and scripts; a screen does not chain them.
1265
+ - **Host-keyed documents** (decision "Documents and table rows can belong to a host", 2026-11-09; spec
1266
+ `host-keyed/spec.md`): `keyed: Session` keys documents by addresses of a host kind: `KeyedHandle<T, Address<K>>`,
1267
+ `tx.draft(meta, Session({ id }))`; `keys()` yields addresses. Only addresses of the kind are taken (a string, the
1268
+ empty one included, is `invalid/args`). **The canonical key** is an address's key under the `str()` text rules (a
1269
+ lone surrogate replaced, NUL refused); for an address a plugin hands in (a key, a cell, a member key) it is computed
1270
+ from the params, never taken from its `.key`, while the host data calls take `address.key`. It is the document's
1271
+ key, the record's `host`, a `host(...)` cell and a host data selection alike. **The discriminator:** a persisted host-keyed document's record has `host = key`, every other record
1272
+ `host` NULL; a find or load whose record does not fit the definition's keys fails the object `broken` (no implicit
1273
+ conversion; converting is an explicit store migration). Pins (`at(address)`), watches and retirements work by the
1274
+ canonical key as for string keys; migration on access is unchanged. **Store maintenance** (a host data import or
1275
+ delete, §10) is the one change of an object's documents outside its transactions: it holds the object's line,
1276
+ reads what the object holds of the address inside its commit step and adopts it in one batch (§10).
1277
+ - **Values are immutable by convention** (Chord Delta's rule, as in Durable): `handle.value` and published values
1278
+ are shared, never mutated by their readers, and never copied or frozen; a draft belongs only to its transaction.
1279
+
1280
+ ### Writes and transactions
1281
+
1282
+ - **Only `tx.draft`** (as Durable's `tx.doc`): `await tx.draft(handle, key?)` inside `self.tx(fn, ctx)`
1283
+ returns a draft of the current document, or a draft over `initial()` if it is absent. Reading is drafting (Delta's
1284
+ overlay: no copy). An unchanged draft (empty ops) commits nothing, so an absent document is never stored by being
1285
+ read. `tx.retire(handle, key?)` removes a document. `keyed` makes the key mandatory at the type level. There is no
1286
+ `tx.get` for documents (tables have one, section 10).
1287
+ - Drafts record ops (assignment, `push`, `Object.assign`); the same document returns the same draft within one
1288
+ transaction. **Drafts are revoked when the transaction settles (R12, as in Durable):** a transaction writes and
1289
+ returns at most plain values (an id, a count), never anything taken from a draft. To return data, read after the
1290
+ commit from the document (`handle.value`, `handle.get`), which then holds the committed revision; a later commit
1291
+ may slip in between, and the reader gets that newer value.
1292
+ - **No existence check inside a transaction (R13, as in Durable):** `tx.retire` of an absent document is a no-op (it
1293
+ never creates); `tx.draft(handle, key)` creates a missing document when the draft changes;
1294
+ whether a keyed document exists is read outside the transaction (`handle.get(key, ctx)` gives `undefined` for an absent
1295
+ one). **A singleton always has a value (Q11):** `handle.value` is the written value or `initial()`, never
1296
+ `undefined`, so an exposed singleton is typed `T`; singleton existence has no API (unlike Durable's `snapshot()`).
1297
+
1298
+ Patterns:
1299
+
1300
+ ```ts
1301
+ // Return data: write in the transaction, read after the commit.
1302
+ await self.tx(async (tx) => { (await tx.draft(notes)).items.push(note); }, ctx);
1303
+ return notes.value.items; // the committed revision (or a newer one)
1304
+
1305
+ // Remove if present: retire is a no-op for an absent document.
1306
+ await self.tx((tx) => tx.retire(drafts, conversation), ctx);
1307
+
1308
+ // Create if missing: the draft creates it (only if it changes).
1309
+ await self.tx(async (tx) => {
1310
+ (await tx.draft(drafts, conversation)).text = text;
1311
+ }, ctx);
1312
+
1313
+ // Branch on existence (keyed documents): read first, outside the transaction.
1314
+ if ((await drafts.get(conversation, ctx)) === undefined) { … }
1315
+ ```
1316
+ - Document roots are `JsonObject` (as in Durable; lists live in a field); documents hold JSON only (bytes are a value
1317
+ and wire type). A singleton that does not exist yet reads `initial()` through its handle; retiring resets it to
1318
+ `initial()`. Handles may be used only in transactions of their own object.
1319
+ - **Commit sequence** (Durable's): wait for the object's line (per object, never across objects; reads outside a
1320
+ transaction do not take it exclusively); run the callback; an error or an abort before the storage write discards
1321
+ everything; prepare every draft (Delta copies and checks only the placed values); write persisted documents in one
1322
+ storage batch through the store's commit step, `await store.commit(writes, adopt, ctx)` without the caller's abort
1323
+ signal (deltas, or a base when `checkpointWhen` says so; the line held until the step returned, as Durable's
1324
+ `#runCommit`, owner, 2026-10-26); adopt by pointer swap and mark dependents in the step, persisted and in-memory
1325
+ documents and staged changes in one `host.batch.commit` (errors as Durable's Storage, owner, 2026-10-27: a step that
1326
+ fails before `COMMIT` rolls back and rejects that commit only, nothing adopted, the store goes on; plugin mistakes are
1327
+ refused when a write is staged; a seal-fenced commit is rejected `released` before `BEGIN`); then the owner's synchronous flush recomputes dirty derives, sends one message
1328
+ per link and queues watch callbacks (W1); drafts then throw if touched. In-memory-only commits take no store seq and never
1329
+ enter the commit queue (W12). No
1330
+ revalidation of the whole document, no copy, no freeze.
1331
+ - **Nothing leaves a transaction before it commits (S2):** ids and data reach other owners only after the commit;
1332
+ reference what is committed (a reference to a later commit dangles on every replica that stops in between).
1333
+ - **Durable's rule:** inside the callback only `await tx.*`: no other objects, models, processes or network, no second
1334
+ `self.tx`, no reads past `tx` (otherwise a hang, not an error). Fetch first; decide and write inside.
1335
+ - **An emit is no transaction work** (decision "Events: fire-and-forget members"): `source.emit` neither waits for the
1336
+ object's line nor joins a commit; an emit inside a `self.tx` callback is outside the rule above (and delivered even if
1337
+ the transaction fails), unchecked. The pattern: `await self.tx(...); source.emit(...)`.
1338
+ - A transaction covers only its own object's documents and tables: one line, no transactions across owners (facet
1339
+ documents were removed, owner, 2026-10-26; shared plugin state is a `local` store object's, reached by methods).
1340
+ - **Shorthands:** `handle.change(fn, ctx)` (keyed: `handle.change(key, fn, ctx)`) (one document, loaded before the synchronous `fn`),
1341
+ `handle.retire(ctx)` (keyed: `handle.retire(key, ctx)`); several steps atomically: `self.tx`.
1342
+
1343
+ ### Versions
1344
+
1345
+ - A shape or meaning change raises `version` with a pure `migrate(old, from)`. A document migrates on access by the
1346
+ new definition (in memory too); the migrated base is persisted with the next commit.
1347
+ - **Schema fingerprints instead of value validation:** `defineState` computes the fingerprint of its structural schema
1348
+ once (descriptions and titles ignored) and keeps it on the token; every document record stores the fingerprint it was
1349
+ written with (at creation, and with the new base after a `migrate`). On access Chord compares the token's fingerprint
1350
+ with the record's: the same version with a different fingerprint fails the object `broken` ("schema changed without
1351
+ a version bump"). Always on, O(1). Every structural schema change needs a version bump (an additive change gets a
1352
+ trivial `migrate`). Values are not walked against the schema in production, with two exceptions (R8):
1353
+ - the result of `migrate` is validated against the new schema once, when it is produced (per document per version
1354
+ change, off the commit path); a failure refuses the access, keeps the old data and fails the object (slice 6);
1355
+ - `initial()` is checked once per definition, at its first value (D3, owner, 2026-10-24: `initial()` takes no input,
1356
+ so a wrong shape is wrong at its first call; checking every call would cost one validation per created document
1357
+ and catch nothing more). A failing singleton `initial()` fails its object's activation (`broken`); a failing
1358
+ keyed one fails only the transaction that drafts the absent document, naming the definition (slice 1).
1359
+ - Old code whose definition is older than the document throws on access. Without `migrate` the access is refused and
1360
+ the data kept. A changed meaning without a bump cannot be detected.
1361
+ - Singleton documents migrate during activation and after reload (hydration counts as access). A hydration or
1362
+ migration failure keeps stored data and fails the whole owning object, not only the exposed member. Keyed
1363
+ documents migrate on their next access; a migration failure there also fails their owner. A migrated base is written
1364
+ back by the next commit that changes the document (owner, 2026-10-27); until then a load migrates again (once per
1365
+ object, since documents stay on the object).
1366
+
1367
+ ### Lifetime, persistence
1368
+
1369
+ - **No tags (owner, 2026-10-21):** deleting a session deletes its store and directory. Instance data on the server
1370
+ that refers to a session and must travel with it (export, import, delete) is host-keyed (decision "Documents and
1371
+ table rows can belong to a host", 2026-11-09): documents keyed by `Session` or rows with a `host(Session)` column;
1372
+ the store finds them by address (§10). Data that only refers to a session is cleaned up by its owner
1373
+ (`deleteWhere`, reconciling from the catalog).
1374
+ - **In-memory documents are instance state (P2, owner, 2026-10-21):** attached to the live object, with no storage, no
1375
+ address, no seq and never in the outbox; their commit is prepare and adopt (inside the store's commit step when the
1376
+ transaction also writes persisted data).
1377
+ - **Lifetime:** in-memory documents end with their object (last reference released, linger expired, a params change on
1378
+ reload) and survive reloads and native restarts of a live object; long-lived objects creating many keyed in-memory documents retire
1379
+ them themselves. Persisted documents stay until retired.
1380
+ - **Persisted data only in `local` objects with empty params (P3, owner, 2026-10-21):** persisted documents and tables
1381
+ live in `local` objects with empty params (one per host and type); their address is (object type, name, key), never a
1382
+ host instance such as the session id (W7; no host kind either since slice 6b R2: a store belongs to one host),
1383
+ so a params change never orphans data. Per-entity data is keyed documents or table rows there, with an app-chosen
1384
+ key; objects with params keep only in-memory state and read persisted data by key. Renaming a persisted store's type or
1385
+ definition, or changing how keys are formed, is an explicit one-off migration in the store.
1386
+ Why not elsewhere: a `remote` object's identity contains the principal key (provenance, grant revision), so its
1387
+ persisted documents would scatter across access paths and be orphaned after a reconnect; a shared storage key
1388
+ (`storeKey`) would put two objects with two lines on one document, so it does not exist; params would orphan data
1389
+ on a params change. Enforced at the type level (`self.state(…, persist)` and `self.table` only in factories of
1390
+ `local` types with empty params) and as a declaration error at runtime ("persist needs a stable identity: put the
1391
+ documents into a local shared store").
1392
+ - **Durable plugin state:** whatever must survive a host teardown (crash, restart, a DO eviction) is a persisted
1393
+ document; everything else is rebuilt on activation (in-memory documents, natives, derives, routines, presence,
1394
+ references re-held by clients; job runs end `lost` unless their records persist).
1395
+
1396
+ ### Rules across owners
1397
+
1398
+ - **No plugin reads or writes another plugin's documents** (Chord or Durable). Data crosses plugins only through
1399
+ state and methods. Data core enforces lives in a format core owns and is handed to core through its API when the data is
1400
+ created (`createConversation` with `init`), never written into core's documents directly.
1401
+ - **Column sets (slice 14):** a plugin's contract may declare a column set of one of its tables (section 10);
1402
+ another plugin's condition or join may read those columns, in queries only. Nobody writes through one.
1403
+ - **Invariants across owners** are enforced by the owner of the dependent data, which reconciles from the other
1404
+ owner's state with an idempotent routine. No cross-owner transactions, no "notify the other owner" calls that can
1405
+ be lost:
1406
+
1407
+ ```ts
1408
+ // ports' ForwardStore: "a forward of an archived session is closed"
1409
+ const catalog = self.get(Catalog, {});
1410
+ self.on(catalog.sessions, async ({ value: sessions }, ctx) => {
1411
+ for (const f of forwards.value.list) if (sessions[f.session]?.archived) await close(f.id, ctx); // idempotent
1412
+ });
1413
+ ```
1414
+
1415
+ After a crash the routine runs again with the current value; sessions does not know ports exists.
1416
+
1417
+ ---
1418
+
1419
+ ## 10. Store and storage
1420
+
1421
+ > **Superseded (owner, 2026-10-21):** persisted data lives in one transactional store per session, designed in
1422
+ > `packages/chord/docs/store/book.md` and decided in the log ("The store", S1-S17, W1-W14, P2-P4, "Flat columns",
1423
+ > "Query runner", "Index definitions are recorded", "Blobs and derived data"). In short: backends SQLite (Node, Durable
1424
+ > Objects, sqlite-wasm in the browser; tests on SQLite `:memory:`, no hand-written memory backend, owner, 2026-10-27); real tables owned by objects with empty params (P3), flat
1425
+ > columns (scalars, every `str()` as plain UTF-8 `TEXT` in code point order with lone surrogates replaced and NUL refused (owner, 2026-10-26, superseding W8), `json(...)` with its own version and on-access migration), a small
1426
+ > query language, writes `put`/`update`/`delete`/`updateWhere`/`deleteWhere`; one documents engine for Durable
1427
+ > (`StoreStorage`) and Chord; one commit queue per store that writes, adopts and marks (S1, W1), with `Storage.commit(
1428
+ > writes, adopt, context)` in Durable; an outbox of ordered operations in the same transaction (no compaction at first);
1429
+ > eager migrations by scan with row `v` for eager steps only. In-memory documents are instance state with no storage
1430
+ > (P2). The text below describes the per-object lines, Delta trackers and commit sequence, which stay; its storage
1431
+ > interface is replaced by the store.
1432
+
1433
+ - **What stays from Durable's store design** (`durable/src/session/transaction.ts`, `session.ts`): one Delta tracker
1434
+ per document held by its object, prepare and adopt by pointer swap, ops per commit, lines per object, migrate on
1435
+ access, `checkpointWhen` (required for persisted documents, R14), retire, and the documents engine's invariants (create before change, no
1436
+ change after retire, one live incarnation per address, `deltasSinceBase`).
1437
+ - **Where persisted documents live:** rows of the store's documents engine (S13) with address `(namespace: "chord",
1438
+ owner: "<object type>", kind: <definition>, key)` (key `""` for a singleton), never a host instance (W7); ids from the store's
1439
+ counter (S10). Chord ships no storage of its own: no `DocumentStorage` interface, no Chord SQLite or memory document
1440
+ storage and no Chord storage conformance suite (the store's conformance suite covers the engine); the frozen `next/`
1441
+ storages are not ported. The store is passed to the session's host by base code (owner, 2026-10-26):
1442
+
1443
+ ```ts
1444
+ const store = await openStore(sqliteBackend(await openNodeSqliteDatabase(join(dir, "session.sqlite"))), ctx);
1445
+ const worker = createHost<P>({ address: Session({ id }), principal, store, onError }); // tests: SQLite :memory:
1446
+ …
1447
+ await worker.close(ctx);
1448
+ await store.close(ctx); // the app owns the store; in 6b the Durable Session shares it
1449
+ ```
1450
+
1451
+ `openStore` runs the store's own migrations, checks the file is UTF-8 and reads `lastSeq`, the definitions and the
1452
+ id counters once; `sqliteBackend(db)` takes any `SqliteDatabase` (Node, Durable Objects, sqlite-wasm later); the
1453
+ backend interface is internal; `importStore(backend, archive, ctx)` takes the same backends. No `openNodeStore`.
1454
+ - **Loading at activation (owner, 2026-10-26):** persisted singletons load right after the factory, sequentially,
1455
+ all singletons of the object with plain reads (owner, 2026-10-27: the object holds its line, so no read transaction
1456
+ is needed), once per object, before its references are bound: find, load (base plus
1457
+ deltas), fingerprint check, `migrate` with its result validated once (R8). A storage error is `storage_failed`; a
1458
+ fingerprint mismatch, a throwing `migrate` or an invalid migration result fails the object `broken`.
1459
+ - **Statements per commit (owner, 2026-10-26):** the store keeps `lastSeq` (the seq of its last commit) in memory (read at open,
1460
+ persisted with each commit, S9) and folds the documents engine's checks into the writes (unique keys, a partial
1461
+ unique index on the live address, conditional `UPDATE … WHERE id = ? AND version = ?`): a delta commit is about three
1462
+ statements (revision, the record's counted conditional `UPDATE`, `lastSeq`), plus one `INSERT` with an outbox. Durable's ids in the store (slice 6b D3): one id allocator per store
1463
+ for every id (Durable's `mintId` and Chord's document ids; it starts at 2, saturates at `Number.MAX_SAFE_INTEGER`, each
1464
+ commit persists it, outbox commits and archives carry it as `nextId`); `StoreStorage`'s `record_ids` table only checks
1465
+ an id's record type. Every table and document namespace in the store is claimed once (slice 6b "owner names and
1466
+ claims"): a table by its SQL name `"<owner>:<table>"`, documents by `(owner, namespace)`; an object claims under its
1467
+ type, `StoreStorage.open(store, owner, ctx)` under `owner` (two harnesses on one store under two names are fine).
1468
+ - **Tables in a transaction (owner, 2026-10-26):** the table handle first, keys as objects with exactly the key
1469
+ columns, reads async, writes synchronous and buffered like a draft's ops (checked and staged, no I/O; written in the
1470
+ commit step or dropped on failure); no write shorthands on the handle:
1471
+
1472
+ ```ts
1473
+ self.tx(async (tx) => {
1474
+ const old = await tx.get(edits, { id }); // overlays own put/update/delete (W10 after bulk)
1475
+ const { items, next } = await tx.page(edits, q, 50, { after }); // committed rows, stable for the transaction
1476
+ tx.put(edits, row);
1477
+ tx.update(edits, { id }, { at: now });
1478
+ tx.delete(edits, { id });
1479
+ tx.updateWhere(edits, (e) => prefix(e.path, from), (e) => ({ path: replacePrefix(e.path, from, to) }));
1480
+ tx.deleteWhere(edits, (e) => lt(e.at, cutoff));
1481
+ }, ctx);
1482
+ await edits.get({ id }, ctx); // outside: committed state, ctx last
1483
+ ```
1484
+ - **Reads in the commit step (owner, 2026-11-03; slice 14; section 11):** the store keeps which reads read which
1485
+ table (`store.reads`: the owner's `self.query` windows, named queries read with `self.liveQuery`, counts),
1486
+ whoever owns them. A transaction that wrote tables stages one more step write after its own. Inside the commit
1487
+ step it takes the reads over those tables from the index as it is then (a read opened while the commit waited in
1488
+ the queue is refreshed by it), runs the skip test for each, and runs the others again on the step's backend
1489
+ transaction (one `SELECT` each, `chord.query.runs`); it writes nothing and records nothing in the outbox; the rows
1490
+ are adopted with the documents in the commit's batch. A refused step adopts nothing.
1491
+ - **The skip test (slice 14 §3.3):** a skip proves the result unchanged by the row before the write (the keys and
1492
+ matched values the read kept of its last run, the row past its bound included) and by the row after it (the
1493
+ **probe**: the read's own statement, its condition and range, limited to the rows the written row pairs with,
1494
+ asking for one row; `chord.query.probes`, at most eight per read and step: past that the read runs). An `update`
1495
+ that assigns none of the columns a read depends on skips without a probe. Where the value before is unknown and matters (a matched column outside the set's key), the read
1496
+ runs. There is no second evaluator: the database decides with the real condition. The store's backend interface
1497
+ gains nothing SQL-specific. `deleteWhere`, an `updateWhere` of a column a read depends on, and a host data import
1498
+ or delete run every read of the table.
1499
+ - **The outbox (owner, 2026-10-26):** optional, `openStore(backend, ctx, { outbox: true })` (an omitted option keeps the
1500
+ persisted setting; switching needs an explicit `true` or `false`), persisted in the store's
1501
+ metadata (turning it on starts sync from an archive at the current `lastSeq`); a table in the store's backend,
1502
+ written in the commit step's transaction (atomic for one `INSERT`); exposed as `store.outbox.read(afterSeq, limit,
1503
+ ctx)` -> `{ seq, writes }[]` and `store.outbox.trim(throughSeq, ctx)`, no pluggable encoding; versioned by the store's
1504
+ schema migrations (its layout) and a `format` per outbox commit (the write vocabulary, the archive's `format`; older
1505
+ formats stepped forward on read, newer ones refused).
1506
+ - **Writes, commits, batches, archives (owner, 2026-10-26):** a *write* (`StoreWrite`, tagged by `kind`) is one change
1507
+ of the store (`put`, `update`, `updateWhere`, `table`, `index`, `document.create`, …); a *commit* the writes of one
1508
+ seq in the outbox; a *batch* the commits `from..to` that sync uploads and a replica applies; an *archive* a manifest,
1509
+ the writes from 0 to `lastSeq` and an `end`. `lastSeq` is the seq of the store's last commit.
1510
+ - **Export and import (owner, 2026-10-26):** `store.export(ctx)` yields the archive's parts, the state after its
1511
+ `lastSeq` as writes (manifest, `table`, `index`, `put`, `document.create`, `end`), holding the commit queue
1512
+ until the iteration ends or `ctx` aborts; `importStore(backend, parts, ctx)` applies them into an empty backend in
1513
+ one transaction with the replica's applier. Lossless (owner, 2026-10-26): every `put` write carries its versions (`$v`,
1514
+ each `json(...)` column's) in the outbox and in archives, a `table` write its state, a `latest` document its current
1515
+ value; the applier never infers a version. The encoding is pluggable; plain JSONL ships first. Sync is not export:
1516
+ it ships outbox batches as commits happen.
1517
+ - **Group commit (S18, owner, 2026-11-04):** the commits queued behind a running commit step form one group, written in
1518
+ one backend transaction at the queue's next turn: each keeps its own step, seq and outbox commit, and memory follows
1519
+ commit by commit after `COMMIT`, in queue order. A refusal in a group rolls it back whole and its commits run again
1520
+ one by one, so only the refusing commit is refused (`store/book.md`).
1521
+ - **`store.onCommitted(listener, onError)`** (built with p2's backup coordinator, 2026-11-11; no decision): calls
1522
+ `listener` with the new `lastSeq` once commits are durable and adopted (a commit, a group, a series, an applied
1523
+ batch), in a microtask of its own, never inside a commit, once for however many commits it covers; a listener that
1524
+ throws is removed and its error handed to `onError`, never to the commit. Returns its removal.
1525
+ - **Session sync** (`@diffra-ai/chord/sync`, experimental): uploads of a store's outbox batches to a remote, pulls
1526
+ applied with `applyBatch` (one transaction per chunk), restores from an archive. A batch is applied with the host
1527
+ stopped (decision "Sync applies batches with the host stopped", 2026-11-02): `applyBatch` refuses (`invalid/args`)
1528
+ while an owner holds a claim on the store.
1529
+ - **`json(schema, { version, migrate? })` columns (owner, 2026-10-26):** schema and version required, `migrate`
1530
+ optional and pure, on access (W11), its result checked once (R8); without it (or failing) the read is refused and
1531
+ the owner fails `broken`; each column's version and schema fingerprint are recorded in the table definition and
1532
+ compared at activation (same version, other fingerprint: `broken`, D9); a read never writes back.
1533
+ - **Table versions: `evolveTable` (2026-10-27, the second spec review's majority):** a table's history is a base
1534
+ (`defineTable`) and one `evolveTable(prev, (t) => t.rename(…).add(…).rows(…).drop(…).index(…))` per version, each
1535
+ materialized and fingerprinted at declaration, as contracts' `evolve`; the store replays the recorded version's
1536
+ successors in order (DDL and `migrating`, the data step, `ready`); key columns are immutable in `set`.
1537
+ - **Eager migrations and addresses (owner, 2026-10-26):** the activation attempt's `readyTimeout` deadline does not
1538
+ run while an eager migration step runs (getters still time out by their own). Store names carry no host kind (slice
1539
+ 6b R2, owner, 2026-10-27): tables are `"<object type>:<table>"`, document owners `"<object type>"`.
1540
+ - **Eager `rows` migrations** commit in chunks of 100 rows (owner, 2026-10-26; a fixed constant: about 1 ms of commit
1541
+ step per chunk, the total time is the same for larger chunks, and every other owner's commit waits for the step).
1542
+ Between chunks the migration yields one macrotask without `setTimeout`'s 1 ms clamp: `setImmediate` where the
1543
+ runtime has it, otherwise a `MessageChannel` message (2026-10-27, slice 6a build reviews).
1544
+ - **Eviction as in Durable,** for keyed persisted documents only (persisted singletons and `at(key)` documents stay
1545
+ in memory while their object lives: `handle.value` is a synchronous read; owner, 2026-10-26): one not read, written or watched for the retention
1546
+ period (default 10 minutes) leaves memory and reloads on the next access. **Store errors (owner, 2026-10-27; supersedes in part "Store errors: Durable's rule"):** the store has Durable's
1547
+ `Storage` semantics, its owners react as Durable's Session does. A step that fails before `COMMIT` rolls back: that
1548
+ commit rejects, nothing is adopted, the store goes on. The store stops (`storage_failed`: later calls reject
1549
+ `unavailable/storage_failed`, the host closes, `onError` receives `{ kind: "storage_failed" }`, the app decides,
1550
+ section 3) only when the outcome is unknown (`COMMIT` or `ROLLBACK` failed) or `adopt` threw, and on a backend
1551
+ error of a read whose `ctx` was not aborted. A Chord object whose commit the step refused (memory and disk disagree:
1552
+ the counted conditional `UPDATE`, the live-address index) fails live (`object_failed`, `broken`); an `int` result out
1553
+ of range (`CHECK`) fails only that transaction (`invalid/args`). Durable's Session fails on any commit error
1554
+ (`GuardedStorage`), as today.
1555
+
1556
+ ### Data belonging to a host (decision "Documents and table rows can belong to a host", 2026-11-09)
1557
+
1558
+ Spec `host-keyed/spec.md` §2 to §5.
1559
+
1560
+ - **Schema 3:** `chord_documents.host` (the canonical address key of a host-keyed document's host, NULL otherwise) with
1561
+ a partial index. Archives stay `format: 1`; a record carries `host`, a column `host`, a host data archive's manifest
1562
+ `host`.
1563
+ - **`host(Kind)` columns:** a non-`opt` `str` column holding canonical address keys (`{ type: "str", host: "<kind>" }`
1564
+ in the catalog and the fingerprint), at most one per table, read as addresses. The definition adds the index `host`
1565
+ over it unless the key starts with it; `evolveTable` cannot add a host column (no default). Queries compare it with
1566
+ `eq`, `ne`, `inArray` only, and match it in `exists` and `join` as any column of a set's key or declared index.
1567
+ - **Column sets (slice 14):** `defineColumns(name, { columns, key, indexes? })` in a contract file names the scalar
1568
+ columns of a table others may use, its key, and the indexes others may match by. The table spreads
1569
+ `...Set.columns` into its columns and declares `exposes: Set` (`evolveTable(previous, edit, { exposes })` for a
1570
+ later version); `defineTable` checks both at declaration. No versions: the columns a read uses are checked by name
1571
+ and type when it opens, and again when the binding changes: a joined set's key must still be the key the read
1572
+ matches whole, and the columns an `exists` compares must still have their types. The store's binding of the name to a table follows the
1573
+ committed code: made when the owner's attempt has prepared the table, moved or dropped by its successor, dropped
1574
+ when the object ends; two tables exposing one name fail the second owner's activation, naming both. A read over a
1575
+ set nobody serves fails `unavailable` and runs when one appears; a run a commit's step made before a binding
1576
+ changed is dropped when that commit adopts (it is of a statement the read no longer has). While a bound table is created or migrated, other
1577
+ owners' reads over it are held (not run, their rows kept); when it is ready they compile again and run once.
1578
+ - **`exists` and `join` (slice 14):** `exists(Set, { setColumn: column, … }, (t) => condition)` is true for a row
1579
+ when the set's table has a row equal in the matched columns that satisfies the condition; `existsNode(Set, match,
1580
+ node)` takes the condition as data. `query(Table).join(Set, (row) => ({ keyColumn: row.column, … }))` pairs each
1581
+ row with the one row of that key, as an inner join driven from the query's own table; the partner's columns may
1582
+ be compared, ordered by and handed to the mapping. **Two tables are matched only by equality to the set's key or
1583
+ to one of its declared indexes** (a leading prefix for `exists`, the whole key for `join`). A `NULL` in a matched
1584
+ column matches nothing. `updateWhere`, `deleteWhere` and a `when` take neither.
1585
+ - **Conditions as data (slice 14):** `compile(Set, condition)` gives a condition as plain data; a builder takes one
1586
+ with `query(Table).whereNode(Set, node)`, for the query's own set or a joined one, which checks the whole node
1587
+ before anything is rendered (one known kind per node, operand types, every column, a depth bound). Conditions are
1588
+ built by server code, never taken from a client. There is no substring filter: filtering as you type goes
1589
+ through a search plugin's method.
1590
+ - **Filtered archives:** `exportHostData(store, address)` writes the address's records and rows in the archive
1591
+ format (the tables with a host column of its kind, only its rows; its records), holding the commit queue.
1592
+ - **Import** (the host's `importHostData(parts, ctx, { address?, existing? })`, one commit): the archive is
1593
+ checked as untrusted (a manifest `host`, every row and record of it, Chord records only; its table metadata is not
1594
+ compared: a fingerprint is no security boundary);
1595
+ existing data of the target is refused or, with `existing: "replace"`, retired and deleted in the same commit; a
1596
+ table not recorded here is created from the archive; every row must hold the target in the recorded table's own host
1597
+ column; an older or `migrating` archive table's rows migrate in
1598
+ memory through the owner's `evolveTable` history (edits, `rows` and `update` steps, `$v` and `json(...)` cell
1599
+ versions exact; the owner activated for it); a newer one is refused. Records get fresh ids and the commit's seq,
1600
+ their values as bases at their versions (they migrate on access); rows never replace another address's row. A copy
1601
+ under another address of the kind rewrites host cells and keys only. The commit's writes are ordinary outbox
1602
+ writes (`document.create`, `put`, `document.retire`, `deleteWhere`).
1603
+ - **Delete** (`deleteHostData(address, ctx, { plugin? })`): one commit retiring the address's records and deleting
1604
+ its rows; with `plugin` (slice 14 §6) only what that plugin's objects own, the documents and tables of the types
1605
+ it serves on the host now (a session moving to another app drops the old app's data of it; data under a type
1606
+ the plugin served before and serves no more stays); a plugin not loaded there is `invalid/args`.
1607
+ - **Live claims:** import and delete are the host's only (the store-level functions are internal). A host data gate
1608
+ serializes them and keeps activations' load phases out while one is exclusive; the operation holds the lines of
1609
+ every live owner (of host-keyed documents of the kind, of tables with a host column of it, of the archive's and
1610
+ stored records), reads what they hold of the address inside its commit step (documents through the step, live
1611
+ queries re-run) and adopts it all in one `host.batch.commit` after `COMMIT`, as an ordinary commit (W1). The commit
1612
+ is admitted only while the caller's context is live; an object that cannot read an imported
1613
+ document fails alone.
1614
+
1615
+ ---
1616
+
1617
+ ## 11. Kinds of state
1618
+
1619
+ | Kind | For | API |
1620
+ | --- | --- | --- |
1621
+ | document | data the object owns | `self.state`, `self.tx` |
1622
+ | derive | computed values | `self.derive(sources, fn)` |
1623
+ | Durable's views | the conversation view, task graph and Durable documents | `Watchable`s through Durable's watches; feed derives and state members |
1624
+ | paged method | large or queryable collections | a method returning pages (chat history) |
1625
+ | table | a plugin's own records with queries (owner, 2026-10-21) | `self.table`, the store's query DSL |
1626
+ | live query (own) | the owner's own bounded window, live (owner, 2026-11-03) | `self.query(table, q, limit)` |
1627
+ | named query | a store's records as others read them (slice 14) | `queries(Item, { name: argsSchema })`, `self.queries` |
1628
+ | live query (named) | the first `n` rows of a named query, live | `self.liveQuery(namedQuery, args, { first })` |
1629
+ | count | the exact number of rows of a named query: every matching row read on each run | `self.count(namedQuery, args)` |
1630
+ | list | a named query a screen loads more of | `self.list(name, [[namedQuery, args]], { first })` |
1631
+ | plugin database | derived data only: full-text search, caches (rebuilt, never synced) | a native opened by its owner |
1632
+
1633
+ App state lives in Chord documents; only transcript-bound data (entries, documents that fork and rewind with a
1634
+ conversation) lives in Durable.
1635
+
1636
+ **Live queries** (decision "Live queries over an object's own tables", owner, 2026-11-03): `self.query(table, q,
1637
+ limit)` in the factory of the table's owner returns a `Watchable` of `q`'s rows (at most `limit`, in its order): a
1638
+ state member, a derive source, an `on` source. Chord runs it before the object goes live (with its documents and
1639
+ tables, section 10) and again in the commit step of every commit that can change it (the skip test, section 10);
1640
+ the rows are adopted in the commit's batch and published as `diffRevisions` ops (W1), unchanged rows kept the same
1641
+ objects so the diff compares them by identity. Rules: its own unnamed read (other objects read named queries); the
1642
+ query is fixed for the attempt (params decide it); **a limit is required** (`invalid/args` at declaration; the store's query language keeps the limit
1643
+ an argument of the runner, as `page` has it). A run that fails (a row the code cannot read) is a failed member, as a
1644
+ throwing derive (one failure call, `query_failed` once per episode, `[["r", rows]]` at the next good run); the object
1645
+ stays live. It is no native: a restart's successor runs its live queries again at its activation (section 21). A host
1646
+ data import or delete (§10) is the one other writer of an object's tables: it runs every read over a table with a
1647
+ host column of its kind again (joined and `exists` tables included) inside its commit step and adopts them in its
1648
+ batch. Cost: a bound limits the rows a run returns; what it reads depends on the index its order and condition can
1649
+ use, and every run blocks its host (the store's backend is synchronous). 100 rows: about 60 µs unwatched, 80 µs
1650
+ watched (`benchmarks.md`). **There may be dragons** for a table written hundreds of times a second with many live
1651
+ queries the skip test cannot skip. Maintaining a page from the written rows instead of running it again is left for
1652
+ when a case needs it.
1653
+
1654
+ **Named queries** (slice 14, `slice-14.md` §3): a `local` contract lists them, `members: { sessions:
1655
+ queries(SessionRow, { visible: argsSchema, one: argsSchema }) }`, the argument schemas part of the fingerprint. The
1656
+ table's owner returns what `self.queries(table, { map, reads?, partnerReads? }, { name: builder })` gives: one
1657
+ builder per listed query, a pure function of its arguments returning a query of the table (joined or not); a query
1658
+ the contract does not list is private to its owner and brings its schema (`name: [argsSchema, builder]`). `map`
1659
+ gets only the columns `reads` (and `partnerReads`) list: a change of another column is no change of an item. Any
1660
+ object on the store's host declares `self.liveQuery(ref.sessions.one, args, { first })` in its factory (its member
1661
+ is `{ rows, more }`), `self.count(…)` (the exact number, expensive: every run reads every matching row, and every
1662
+ write to its tables runs it again except an `update` that assigns none of its condition's columns), or calls
1663
+ `ref.sessions.visible.page(args, n, ctx, { after })` anywhere (not live). `args` may be a watchable of the
1664
+ arguments: the member shows the previous rows until the read for the new arguments has run, then switches in one
1665
+ frame. A reader's reads open during its activation, after the member check and before its natives (a waiting
1666
+ attempt holds none; arguments computed from a followed source or a native have no value there and fail the attempt
1667
+ `broken`); one whose first
1668
+ run fails (a column set nobody serves) parks its object `failed { waiting }` until a later run
1669
+ succeeds; arguments the schema refuses and a builder that throws fail it `broken`. A `queries` member cannot be
1670
+ re-exposed and exists in `local` contracts only. The wrong form of each call throws naming the other
1671
+ (`self.query` given a named query, `self.liveQuery` given a table). The index rule: a named query names, in a
1672
+ comment, the index its order and its condition's selective part run on; an `inArray` on one column with an order on
1673
+ another walks the order's index (measured: 2.3 ms instead of 0.07 ms at 10,000 rows), so every named query gets a
1674
+ plan test.
1675
+
1676
+ **Lists** (slice 14, `slice-14.md` §4): `self.list(name, [[namedQuery, args]], { first })` returns `{ value, more }`:
1677
+ `value` is a `Watchable` of `{ rows, moreAfter }` (a state member), `more(ctx)` a method's body. "Load more" must
1678
+ send only the new rows, loaded rows must stay live, and a row that moves (a list by last touch) must leave no gap
1679
+ and no duplicate; a range by count cannot do that (when a row moves to the top, "the first 50" loses its old last
1680
+ row to no page). So a list's pages tile the query's order between fixed **bookmarks** (positions: the order
1681
+ columns' values): page 1 is `(start, b1]`, page 2 `(b1, b2]`, each one read of the store with its bounds, and the
1682
+ last page is open at its end while no row is known behind it. The open last page reads `first + 1` rows; when a run
1683
+ finds a row behind what it shows, its bound is fixed at its last shown row and `moreAfter` turns true until `more`
1684
+ opens the next page (`moreAfter` true may be stale: the `more` that loads nothing turns it false). A touched row
1685
+ leaves its page's range and enters the first page's: both run in that commit and the value changes by one move.
1686
+ Pages split and merge when their runs are adopted, from the rows just read, with no I/O (a page of more than two
1687
+ pages' rows is cut; neighbours with at most one page's rows together become one); a run belongs to the interval it
1688
+ read, so in a commit group a later run lands in whatever pages cover its interval after an earlier one's cut or
1689
+ merge, which then know its rows and whether it was cut by its limit. A failed page fails the list until a run of
1690
+ that page succeeds; arguments the builder refuses fail it until arguments build again, and nothing read before may
1691
+ heal either. A bounded page reads at most four pages' rows: a bulk write past that is cut, the rest of its range loads
1692
+ next, and the value ends at the cut meanwhile, a prefix, never a hole. A commit that touches several pages (a row
1693
+ moving from one to another) is one frame of the list: the value after the commit, diffed from the value before it.
1694
+ One list object per screen (a remote object
1695
+ with the screen's own id in its params); a re-hold sends everything it has loaded. The object keeps each list's
1696
+ bookmarks by the list's name across its attempts: a reload's successor opens the pages the list had and goes live
1697
+ once each ran, one frame; arguments that follow a value and a provider's restart reopen every page under its
1698
+ bookmark and switch in one frame (a `more` called while such a switch is pending or the provider restarts waits and loads behind
1699
+ the pages the list shows next), and so does a change of a column set's binding the query names (a publisher's migration may change every
1700
+ page's rows and order: the pages are never read again one by one); another order starts the list again with a first page. A keyed document's keys
1701
+ still have no live list. Lists over several named queries merged into one are carry-over (`slices.md`).
1702
+
1703
+ ### Watchables (owner, 2026-10-21; log "Watchable and one watch API", W1-W4)
1704
+
1705
+ There is no `replicatedState` in v2. Everything observable is one of two kinds, sharing one lifecycle:
1706
+
1707
+ ```ts
1708
+ interface Watchable<T extends JsonValue> { // JSON only (no bytes); documents, derives, reference members, constant(v), Durable's views
1709
+ readonly value: T;
1710
+ watch(ctx: Context): Promise<WatchHandle<T>>; // listener (call, ctx), call: WatchCall<T> (below)
1711
+ }
1712
+ interface NativeWatchable<T> { // self.writable(initial) with set(), composed registry values
1713
+ readonly value: T;
1714
+ watch(ctx: Context): Promise<NativeWatchHandle<T>>; // listener (call, ctx), call: NativeWatchCall<T>; a change is a new value (!==)
1715
+ }
1716
+ type WatchCall<T> = // owner, 2026-10-27: a recoverable failure is a call, the watch stays open
1717
+ | { kind: "value"; value: T; ops: Op[]; retired: boolean }
1718
+ | { kind: "failed"; error: unknown };
1719
+ type NativeWatchCall<T> = { kind: "value"; value: T } | { kind: "failed"; error: unknown };
1720
+ // const w = await notes.watch(ctx); send(w.value);
1721
+ // w.start(async (call, ctx) => { if (call.kind === "failed") return showError(call.error); render(call.value); });
1722
+ // … await w.stop();
1723
+ ```
1724
+
1725
+ - **Failures are calls, watches end only for good (owner, 2026-10-27):** a source that fails and can recover (a
1726
+ derive whose compute throws, a replica member a hold lists as failed, a member a new variant lacks, a registry whose
1727
+ `compose` throws, slice 8) gives its watches one `{ kind: "failed", error }` call and keeps them open; its next good
1728
+ value arrives as `[["r", value]]` (folded with the failure for a busy listener). A failed derive recomputes on every
1729
+ later change of its sources and on a re-bind (self-healing). A watch ends only when nothing can come back: its owner
1730
+ ended (`ended`), `stop()` or a cancelled context, a throwing listener (`listener_error`), `storage_failed`. `self.on`
1731
+ handlers are not called for failures: a routine waits for the next good value (the failure is reported where it
1732
+ happens: the derive's owner reports `derive_failed { object, member?, error }` once per failure episode, the first
1733
+ failure after a value or after creation, not for a derive failing only because a source failed). `ref.state` stays
1734
+ a separate watchable of the object's reachability (`loading | live | failed | ended`), with the same words. A
1735
+ replica member that vanished with a variant is kept and comes back with a later binding; while failed it accepts
1736
+ only `[["r", value]]`.
1737
+ - **Watch handles are Durable's, moved into Chord** (Durable imports them): `watch()` atomically takes the current
1738
+ value and buffers later commits; `start(listener)` installs the one listener; commits are delivered in order, async
1739
+ listeners awaited; a listener still busy with an earlier frame gets the commits made meanwhile as one call, from
1740
+ the **pending queue** (owner, 2026-10-23): ops stay raw and are folded through a leaf index (a map from path to
1741
+ the last pending append or primitive set; a new one on that path merges into it; any structural op clears the
1742
+ map; `r` drops everything before it); past 10,000 pending ops only "replace with the current value" is kept (no
1743
+ size, text or time caps; no folding of list appends or trims; ops come only from Chord's tracker and
1744
+ `diffRevisions`, so there are no defences against hand-written ops). `PendingOps` is Chord's shared Delta code. The
1745
+ same queue holds a link hold's ops while its window is full (section 3). Natives: every value in order, past 100 pending values one call with the newest (W4). Durable's
1746
+ event stream keeps its own queue (events are not state); `stop()` is idempotent, drops pending frames, never aborts or awaits a running call; `stop()` and
1747
+ `closed` return the end, tagged by `kind` (owner, 2026-10-27): `stopped`, `aborted` (its context aborted), `ended`,
1748
+ `listener_error { error }`, `failed { error }` (a final failure; a recoverable one is a call). Durable's synchronous
1749
+ observers take the same shapes: `advance(call, ctx)`, `end(end)`.
1750
+ **Retirement (owner, 2026-10-26, option A; replaces W2a's `[["r", null]]` frame and the end `retired`):** one
1751
+ mechanism for Chord and Durable documents, singletons and keyed alike. A watch follows its document's address; a
1752
+ retirement is one last call with a `retired` flag (a Chord document: `initial()` with `[["r", initial()]]`, which a
1753
+ wire replica applies; a Durable document: the last good value, no ops); the watch goes on, and a later
1754
+ write delivers the new incarnation as `[["r", value]]`. A watch ends `ended` with its owner (the object of a Chord
1755
+ document; for Durable the task of a task document, right after its retirement call, or the Session). Listeners take
1756
+ one object before the context (owner, 2026-10-26; tagged since 2026-10-27, above): `(call, ctx)`, a `WatchCall` or
1757
+ `NativeWatchCall`.
1758
+ A retirement call carries the address's value after the retirement: `initial()` for a Chord document, the last value
1759
+ (no ops) for a Durable one, which has none while absent. Watching an absent address gives `undefined`. On the wire a
1760
+ `state` entry lists retired members like failed ones. A per-key source in a factory, `handle.at(key)`, is a singleton per key: loaded at activation, `initial()` while absent, usable as a state member, derive source and `on` source (owner, 2026-10-26). A
1761
+ stopped watch releases every reference it held (W3).
1762
+ - **Only a `Watchable<Json>` can be a contract state member**, by type and by a kind check when the object is served
1763
+ (Q14); a `NativeWatchable` never can, even holding JSON. Mutating a native value in place notifies nobody. (Event
1764
+ members go on the wire too: below.)
1765
+ - **Publication (W1):** the commit step writes, adopts (pointer swaps, Durable's touched views dispatched by id) and
1766
+ marks (dirty derives; ops appended by reference to each touched hold's batch and each watch's queue). Right after
1767
+ the step, synchronously, the owner's flush recomputes the dirty derives someone holds or watches (dependency order),
1768
+ encodes one entry per touched hold into one `state` message per link and origin, and queues watch callbacks. A
1769
+ throwing derive fails only its member; reentrant `self.tx`/`watch`/`release`/`get`/`hold`/`load`/`close` throw
1770
+ `invalid/reentrant`; a delivery or flush that throws is reported (`delivery_failed`) and the others still run. The
1771
+ same boundary runs without a store seq for in-memory commits, `writable.set`, registry changes and inbound wire
1772
+ batches (a `bound` or `state` message is applied as one batch before listeners run). There is **one batch per host**,
1773
+ passed to its sources (no module-level singleton); a dirty derive nobody holds or watches recomputes lazily on its
1774
+ next read.
1775
+ - **Consumers:** derives and the wire use the internal flush; app code uses watches; `self.on` is a watch owned by
1776
+ the object (first call with the current value, then every commit; Chord awaits a running call on reload); clients
1777
+ get ordered ops over the link, folded by the provider's pending queue when they fall behind (section 3); a re-hold
1778
+ gets a fresh snapshot.
1779
+
1780
+ ### Events (decision "Events: fire-and-forget members", owner, 2026-11-11)
1781
+
1782
+ Folding and the window are right for state (a slow page gets the newest value, never a backlog) and wrong for motion:
1783
+ a paddle position is a sample in time, worthless a moment later, and interpolation needs the samples around the time
1784
+ it draws. Events are the third member kind for that (section 5): never folded, never kept. **One rule: events are
1785
+ collected until the event flush, a microtask the first emit queues; the flush sends them after every `state` message
1786
+ published before it runs.**
1787
+
1788
+ - **The list and the counter:** an emit increments the host's emit counter and appends `{ source, value, at, n }` (`n`
1789
+ the counter's new value, `at` the emitting host's `Date.now()`) to the host's event list; the first entry queues the
1790
+ flush. Commits keep flushing synchronously at their end (W1), so state published before the flush is sent first:
1791
+ `emit(A); commit; emit(B)` in one synchronous run is the commit's `state` message, then one `event` message with A
1792
+ and B. A commit whose publication waits for a later microtask (`emit(A); queueMicrotask(commit)`) may follow A.
1793
+ - **Who gets an event:** each binding records the counter's value when it is made: a hold over a link when its `bound`
1794
+ is sent (one held back by the state window gets nothing before it), a same-host reference when it binds to the
1795
+ instance, a re-exposing reference likewise; a reference joining a shared remote object (§7) when it binds (it gets
1796
+ the events that arrive at its host after it bound, also one emitted before that was in transit; the provider's
1797
+ eligibility is per wire hold). Counter values are each host's own: an event arriving over a link takes
1798
+ the receiving host's next value as it arrives, and that host's bindings are judged by it. A binding gets only entries
1799
+ with a higher `n`, and only while it stays that binding: at the flush each entry goes to the bindings of its
1800
+ source's object instance that pass this test, and through re-exposure to the bindings of the re-exposing objects by
1801
+ the same test. A binding that ended before the flush (released, `loading`, failed, ended, or unbound and bound
1802
+ again, even to the same instance) gets nothing; one made after the emit never inherits it. A binding whose object no
1803
+ longer shows it live stops getting events at once, everywhere: a hold over a link untaps its event members then,
1804
+ while its state still follows the instance's admitted commits until they published (section 7); an old attempt still
1805
+ shown live during a reload's drain keeps delivering until its holds leave it.
1806
+ - **Sends, then listeners:** per link and origin with entries, one `event` message (section 22), unless that origin's
1807
+ event window is full (section 3: dropped). Then the same-host listeners, outside the publication's reentrancy fence
1808
+ (as watch callbacks): in entry order, then subscription order. A listener may release, subscribe, start transactions
1809
+ and emit (into the next flush, a new list); one stopped, aborted or released before its call is skipped; one that
1810
+ throws is reported (`listener_error`) and its subscription ends, the others are called. A consumer applies a
1811
+ received `event` message the same way.
1812
+ - **Re-exposure:** an object implementing its event member with a reference's (`paddle: store.paddle`) forwards each
1813
+ event unchanged, value and `at`; an object that transforms events emits from a source of its own, which stamps anew
1814
+ (a sample time the app needs belongs in the value). Per-principal filtering is a routine re-emitting (section 14).
1815
+ - **No order with later state:** a `state` message held back by a full state window is overtaken by later events. A
1816
+ fact that must follow a state change on every holder goes into state.
1817
+
1818
+ ---
1819
+
1820
+ ## 12. Derives
1821
+
1822
+ `self.derive(sources, (values) => value)`: a synchronous pure function, recomputed when a source changes and
1823
+ diffed into ops for the wire. Sources are `Watchable`s and `NativeWatchable`s (documents, other derives, reference
1824
+ members, Durable's views, registry values); the result is always JSON (state is JSON only; bytes only in method arguments and results). A derive is marked dirty in the
1825
+ commit step and recomputed in the owner's flush right after it, so its change travels in the same message as its
1826
+ source (W1); a dirty derive nobody holds recomputes on its next read. One commit is one frame of a derive, its
1827
+ value at the end of the commit diffed from the value before it, however often its sources changed in the commit and
1828
+ whoever read it in between. A throwing derive fails only its member (`broken`). There is no `previous` (W14): `mapShared` keeps unchanged elements identical.
1829
+
1830
+ - **Built on what exists:** derives sit on Chord's internal publication primitive (not today's `cell.ts` or
1831
+ `replicatedState`); the diff is
1832
+ Delta's `diffRevisions` called directly (identity short-circuit: unchanged shared subtrees cost one `===`; bytes are
1833
+ atomic leaves compared by identity; equality never by stringify).
1834
+ - **Container width (R24):** structural sharing is O(change) along a path, not across a container's width: changing
1835
+ one item of a flat array copies the array's slots, and `mapShared` visits every element (one identity comparison
1836
+ each). Large collections are keyed documents or bounded windows; a benchmark of long arrays (allocations, element
1837
+ visits per change) sets the documented limit.
1838
+ - **The footgun:** a derive that builds new objects for unchanged data makes every commit cost O(size of the value),
1839
+ per view, because the diff must compare contents. Unchanged parts must be the same objects as last time.
1840
+ - **`mapShared(f)`** (from `@diffra-ai/chord` state; it moves into Delta when v2 goes upstream): an identity cache per source element: `f` runs only for new or
1841
+ changed source elements, unchanged ones return their previous result object. With it a list derive costs pointer
1842
+ comparisons, not content comparisons:
1843
+
1844
+ ```ts
1845
+ const strip = mapShared((n: Note) => ({ text: n.text, at: n.at })); // a mapper over the whole array
1846
+ self.derive([notes], ([n]) => ({ list: strip(n.list) }));
1847
+ // one appended note: one new object, 2,000 identical references, diffRevisions emits one insert
1848
+ ```
1849
+
1850
+ - **Cookbook** (documentation with examples per case): select a field, look up by key, small aggregates (just compute;
1851
+ the value is small); filter or map a list (`mapShared`); redaction (preferably separate documents per visibility,
1852
+ otherwise `mapShared`; computed once in the shared store, not per view); joins across two sources (`mapShared` plus
1853
+ the looked-up source's revision); a window over a large list (take a section of the source elements without
1854
+ rebuilding them, cache per-element measurements by identity, keep the window's start stable so changes arrive as
1855
+ appends). Large combined views from several sources re-path the sources' ops (as Durable's `ConversationView`);
1856
+ application code never interprets ops.
1857
+
1858
+ ---
1859
+
1860
+ ## 13. Natives
1861
+
1862
+ ```ts
1863
+ const watcher = self.open(async (context) => watchDir(path, { signal: context.abortSignal }), (w) => w.close());
1864
+ self.onLive(async (ctx) => { for await (const f of watcher.value.files(ctx.abortSignal)) await importFile(f, ctx); });
1865
+ ```
1866
+
1867
+ - `self.open(open, close, { closeTimeout? })` (slice 2): `open(context)` gets a context aborted when the attempt is
1868
+ abandoned (a timeout, a cycle, its end); `close(value, reason, context)` gets one aborted at the close timeout, after
1869
+ which a possible leak is reported (`close_timeout`) and the rest continues. It returns a handle with `.value`, not a
1870
+ proxy: reading it before its open resolved throws `not_ready`, after its close started `released`. A value that
1871
+ arrives after its attempt was abandoned is closed at once.
1872
+ Natives open during activation (the object goes live after all opens) and close in reverse order when it ends.
1873
+ The opened value never changes during that attempt: no `self.resource`, versions, `replace`, `deps` or stale
1874
+ handles. To change a live native, the object restarts. A partly failed activation closes already-open natives
1875
+ with reason `end`; a later attempt opens them all anew. `retryOn` may appear anywhere in the synchronous factory.
1876
+ Type names: `Native<T>` (the handle), `NativeCloseReason`.
1877
+ - **Order:** natives open one after another in declaration order (a later opener may use an earlier handle's
1878
+ `.value`) and close in reverse. A throwing `close` does not stop the others: on `host.close()` all errors are
1879
+ collected and it rejects with them; an object ending in the background reports them to `onError`.
1880
+ - Behaviour around a native goes into routines; listeners on natives outside routines are forbidden.
1881
+ - The facet may not open natives.
1882
+ - What an old native does after its owner restarts is its owner's `close` (a model runtime keeps working until
1883
+ collected; a closed SSH connection fails its in-flight `exec`).
1884
+ - An open that fails makes the object `failed` (`transient` with backoff, or `broken` if it says so).
1885
+
1886
+ - **`close` gets a reason:** `reason: { kind: "reload" } | { kind: "close" } |
1887
+ { kind: "end" }` (the plugin is reloaded and the object is native / the host shuts down / the last reference ended or
1888
+ the type was removed). Chord aborts only the object's own calls and jobs; other work using the native (Durable tool
1889
+ executions on a code mode sandbox) is the owner's: `close` may drain instead of tearing down, e.g. seal the sandbox
1890
+ (no new scripts) and end it when its running scripts finish or hit their deadline.
1891
+ - **Restart stays sequential (R16):** close the old native, then open the new one. Two patterns for natives whose
1892
+ resource has work in flight:
1893
+ - **Drain in the background:** `close` detaches the old resource, returns at once, and disposes of it when its work
1894
+ has finished or after `closeTimeout` (30 s at most, Q7: a longer script is aborted); Chord then opens the new one
1895
+ immediately. Code mode's sandbox does
1896
+ this; its tool entry looks up the current sandbox at `execute()`.
1897
+ - **Replace through a registry:** the resource is a registry contribution; readers always find the current one, and a
1898
+ reader that must wait for one uses a cancellable "wait until present" with the park deadline.
1899
+
1900
+ ---
1901
+
1902
+ ## 14. Routines
1903
+
1904
+ Two kinds, declared in the factory (owner, 2026-10-24; C4 decided; slice 5):
1905
+
1906
+ ```ts
1907
+ self.on(catalog.sessions, async ({ value: sessions }, ctx) => { // reacts to a value: first the current one, then every change
1908
+ for (const f of forwards.value.list) if (sessions[f.session]?.archived) await close(f.id, ctx); // idempotent
1909
+ });
1910
+ self.onLive(async (ctx) => { // called once when the object goes live
1911
+ for await (const file of watcher.value.files(ctx.abortSignal)) await importFile(file, ctx);
1912
+ });
1913
+ self.onLive(async (ctx) => { // periodic: a loop with sleep
1914
+ for (;;) { await sleep(HOUR, ctx); await dropOld(ctx); }
1915
+ });
1916
+ self.onLive(async (ctx) => { // set up, wait for the end, clean up
1917
+ const timer = setInterval(tick, 1000);
1918
+ try { await untilAborted(ctx); } finally { clearInterval(timer); }
1919
+ });
1920
+ ```
1921
+
1922
+ - **Lifecycle (both kinds):** declared in objects, never in facets (owner, 2026-10-26: everything is done through
1923
+ objects); they start when the object goes live (in the same turn)
1924
+ and stop when it ends (their `ctx` is aborted, then
1925
+ the drain waits for running calls, bounded by `closeTimeout`). Each call gets its own `ctx` (the object's principal
1926
+ for a remote type, the host's for a local one; the host's incarnation; `ctx.get` released when the call settles).
1927
+ - **On reload** the old routines' `ctx` is aborted at the restart; their calls drain with the old attempt, and the
1928
+ new routines start when the successor goes live, after the old attempt's seal: routines need no names. Example it
1929
+ prevents: an old handler midway through `restart(W1)` and a new one seeing W1 still pending and restarting it again.
1930
+ The bound is the reload drain bound (`reloadDrainTimeout`); a call still running then is reported `drain_timeout`
1931
+ and the whole old attempt is sealed (audit A12: one seal token per attempt).
1932
+ - **`on(source, fn)`:** any watchable (a document, a derive, a reference member, a registry value, `ref.state`). The
1933
+ first call gets the current value (`[["r", value]]`, W2b), then one call per change; calls never overlap (S8);
1934
+ changes made during a call arrive folded in the next (newest value, folded ops); a running call is not aborted by a
1935
+ change (native sources too: a busy call is followed by one call with the newest value). A throwing call is
1936
+ reported and called again with the current value after a backoff (1 s doubling to 60 s;
1937
+ a change during the backoff calls at once; success resets it). The source ending (a released reference, its object's
1938
+ end) ends the routine without a report; a retired document does not end it (the call has `retired: true`).
1939
+ - **`onLive(fn)`:** called once when the object goes live. Returning ends it until the next reload or activation;
1940
+ throwing is reported and restarts it after the same backoff (reset after a run of at least a minute); an abort is
1941
+ no error.
1942
+ - **Idempotent reconcilers:** a routine reconciles from the current value, writes no "in progress" flags and starts a
1943
+ job for long work. Chord keeps no state for routines across reloads or restarts; what must survive is a document of
1944
+ the object (e.g. a `lastCleanup` time, which also survives a crash).
1945
+ - **Helpers:** `sleep(ms, ctx)` (rejects when `ctx` is aborted, leaves no timer or listener) and `untilAborted(ctx)`.
1946
+ Routines and handlers wait only through calls that take `ctx`; otherwise Chord cannot stop them, and the drain
1947
+ reports them stuck.
1948
+ - **Re-emitting events** (decision "Events: fire-and-forget members"): an event member is no `on` source; a
1949
+ per-principal view filters a store's events with an `onLive` that subscribes and re-emits from a source of its own:
1950
+ `self.onLive(async (ctx) => { const s = await store.paddle.on((e) => mine.emit(redact(e.value)), ctx); try { await
1951
+ untilAborted(ctx); } finally { s.stop(); } })`.
1952
+ - **Errors:** `onError` gets `routine_failed { object, routine, error }`, `routine` a `Position` (`{ kind: "on" |
1953
+ "onLive", position }`; natives use the same type); never uncaught.
1954
+ - **Keep-alive:** routines do not count in `host.activity` (an `onLive` runs forever).
1955
+ - No bare timers or callbacks that touch state outside routines, jobs or calls. Gone (C4): `every` (an `onLive` with
1956
+ `sleep`), `custom` and its `run(fn)` (an `onLive` with `try`/`finally`; callbacks that must run one at a time go
1957
+ through a small queue or the source's async iterator), names, a due time kept across reloads.
1958
+
1959
+ ---
1960
+
1961
+ ## 15. Jobs
1962
+
1963
+ Owned work a call starts that outlives the call (a shell command, a session clone, a peer send, a login's work), in
1964
+ Durable's sandwich: **intent** (a transaction), **run** (any effect), **finish** (a transaction on the current code).
1965
+ Decided with the owner on 2026-10-24 (decision log "Routines and jobs open points", "Jobs keep accepts", "Job crash
1966
+ handling"; C3 settled this way); slice 5 builds jobs in memory, slice 6 persistence, slice 7 their reload rules.
1967
+
1968
+ ```ts
1969
+ const ShellState = defineState("chat.shell.state", {
1970
+ schema: obj({ output: str() }), version: 1, initial: () => ({ output: "" }),
1971
+ });
1972
+ const ShellJob = defineJob("chat.shell", {
1973
+ version: 1,
1974
+ args: obj({ command: str(), author: Author }),
1975
+ result: obj({ exit: int(), output: str() }),
1976
+ state: ShellState, // optional: one document per run
1977
+ concurrency: 1, // optional: at most one active run per object
1978
+ });
1979
+
1980
+ host.serve(ChatStore, ({ conversation }, self) => { // local: no principals; views filter (below)
1981
+ const entries = self.state(ChatEntries);
1982
+ const shell = self.job(ShellJob, {
1983
+ run: async ({ command }, ctx) => {
1984
+ const out = new OutputBuffer({ maxLines: 2000, retain: "tail" });
1985
+ const progress = throttle(100, () => ctx.state.change((d) => { d.output = out.snapshot().text; }, ctx));
1986
+ try {
1987
+ const r = await runProcess(command, ctx.abortSignal, (chunk) => { out.push(chunk); progress.schedule(); });
1988
+ return { exit: r.code, output: out.snapshot().text };
1989
+ } finally {
1990
+ await progress.flush(); // the last output reaches outcome.state, also after an abort
1991
+ }
1992
+ },
1993
+ finish: async (outcome, tx) => {
1994
+ const list = (await tx.draft(entries)).list;
1995
+ list.push(outcome.kind === "done"
1996
+ ? shellEntry(outcome.args, outcome.result)
1997
+ : shellEntry(outcome.args, { interrupted: outcome.error.kind, output: outcome.state.output }));
1998
+ }, // the run's state document is retired in this commit
1999
+ });
2000
+ return {
2001
+ shells: shell.running,
2002
+ runShell: async ({ command, author, requestId }, ctx) =>
2003
+ ({ id: (await shell.start({ command, author }, ctx, { key: requestId })).id }),
2004
+ abortShell: async ({ id }) => shell.abort(id),
2005
+ };
2006
+ });
2007
+ ```
2008
+
2009
+ - **Definition:** `defineJob(name, { version, args, result, state?, concurrency?, accepts?, persist? })`. `args` and
2010
+ `result` are schemas; `state` is a document definition (a singleton, one document per run); `persist` arrives with
2011
+ slice 6. `self.job(Job, { run, finish? })` is declared in an object's factory (not in a facet) and returns the job
2012
+ handle: `start(args, ctx, { key? })` (a `Run { id, outcome(ctx) }` after the commit), `tx.start(job, args, { key? })`
2013
+ inside `self.tx` (a `Run` handle at once, whose `outcome` rejects if the transaction is discarded), `outcome(id, ctx)`
2014
+ (unsettled runs only), `abort(id, ctx)` (`"marked" | "terminal"`, as Durable's `abortTask`: stored, resolves once `run` settled; slice 6b) and `running`.
2015
+ - **1. Intent:** one transaction on the owner's line. Arguments are checked against `args` (closed schema, like
2016
+ method arguments). Dedupe first: a run with the same `key` that is not settled is returned as it is (the run whose
2017
+ `finish` this transaction is never counts, so `finish` can start the same job again with the same key). Then the
2018
+ `concurrency` check: at the limit `start` rejects with `unavailable/busy` (a queue is the owner's, built from a
2019
+ document and a routine). Otherwise a run record `{ id: uuidv7, version, args, key }` and its state document
2020
+ (`initial()`) are written in the commit, with whatever else the transaction writes (`tx.start`: a request entry and
2021
+ the run, both or neither). `run` starts after the commit.
2022
+ - **2. Run:** `run(args, ctx)` may do anything, outside transactions. `ctx` is a `Ctx` (the object's principal for a
2023
+ remote type, the host's for a local one) plus `jobId` and `state`: `ctx.state.value` (synchronous) and
2024
+ `ctx.state.change(fn, ctx)` (a transaction on the owner's line on the run's document, without the run's abort signal).
2025
+ State changes are accepted until `run` settles, also after an abort (so output written while stopping still reaches `outcome.state`), and are
2026
+ refused (`released`) afterwards, never recreating a retired document. Each change is a commit and, while someone
2027
+ watches, a message: authors throttle frequent changes themselves (Chord does not coalesce them); awaiting or
2028
+ catching each change is the author's (an unhandled rejection is the author's bug). External writes carry keys made
2029
+ from `ctx.jobId`. A `run` that throws after its signal fired ends `aborted`, otherwise `threw` (reported as
2030
+ `job_failed`).
2031
+ - **3. Finish:** when `run` settles, Chord records the outcome on the run (`phase: "finishing"`), then calls the
2032
+ current code's `finish(outcome, tx)` in a transaction (Durable's rule: only `await tx.*`). In the same commit Chord
2033
+ deletes the run record and its key (Q9: dedupe covers unsettled runs only) and retires the run's state document. A
2034
+ `finish` that throws changes nothing: it is retried with backoff (1 s doubling to 60 s), each failure reported
2035
+ (`job_finish_failed`); after five consecutive failures the run is `blocked { finish_failed }`, its outcome, state
2036
+ and key kept, retried on the next reload. `finish` is optional (then the commit only cleans up).
2037
+
2038
+ ```ts
2039
+ type Outcome<Args, Result, State> = { readonly id: string; readonly args: Args; readonly state: State } & (
2040
+ | { readonly kind: "done"; readonly result: Result }
2041
+ | { readonly kind: "failed"; readonly error: JobError }
2042
+ );
2043
+ type JobError =
2044
+ | { readonly kind: "threw"; readonly error: ChordError | PluginError } // run threw (reported)
2045
+ | { readonly kind: "aborted"; readonly reason: "abort" | "reload" | "restart" }
2046
+ | { readonly kind: "restart_limit"; readonly restarts: number }; // persisted runs (slice 6b)
2047
+ // abort(id); a native restart on reload, in-memory runs (slice 7b); "restart": a persisted run abandoned after a crash (slice 6b),
2048
+ // or a run cut off by its attempt's seal while the object continues (slice 6a)
2049
+ ```
2050
+ - **Abort is a request:** `abort(id)` fires `run`'s `ctx.abortSignal`; `run` decides what it returns (a result that
2051
+ already arrived stays a success); a run ignoring the signal keeps its slot. Abort of a finishing run does nothing;
2052
+ abort of a blocked run drops it (no `finish`, its record, key and state document go, reported; owner, 2026-10-24).
2053
+ - **Waiting:** `run.outcome(ctx)` resolves with the outcome once `finish` committed; the caller's abort ends only its
2054
+ wait. Across a link nobody waits on a long call: UIs watch state.
2055
+ - **`running`:** a JSON watchable, one entry per unsettled run, tagged by phase:
2056
+ `{ id, version, key?, args, state, phase: "running" | "finishing" } | { id, version, phase: "blocked", reason }`. A
2057
+ blocked run carries no `args` or `state` (it may be of another version than the code); views filter it as they
2058
+ filter anything. Per-principal views derive what each principal may see (§6, the shared store): a reader without
2059
+ output, a guest only their own runs.
2060
+ - **Concurrency and keep-alive:** `concurrency` counts runs that are running or finishing; blocked runs do not count.
2061
+ **Runs belong to the object** (owner, 2026-10-26): records, keys, the active count, `running`, run state documents
2062
+ and pending actions are the object's, across attempts and native restarts; an attempt has the implementation and
2063
+ its running invocations; a run's state changes and outcome are fenced by the run's own invocation; `finish` runs
2064
+ on the current live attempt. **Jobs keep their object alive** (D4): running and finishing runs are a count on the object, not references (they
2065
+ never appear in `host.references`); an object whose last reference goes stays while the count is above zero, and
2066
+ ends (after its type's `linger`) when it reaches zero, dropping blocked runs with a report. `host.activity.jobs`
2067
+ counts them.
2068
+ - **Object end:** revocation (R11), `host.close` and a reload that removes the type end the object at once: runs get
2069
+ the abort signal, the drain is bounded by `closeTimeout`; an in-memory run's outcome and state go with the object
2070
+ (no `finish`). Jobs in `local` stores are never revoked (no principal): a store that runs work for a principal keeps
2071
+ the grant as data and reconciles with a routine (§25).
2072
+ - **Versions (`accepts`, slice 7b §8):** a job is versioned like everything else; `accepts` maps an older version's args
2073
+ forwards and its result forwards (`{ 1: { args: (old) => current, result: (old) => current } }`; a producer's
2074
+ direction, unlike a contract's). Its records keep every run's version: a new attempt's `self.job(Def, impl)` at
2075
+ another version takes the records over (the same version with another fingerprint, over args, result and state, is
2076
+ refused at declaration, as documents). A reload restarts the job's object: a running in-memory run ends `aborted
2077
+ { reload }` at the old attempt's seal (a persisted one is stopped and resumed per `resume`, R3); `finish` runs on the
2078
+ new code with the outcome's args and result mapped forwards (once per run, never per publication); a run not invoked
2079
+ yet runs on the new code with its args mapped, and its state document migrates through its own `migrate`. Without an adapter, for a run of a newer version than the code (a rollback), or for a job the new
2080
+ code no longer declares, the run is `blocked { version }` (kept, not invoked) until a reload brings matching code;
2081
+ blocked runs (`finish_failed` ones too) are retried on every reload of their object's plugin; a persisted run of
2082
+ another version or fingerprint stays blocked with its record as stored until the reload that brings its version
2083
+ resumes it. A native restart aborts running in-memory runs (`aborted { reason: "reload" }`) and `finish` runs on the
2084
+ new code; persisted runs are stopped and resumed per their `resume` (6b R3, owner, 2026-10-29). A `finish` in flight
2085
+ across a reload completes on the code it started with; the next one runs on the new code. A version change aborts
2086
+ nothing and discards nothing.
2087
+ - **Persistence (slice 6):** `persist: { resume: "rerun" | "abandon" }` keeps the run record and its state document
2088
+ in the owner's store (owner: a `local` object with empty params, P3). How a run resumes after a crash is required, no
2089
+ default: rerun (the current
2090
+ `run`, args mapped forwards, state migrated; only work since the last state change repeats, so it must be
2091
+ idempotent) or abandon (`finish` gets `failed { aborted, reason: "restart" }`); wording aligned with Durable
2092
+ (replay-safe, abandon on restart). A recorded outcome resumes only `finish`, never `run`; an abort request is
2093
+ persisted. A restart limit as Durable's (owner, 2026-10-27, slice 6b D6): at activation a run recorded `running` was
2094
+ cut off by a crash: `restarts + 1`, stored, then it resumes (rerun or abandon); a clean close writes its stopped runs
2095
+ back so the next activation counts nothing; a `ctx.state.change` (progress) resets the count; at five in a row the
2096
+ run ends with `failed { kind: "restart_limit", restarts }`, `finish` runs, `job_interrupted` is reported (no
2097
+ parking, as Durable since #11139). A persisted state document may defer storing a change
2098
+ (`ctx.state.change(fn, ctx, { persistence: { kind: "deferred", withinMs? } })`, Durable's shape, default 1,000 ms;
2099
+ stored before the outcome is recorded; slice 6b D8).
2100
+ - **Chaining:** `finish` may `tx.start` the next job, atomically with the outcome (separate steps, branches).
2101
+ - **Not in an admitted object** (slice 14): `self.job` is refused there. Work for a person lives in a `local`
2102
+ store, carries the person in its arguments, and asks the person's access again on every run.
2103
+ - **Not jobs:** request/response work (a method), standing behaviour (a routine), input into running work (a flow,
2104
+ §20: the owner's document plus methods), multi-step durable work with sleeps, waits or ownership trees on a host
2105
+ with a harness (a Durable task). Jobs as objects (#9) are rejected: a third lifetime, two objects per run for two
2106
+ principals, a `finish` across owners.
2107
+
2108
+ ---
2109
+
2110
+ ## 16. The facet
2111
+
2112
+ ```ts
2113
+ import { defineFacet } from "@app/core"; // base code's defineFacet, bound to the app's P
2114
+
2115
+ export default defineFacet((host, self) => { // `self` (contributions) arrives with slice 8
2116
+ self.contribute(Http, { routes: { "GET /notes/export": exportNotes } });
2117
+ host.serve(Notes, (params, principal, self) => …);
2118
+ host.serve(NoteStore, (params, self) => …);
2119
+ });
2120
+ ```
2121
+
2122
+ - **Facets are typed by the app's principal (owner, 2026-10-21):** base code exports `defineFacet` already bound to its
2123
+ `P` (`export const defineFacet = bindFacet<P>()`, next to the principal union), and every facet (server, worker,
2124
+ web, TUI) imports it from there; `host.load` accepts only facets typed for the host's `P`, so a factory's `principal`
2125
+ narrows by variant. Nothing is checked at runtime: the principal a factory receives is the one the link stamped.
2126
+ - A plugin's per-host setup, **declarations only** (owner, 2026-10-26): `host.serve`, `self.contribute` (slice 8),
2127
+ `host.references`; no natives, no documents (C16 accepted), no routines, no jobs. Everything a plugin does at runtime
2128
+ is done through objects: shared or persisted state and standing behaviour live in a `local` store object with empty
2129
+ params (host lifetime, its own failure domain; its dependents park while it is failed and go on when it recovers), as p2 does (its 63 facets take only
2130
+ `host`). A facet cannot fail after `load`.
2131
+ - `host.serve(Type, factory, { linger?, accepts?, admit? })` (`admit`: §6, "Admission"): `linger` (milliseconds, 0
2132
+ by default; slice 3b) keeps a live object with
2133
+ params alive that long after its last reference, so a new reference within that time reuses it with its documents
2134
+ and dependencies; it never applies to objects that are not live.
2135
+ - `host.serve` and contributions are valid only while the setup runs. The facet never `self.get`s a type it serves
2136
+ itself.
2137
+ - Between plugins only: object types and registries. No natives across plugins except through registry entries.
2138
+
2139
+ ---
2140
+
2141
+ ## 17. Registries
2142
+
2143
+ ```ts
2144
+ export const Http = defineRegistry<HttpContribution, Router>("chord.http", { version: 2 }); // shared: identity only
2145
+ host.serve(Http, { // the defining plugin's facet: the one provider (slice 8 D1)
2146
+ compose: (table, { report }) => buildRouter(table, report), // pure; always delivers a value; reports conflicts
2147
+ accepts: { 1: { contribution: (old: HttpContributionV1) => upgrade(old), value: (router) => routerV1(router) } },
2148
+ });
2149
+ self.contribute(Http, { routes: { … }, wraps: [ … ] });
2150
+ const router = self.registry(Http); // a declared dependency; read router.value at use (await host.registry(Http, ctx) outside objects)
2151
+ ```
2152
+
2153
+ - Each contributor (a facet or an object) contributes **at most one value per registry**; the table is an immutable,
2154
+ ordered list of `(contributor, value)`. Contributor order is sorted by plugin name (never load order): deterministic
2155
+ on every host and across reloads, and deliberately meaningless; meaningful order comes from the owner's composition
2156
+ (e.g. HTTP phases). A reload replaces a contribution as a
2157
+ whole.
2158
+ - **`compose` is a runtime composition, not a staging check:** contributions can be dynamic (known only once a native
2159
+ is open, or changing at runtime; contributions may be readables), so no conflict check can be complete in staging.
2160
+ `compose(table, { report })` is pure and runs whenever the table changes (after a commit, when a contributor goes
2161
+ live or ends, when a dynamic contribution changes). It always delivers a value with its fallback built in (e.g. the
2162
+ first by plugin name wins) and reports conflicts through `report` (owner notices and telemetry events); readers get
2163
+ a plain value and never handle conflicts. If `compose` throws, the failure is reported and its
2164
+ watches get a `failed` call, while `.value` keeps the last good composition (slice 8), **but only while every
2165
+ contribution it was built from is still in the table** (dependency model decision 5, slice 7a): when one leaves (its
2166
+ contributor ended, failed or restarted), the last good value is dropped and `.value` throws until `compose`
2167
+ succeeds, so it never hands out a native whose contributor ended; only before any good composition, or after such a
2168
+ drop, do readers get the error. Work that started earlier keeps the value it read (a pinned Durable phase keeps
2169
+ its old table). Helpers: `keyedEntries(table, entriesOf, report)` (a map, the first by plugin name wins, a duplicate
2170
+ reported), `orderedEntries(table, itemsOf, orderOf?)`; both keep each item's plugin (named so beside the contracts'
2171
+ `keyed`, slice 8 build).
2172
+ - **Who contributes (R21):** only facets and host-lifetime objects (`local`, empty params); their factory's `self` has `contribute`, a
2173
+ referenced object's `self` does not (a type error). Reading a registry's composed value stays open to every object.
2174
+ - **A contribution is in the table exactly while its contributor is live:** a facet's while its plugin is loaded; an
2175
+ object's from `live` until it ends, fails or restarts.
2176
+ - **The owner decides** conflicts, order and selection (which contributions apply where).
2177
+ - **One authoritative declaration (Q8):** only the facet of the plugin that defines a registry declares it to the host
2178
+ (`compose`, version, `accepts`); other plugins' tokens only identify it by name and types (contribute and read,
2179
+ never bring their own `compose`). A reload of the defining plugin replaces the declaration atomically (`serve`
2180
+ replaces; a removed defining plugin's provider goes, its readers wait `not_served`) and the table
2181
+ recomposes. Without a declaration (the defining plugin is not loaded) the registry has no composed value: readers
2182
+ wait `failed { waiting }` (`unavailable/undeclared`), like a request for a type nobody serves, reported
2183
+ `unbound_long` after 5 s (§3); contributions wait in the table, and the registry is reported `registry_undeclared
2184
+ { registry, plugins }` at the publication (decision "Mistakes that wait are reported at once" (b)).
2185
+ - **Versions (Q8, the owner-adapter pattern):** a contribution carries the registry version its plugin was built
2186
+ against; older ones are adapted with the defining facet's pure `accepts` when the table is built. A contribution
2187
+ without a matching version or adapter (older without adapter, or newer) is left out of the table and reported (an
2188
+ owner notice naming plugin, registry and versions); its plugin keeps working. Contributions are in-process values
2189
+ (often functions) and are not schema-checked.
2190
+ - **Use sites guard contributions:** a contribution is untrusted code (third-party plugins are a goal of p3). Every
2191
+ use site catches synchronous throws and rejections when it calls an entry, reports naming the contributor (the
2192
+ composed table keeps each entry's plugin name), and continues with the other entries. Durable already does this for
2193
+ extensions (`extension_error`; a throwing tool becomes an error result); `compose` reports through `report`.
2194
+ - **Slice 8's rules** (decisions "Slice 8 D1" to "Slice 8 S3", `slice-8.md`; S2's `broken` and S3's backoff superseded
2195
+ by slice 7a): the token is shared, the provider serves it (`host.serve(R, { compose, accepts })`); `self.registry(R)`
2196
+ in a factory is a declared dependency: the attempt parks until the registry has a usable value at its version
2197
+ (composed; mapped by `accepts[old].value` for an older reader), otherwise it shows `failed { waiting }` naming the
2198
+ registry (`not_served`: `unavailable/undeclared`; `version`: a reader newer than the provider or without a mapping,
2199
+ `contract_mismatch`; `compose`: a first `compose` or the mapping threw; `loading` before the publication), woken at
2200
+ every change of whether the value is usable; `host.registry` waits the same way up to its `readyTimeout`;
2201
+ contributions never fail a registry (a failed one is left out and reported); a throwing `compose` keeps the last
2202
+ good composition (above); `retryOn` retries on value calls only; `host.root(fn, context, { principal? })` seals its
2203
+ context at settle, abort and `host.close`.
2204
+ - **Registries may carry natives.** An entry lives exactly as long as its contributor; consumers look up at each use
2205
+ or follow the composed value and keep nothing from an entry beyond a use.
2206
+ - **Contributions that change (owner, 2026-10-19; W4):** registries are host-local, so contributions are usually
2207
+ in-process values (functions, runtimes, handles). A contribution is fixed for its contributor's life (dynamic parts
2208
+ behind handles read at use; a change means a restart or reload), a `Watchable`, or a `NativeWatchable`; Chord follows
2209
+ the latter two through the internal flush: on every change it replaces that entry (a new immutable table) and runs
2210
+ `compose` again, in the owner's flush, never inside another owner's commit step. The composed value is itself a
2211
+ `NativeWatchable`; use sites watch it or read its current value. For in-process values that change,
2212
+ `self.writable(initial)` is a `NativeWatchable` with `set` (identity compared, never ops, never a state member). An
2213
+ event member is no followed contribution (it is no watchable): contributed, it is a plain value like any other
2214
+ in-process value:
2215
+
2216
+ ```ts
2217
+ const ext = self.writable(mcpExtension([])); // e.g. MCP: tools known only at runtime
2218
+ self.contribute(HarnessExtensions, ext);
2219
+ self.on(mcp.tools, ({ value: tools }) => ext.set(mcpExtension(tools)));
2220
+ ```
2221
+
2222
+ Tools, sections, hooks, wraps and tasks reach the harness as one Durable `Extension` per plugin contributed to
2223
+ p3's core registry; `compose` builds Durable's registry snapshot (Durable applies selection and wraps, and pins a
2224
+ snapshot per task phase). Skills and other lists work the same way.
2225
+ - **A contribution may be another registry's value** (it is followed: its change recomposes). A ring of registries
2226
+ reading each other is caught when one composes (audit A2): a registry read while it composes throws `invalid/cycle`,
2227
+ the contribution that read it is left out and reported `contribution_failed`, the rest of the registry works.
2228
+ - **Removing a contribution:** there is no remove call (`contribute` is declarative, in the factory). An entry leaves
2229
+ the table when its contributor ends, or after a reload whose new code no longer contributes. A live contributor that
2230
+ has nothing to offer for now sets its readable to the registry's empty value (an extension without tools, empty
2231
+ routes); the table keeps exactly one entry per live contributor.
2232
+ - Registries add behaviour (tools, routes, renderers, commands, input gates); they never replace an owner's checks.
2233
+ No lifecycle in entries: anything needing cleanup is a native of the contributing object.
2234
+
2235
+ ---
2236
+
2237
+ ## 18. Start data and platform bindings
2238
+
2239
+ There are no host values. Start data (session id, init, data directory) is a `local` object with empty params (host lifetime)
2240
+ and constant state (`constant(value)`: a readable that never changes, R23), served by the base code's core facet from the start message:
2241
+
2242
+ ```ts
2243
+ export const SessionInfo = local("app.session-info", { version: 1, params: {}, members: { init: InitSchema } });
2244
+
2245
+ // base code (apps/<app>/src): the core facet, passed to load() like any facet
2246
+ export const coreWorkerFacet = (init: Init) => defineFacet((host) => { // base code's own bound defineFacet
2247
+ host.serve(SessionInfo, () => ({ init: constant(init) })); // local, empty params: host lifetime
2248
+ });
2249
+
2250
+ // any plugin
2251
+ host.serve(NoteInbox, (_, self) => {
2252
+ const info = self.get(SessionInfo, {});
2253
+ const watcher = self.open(async (context) =>
2254
+ watchDir(join(info.init.value.dataDir, info.init.value.id, "inbox"), { signal: context.abortSignal }), (w) => w.close());
2255
+ return {};
2256
+ }); // NoteInbox: local, empty params → host lifetime
2257
+ ```
2258
+
2259
+ Plugins read start data through a reference, after activation (in openers, derives, routines and methods); nothing
2260
+ reads it synchronously in a factory. Platform bindings the host owns (a Durable Object's `state` and `env`) are core
2261
+ objects whose `self.open` returns the binding and whose `close` does nothing. A long-lived native from the host is a
2262
+ host-lifetime object in a core facet (the Durable harness, section 24).
2263
+
2264
+ **Core vs. plugin is decided by where the code lives:** base code (`src/`, imported statically by the start code under
2265
+ a fixed name such as `@app/core`, not switchable, a change restarts the host) or a plugin directory (found by listing,
2266
+ loaded through loader D, named by its `package.json`, switchable, a change reloads it). Core is what the app always
2267
+ needs and everything builds on (harness, catalog, access, session location); optional features are plugins (code
2268
+ mode is a plugin). Both use exactly the same primitives.
2269
+
2270
+ ---
2271
+
2272
+ ## 19. Presence
2273
+
2274
+ ```ts
2275
+ const viewers = self.derive([host.references(Notes)], ([refs]) => refs.length);
2276
+ ```
2277
+
2278
+ `host.references(Type)` (slice 4b) is a JSON `Watchable` of the references to objects of a type on this host:
2279
+ `{ params, principal?, incarnation }[]` (named `origin` until 2026-10-27). It is one rule (owner, 2026-10-24): the incarnation of the host that made
2280
+ the reference as its caller sees it, so two tabs are two origins, and a guest's `ctx.get` shows the guest's tab. An
2281
+ entry is added when a reference binds and removed when it ends, in that batch; a departure discovered while a batch
2282
+ is sending lands in the next batch (so one commit stays one message per link). A hold shared by references of one host
2283
+ (§7) is one entry, until that hold ends: a non-final release there removes nothing here; local, `self.get`,
2284
+ private-retry, other-key and separate downstream holds are not deduplicated. The host keeps a type's list from its
2285
+ first `host.references(Type)` on (one small object per asked type; entries come and go with references). **A link drop is a departure**
2286
+ (accurate and simple); smoothing (a phone switching networks) is the UI's job, e.g. a debounced viewer count. Counts
2287
+ per person or origin are derived by the app from the principals and origins. There is no consumer-side linger
2288
+ (a closed tab closes its link); provider-side `linger` keeps a just-closed object warm and keeps the worker alive
2289
+ (section 3). Replaces the presence, viewer and login-abandon leases. "Leaving" is never derived from an unmount
2290
+ (section 21). A holder of an admitted object (slice 14) is listed from its first allow until a denial or its
2291
+ end. Event subscriptions add no presence entries, counts or principals (nor to `host.activity`, nor
2292
+ revocation): a reference is listed once, subscribed or not.
2293
+
2294
+ ---
2295
+
2296
+ ## 20. Input into running work
2297
+
2298
+ ### Flows kept by their owner
2299
+
2300
+ ```ts
2301
+ start({ provider }, ctx) → { id } // uuidv7
2302
+ LoginFlow {id}: state | { kind: "running"; step?: { id, … }; notices } | { kind: "done" | "failed" | "cancelled"; notices }
2303
+ answer({ id, step, value }, ctx) → ok | "step no longer active"
2304
+ cancel({ id }, ctx)
2305
+ ```
2306
+
2307
+ The UI watches the state; a late or second answer to a step that is gone is refused; a promise-based callback (diffra-ai's
2308
+ `prompt`) stays inside the owner (its job keeps the resolver). Imperative consumers (tests, scripts, a CLI, an agent
2309
+ tool) use a generic client helper over the same state, not a second protocol:
2310
+
2311
+ ```ts
2312
+ async function* steps(flow, ctx) {
2313
+ let last = 0;
2314
+ for (;;) {
2315
+ const s = await until(flow.state, (v) => v.kind !== "running" || (v.step && v.step.id > last), ctx);
2316
+ if (s.kind !== "running") return s.kind;
2317
+ last = s.step.id;
2318
+ yield s.step;
2319
+ }
2320
+ }
2321
+ for await (const step of steps(await ctx.get(LoginFlow, { id }), ctx))
2322
+ await login.answer({ id, step: step.id, value: answerFor(step) }, ctx);
2323
+ ```
2324
+
2325
+ A long-held server `step()` call is not used: a link drop fails it and the consumer cannot tell whether it missed a
2326
+ step; state re-holds by itself and `last` keeps steps from being lost or repeated.
2327
+
2328
+ ### The Questions service
2329
+
2330
+ Another pattern (`apps/p2/docs/questions.md`): a shared store with per-principal views (asker: `ask`; viewer: `open`,
2331
+ `answer`), typed questions (`text`, `select`, `confirm`), policies over a live audience (`first`, `quorum`, `all`),
2332
+ reattachment by `key`, deadlines, authorization per question, secrets redacted. Fits tool approval and a question the
2333
+ agent asks everyone present. Its store must live in an object (it predates "natives only in objects").
2334
+
2335
+ > **Decision needed: where a flow lives.** Options: (a) a keyed document of its owner; (b) an object `LoginFlow {id}`
2336
+ > living until done. (Jobs as objects were rejected, §15; a flow kept as its owner's document plus a job is the likely
2337
+ > answer.)
2338
+
2339
+ ---
2340
+
2341
+ ## 21. Reload and rollout
2342
+
2343
+ ### Per host
2344
+
2345
+ `host.reload(facets, context)` (slice 7b; decision "Slice 7b's open points, as recommended" (1)) takes the host's
2346
+ **complete new plugin set** after `load`: a plugin in it and not loaded is added; one loaded with another facet value is
2347
+ changed (Chord compares no code); one passed as the very same facet object is unchanged and untouched (owner,
2348
+ 2026-10-29: base code passes its core facet value every time); one loaded and not in it is removed. It resolves with a
2349
+ report once the commit happened and every object took its fate (a restart reports what its successor's recorded
2350
+ requests found at once, a retry its new attempt's first dependency check; it does not wait for objects to go live); a
2351
+ plugin whose new code fails keeps its old code and is listed in the report's `failed` (per plugin, below).
2352
+ Reloads run one after another per host; before `load` resolved it throws, and so does a plugin set with an invalid
2353
+ name (before anything changes); after `close` it rejects `released/closed`;
2354
+ `context` bounds it (decision 4: no install watchdog): its abort before the commit rejects `aborted` and changes
2355
+ nothing, after the commit it only ends the wait: it rejects `aborted` with `details.committed`, a `CommittedReload`
2356
+ `{ added, changed, removed, failed }` naming what the commit applied (the plugins component adopts it, so a later
2357
+ reload never passes a committed plugin's old facet; owner, 2026-10-30).
2358
+
2359
+ ```ts
2360
+ type ReloadReport = {
2361
+ readonly plugins: { readonly added: readonly string[]; readonly changed: readonly string[]; readonly removed: readonly string[] };
2362
+ readonly failed: readonly { readonly plugin: string; readonly error: unknown }[]; // new code failed: old code kept, an added one left out
2363
+ readonly objects: readonly ({ readonly object: string } & (
2364
+ | { readonly kind: "restarted" } | { readonly kind: "ended" } | { readonly kind: "retried" }
2365
+ | { readonly kind: "parked"; readonly cause: FailureCause }))[];
2366
+ };
2367
+ ```
2368
+
2369
+ ```
2370
+ 1. load new bundles (the app's or loader's: a facet arrives evaluated); a plugin whose build or evaluation
2371
+ fails keeps its loaded facet (`reload(facets, context, { failed })`)
2372
+ 2. staging every new setup into a staged table, and every affected object's new factory against a recording
2373
+ `self` (declarations only, nothing activated, bound or opened); a plugin whose new code throws keeps its
2374
+ old code, staging runs again without it, then the closure rule (below)
2375
+ 3. commit one batch: the host switches to the new code atomically, a publication (7a)
2376
+ 4. after each object takes its fate (below)
2377
+ ```
2378
+
2379
+ - **Per plugin, never all or nothing** (owner, 2026-10-30, decision "Per plugin at startup and reload"; supersedes 7b's
2380
+ rollback per host): a plugin whose new code fails at a reload (its build or evaluation, a setup's or factory's throw
2381
+ in staging, a declaration error, `checkAccepts`, a type or registry served twice, a remote type on a host without
2382
+ principal or address) keeps its old code (its loaded facet, unchanged) and is reported in the reload's report
2383
+ (`failed: [{ plugin, error }]`, the same list `load`'s report has; an added plugin that fails is left out); staging runs again without it, and every other plugin of the reload applies. **The
2384
+ closure rule:** a changed plugin whose recorded requests would not bind because the plugin they need was kept old (or
2385
+ is missing) is kept old too, so a consumer edited together with a broken provider keeps working on its old code. At
2386
+ startup the same holds: `load` leaves a failing plugin out and resolves with `{ failed: [{ plugin, error }] }`; its
2387
+ consumers wait `failed { waiting }`; `load` never closes the host for a plugin (base code decides whether its core
2388
+ failing is fatal). A loader that kept a plugin on its loaded facet because its new code failed before staging (its
2389
+ build, its evaluation) tells the host with `reload(facets, context, { failed })`: the host lists it and applies the
2390
+ closure rule to it as to a plugin whose staging failed. What no rule detects: a consumer relying on new behaviour of a kept provider whose contract did not
2391
+ change (as in a rollout across hosts). Runtime states (registry conflicts, failed opens, migrations) stay per object
2392
+ after the commit (`onError` as always).
2393
+ - **Staging** runs every new setup (each plugin into its own table, merged; an unchanged or kept plugin's loaded
2394
+ entries are reused, its setup not run again) into a staged table beside the live one (types with their factory,
2395
+ `linger` and provider, `bindProvider(contract, options.accepts)`; registry providers; facet contributions by
2396
+ plugin), then, for
2397
+ every live, activating, parked or failed object of a changed or removed plugin whose type is still served, its new
2398
+ factory with the object's params (and principal) against a recording `self`: it records the documents, tables
2399
+ and jobs it declares with their versions, its contributions and requests, runs the checks an
2400
+ attempt makes without effects (declared twice; persisted data outside a stable identity; contributions outside a
2401
+ host-lifetime object; a document or job at an older version, or at its version with another schema), and hands out
2402
+ inert handles (`self.queries`, `self.liveQuery` and `self.count` among them: a recorded `exposes` makes or changes
2403
+ no column-set binding; a column set is checked when a read opens, not by the closure rule). **An admitted type**
2404
+ (slice 14 §2.5): its new `admit` runs against a recording `self` of what an admission declares with; its new
2405
+ factory is rehearsed with the object's current admitted value only when that value was decided under an
2406
+ `admission` schema of the new one's fingerprint. Otherwise (another fingerprint; an object denied, parked or
2407
+ failed) the factory is not rehearsed, a limit accepted: its declaration errors (the refusal of `self.job` among
2408
+ them) appear at its activation, and its requests are outside the closure rule. Staging is
2409
+ synchronous, so no request or arriving hold meets it half done (audit A1: model §1's `installing` is cut).
2410
+ - **The commit** (one batch): the served types become the staged ones (an unchanged plugin's entries stay as they
2411
+ are); a removed plugin's registry provider goes (its readers wait `not_served`), a reloaded one's replaces the old
2412
+ (`RegistryRecord.serve` replaces), the reloaded plugins' facet contributions are replaced by plugin (object
2413
+ contributions follow their objects), every changed registry composes once; a removed type's presence list goes.
2414
+ After the batch, each object takes its fate, host-lifetime objects of new types start (no barrier), and the
2415
+ publication wakes the requests indexed under the names the reload serves (`UnboundIndex.wake(names)`, per name),
2416
+ refused holds of those names re-run their start.
2417
+ - **Fates** (decided in staging; objects of plugins not in the reload are untouched; decision "Reload restarts every
2418
+ affected object; old work finishes on old code", which superseded the pure swap):
2419
+
2420
+ | The object | Fate |
2421
+ | --- | --- |
2422
+ | its type is removed | **ended**: as an end (natives close `end`, callers of running calls rejected `released`, handlers drained, in-memory documents gone, persisted ones kept); its holders' requests are not ended: they wait unbound `not_served` (§7) |
2423
+ | failed, parked, activating or waiting for its backoff | **retried** on the new code (`ref.retry()`'s rule, whatever broke it); an activating attempt is sealed and its natives close `reload` |
2424
+ | live (natives or not) | **restarted** (below): its old attempt serves old work until that drained and its successor's requests are ready, bounded by the reload drain bound; then it is sealed (in-memory job runs end `aborted { reload }`, persisted ones are stopped and resumed, R3), natives close `reload`, and the successor runs its factory and activates (documents stay; eager table migrations run as at activation) |
2425
+ | a restart whose successor's recorded requests find a failure, or a retry whose new attempt waits for a dependency | **parked** (decision 4): reported with the cause; the successor activates once the dependency is there |
2426
+
2427
+ A restarted object gets a new instance id (an old activation chain never matches it); a retried one keeps it as
2428
+ any retry does. An admitted object restarts as any (slice 14): its successor runs the new `admit` while the old
2429
+ attempt drains, then the new factory; a decision change during the drain seals the old attempt at once. A
2430
+ route's admission takes no fate. Cycles are checked again for the new attempts; `parked_long` is unchanged. Live queries are no
2431
+ natives (section 11): the successor's run at its activation.
2432
+ - **Reads across a restart (slice 14 §3.2, §5):** a restarted provider of named queries does not restart its
2433
+ readers: when its old attempt ends (its admitted work settled, before the successor prepares the tables), the
2434
+ reads of its queries leave the store's index and the readers keep their last values; when the successor is live,
2435
+ each reader reads its query for the current arguments and gives one frame, or none when the rows are equal. While
2436
+ the successor creates or migrates a table, every read over it is held. A restarted owner of a table with `exposes` binds the set again once its tables are
2437
+ prepared: while it creates or migrates the table, other owners' reads over it are held, then compile again and
2438
+ run once; a column a read uses that is gone or retyped fails exactly that read (`invalid/args`), and a set exposed
2439
+ no more fails its reads `unavailable` until one serves it. A reader restarted in the same reload opens its reads
2440
+ when the table is ready, showing `loading` meanwhile. A list's bookmarks are its object's, by the list's name:
2441
+ the successor opens the pages the list had, and bookmarks of another order start it again.
2442
+ - **Fates start in the plan's order**, removals first; the restarts' readiness and successors start once every fate
2443
+ started, so the requests they bind meet the new served types only.
2444
+ - **Old work** (decision "Reload restarts every affected object; old work finishes on old code", rule 2): the calls
2445
+ running on an object at the commit and every call they cause. On one host they are found through `ctx`: a method's
2446
+ `ctx` is a node of its call chain (the attempt it runs on, then the chain of the call that made it), so a call,
2447
+ `ctx.get` or root scope given the method's `ctx` (`withoutAbortSignal(ctx)` for a root) is old work while any
2448
+ attempt in its chain drains for a restart. The host counts its draining attempts and the old calls it runs for
2449
+ other hosts, so outside reloads no chain is walked. Across hosts a consumer marks such a call `old` (§22); a
2450
+ provider honours the mark only from a trusted link and runs the call as old work, counted while it runs; a relay
2451
+ drops it from a link that is not trusted (a page cannot claim old work).
2452
+ - **Old work runs on old attempts:** a call of old work on an object whose old attempt is open runs there, with its
2453
+ handles valid; a getter of old work binds that attempt for any version it serves. A getter for a version the new
2454
+ code dropped binds the open old attempt or fails at once (`contract_mismatch`, never a wait for a code update). An
2455
+ object that did not exist starts on the new code; its requests bind open old attempts as any request does (rule 5
2456
+ below). **New work** (anything else) waits at the gate and runs on the new code (bounded by `readyTimeout`,
2457
+ `unavailable/park_timeout`); a parked successor showing `failed { waiting }` rejects it with that cause. A call
2458
+ never gets `not_ready` there: a hold over a link stays bound while the old attempt is open, so its consumer sees
2459
+ `live` and sends; when the hold then leaves the old instance, it tells the consumer `loading` and keeps the calls
2460
+ still in flight: they go on waiting at the gate (§22, decision "Calls in flight survive a `loading` unbind").
2461
+ - **The seal** (rule 3): the old attempt is sealed once its own calls and the old work routed to it drained (a call
2462
+ routed after the drain began joins it) and its **readiness** holds: the requests its successor's factory made in
2463
+ staging, bound once every fate started, are each live, ended, or failed for a reason other than another host's
2464
+ version skew (`contract_mismatch` or `unavailable/version` from a remote provider, kept on `waiting` causes along a
2465
+ chain; it heals when that host's reload lands). Registry requests are not waited for (the old attempt's
2466
+ contributions keep them). All of it is bounded by the **reload drain bound** `reloadDrainTimeout` (a host option,
2467
+ default 5 s, at most `closeTimeout`; the app kit passes `timeouts.reloadDrainTimeout` to the server and every
2468
+ worker): a method still running then is cut `released` and reported `drain_timeout`; long work belongs in jobs.
2469
+ Only after the seal does the successor's factory run, so no new declaration meets old work: old work writes the
2470
+ documents and tables at their old versions, and the successor migrates what it wrote. The readiness bindings and
2471
+ the old attempt's references are released only once the successor's own requests bound (a dependency held only by
2472
+ them never ends, M§3.9); presence lists (§19) never show readiness bindings (they are no consumers of their own).
2473
+ A failed request is shown by the successor while it lasts (new calls get the cause, consumers of the old attempt
2474
+ see the failure) and no longer once it recovered; from the old attempt's end on, the successor's own dependency
2475
+ checks decide what it shows. The version fences stay for calls cut by the seal (R15: a document or table whose version
2476
+ rose throws `released/version` there).
2477
+ - **Consumers meanwhile** (rule 5): a same-host consumer whose version the open old attempt binds sees the object
2478
+ `live` and follows the old instance (its new code may read the provider's old state for up to the drain); a
2479
+ reference or hold of a version only the new code serves shows `loading` until the successor is live. At the seal
2480
+ the old attempt stops being the instance its holders bind (`loading`; a hold waiting for a window slot unbinds);
2481
+ once its admitted commits published it stops changing and the references take their last values from it. When the
2482
+ successor goes live they move to its members by name (one frame from the last value; a member the new variant
2483
+ lacks fails `invalid/member`; §7); internal derives are rebuilt; in-memory documents migrate through `migrate` when
2484
+ the new code declares a higher version; `self.writable` starts at its new initial value (decision 2); `retryOn`
2485
+ sources are re-declared.
2486
+ - **Contributions:** an old attempt with natives withdraws its contributions at the seal (F-b); one without keeps
2487
+ them until its successor is live, which replaces them in one batch, or drops them when the successor fails or parks
2488
+ (F-c). **Routines** stop at the restart; their calls drain with the old attempt's; the successor's start when it
2489
+ goes live.
2490
+ - **Events** (decision "Events: fire-and-forget members"): a restarting object's old attempt emits until its seal, and
2491
+ the holds bound to it get those events; its successor's events go to the holds that bound to the successor (from
2492
+ their binding's counter value: nothing is replayed). A re-exposing object follows its source's restart without
2493
+ restarting: its references move.
2494
+ - **Against a running host data operation** (decision "Documents and table rows can belong to a host"; spec
2495
+ `host-keyed/spec.md` §5): a restarted object's successor (as every activation) runs its load phase (hydration,
2496
+ persisted loads, table preparation, live query loads) through the host data gate: while an import or delete is
2497
+ exclusive it waits, so it loads what the operation committed; an operation waits for the load phases under way. An
2498
+ owner a running import activated for its table history passes the gate before the import becomes exclusive.
2499
+ - **Reload cycles** (rule 6): a wait of old work on an object whose activation waits, through its parked
2500
+ dependencies or the gates its opener waits at, on the old attempt that very work runs on fails at once with
2501
+ `unavailable/reload_cycle`, naming the chain (`app.f(fresh) → app.p`: old work creating an object whose new code
2502
+ needs the raised provider). Checked when the wait starts and whenever an attempt parks or an opener begins waiting
2503
+ at a gate. What leaves Chord (roots opened without the method's `ctx`, Durable tasks, an app's locks) and cycles
2504
+ across hosts end at the reload drain bound.
2505
+ - **Natives are not kept across reloads by name:** natives have no line, transactions or schema, so old and new code
2506
+ would interleave unchecked. In practice a restart costs little (the Durable harness is base code, terminal PTYs live
2507
+ in their own process, model runtimes, sandboxes and the search index rebuild in milliseconds); reloading the plugin
2508
+ that owns SSH connections or the relay socket hurts.
2509
+ - **UI on client hosts** (decision "Slice 11, P4", refined by "Tutorial gaps" (1)): a page or terminal applies a new
2510
+ plugin script with `host.reload`, as any host; the UI re-renders from its registries and keeps what lives outside
2511
+ the changed plugin. A component of a reloaded plugin is a new function, so React (or a terminal scope reopened by the
2512
+ app) mounts it anew and its own state (`useState`) starts over. What must survive a plugin update (a half-typed
2513
+ message, a scroll position) is **page state**: values the client host keeps by key (`usePageState(key, initial)` in
2514
+ `chord/react`, `scope.pageState(key, initial)` on a `TuiScope`, one store per host), any same-host value, never on
2515
+ the wire, untouched by reloads and gone with the page (a page reload, a terminal's new base bundle). Rejected: React
2516
+ Fast Refresh (a Babel or SWC transform in every web build, fragile when hooks change).
2517
+ - **No factory trial, no migrate dry run, no consumer contract check during staging:** staging records declarations;
2518
+ incompatible consumers wait at bind (`failed { waiting }`, `contract_mismatch`); a reference joining a held remote
2519
+ object (§7) is not checked against the provider's new contract while the old attempt still serves its hold. The
2520
+ one exception is the closure
2521
+ rule above: when a plugin of the reload failed, a changed plugin's recorded requests are checked as a bind would
2522
+ check them, to keep it old.
2523
+ - **Start barrier** (host start and first load; dependency model §6, decision (a), slice 7a): `load` runs the facets'
2524
+ setups (the core facet with its start data among them) and **publishes** them in one batch (types served,
2525
+ registries served and composed once, contributions in their tables); requests that waited for the publication are
2526
+ placed after that batch (holds and `host.hold` wait for the publication only, never for the barrier: two hosts
2527
+ whose objects need each other's types start without a deadlock). Then it activates the host-lifetime objects and
2528
+ resolves when each has its **first outcome**: live, failed by its own cause, or parked with no blocker that is a
2529
+ local object still without its first outcome (`local`: executing on this host, a keyed pin still loading here
2530
+ included; a wait on another host or on a failed dependency ends the first pass), or ended (`host.close` settles a
2531
+ waiting `load`). One first-outcome signal per object, separate from the readiness dependents wait for, counted once,
2532
+ never reopened by retries. So `CodeMode → Harness` waits for the harness's outcome. **What it promises:** every
2533
+ host-lifetime object here had its first try, and the contributions of those that went live are in their tables;
2534
+ **not** every tool that will arrive (a parked or slow contributor, tools found in `onLive`, MCP): what a first turn
2535
+ needs is p3's explicit admission check. Base code calls `harness.resume()` after `load` (the harness is an ordinary
2536
+ host-lifetime object that opened Durable paused during the barrier; owner, 2026-10-21, refines R17). Nothing waits
2537
+ for specific contributions: what is missing shows where it is used (section 24). Failed plugins are reported with
2538
+ their error. Reloads need no barrier.
2539
+
2540
+ ### Rollout across hosts
2541
+
2542
+ - **The rollout is the app's** (decision "Slice 7b's open points" (3)): it calls `host.reload` on each host in order,
2543
+ server, then workers, then clients; Chord guarantees per host (staging, commit, a failing plugin kept on its old
2544
+ code). The plugins component's `rollout` (slice 7c) runs such steps. An install never waits for activations (a reverse-order rollout would
2545
+ deadlock).
2546
+ - **Each host knows only its own install** (model §5): until its reload commits (while the app bundles, before
2547
+ `host.reload`), a hold that does not fit its running code is answered `failed { waiting, version }` and the commit
2548
+ wakes it (a blip of at most one install; staging itself is synchronous, audit A1). What a consumer on
2549
+ another host sees follows §7: kept and freshly bound while its version is accepted; `failed
2550
+ { waiting }` (`version`, `not_served`) otherwise, bound again by the install that serves it; a consumer whose own
2551
+ code moves to a new version releases its old request and makes a new one.
2552
+ - **A contract change between hosts in one rollout leaves a gap** (decision "The rollout order stays; no `loading`
2553
+ grace"): a consumer on an earlier step whose provider on a later step moves to a new version waits for the
2554
+ provider's step (server first: server consumers of worker types). A restarting consumer's readiness waits out the
2555
+ other host's version refusal, so its old attempt keeps serving meanwhile, up to the reload drain bound; past it, or
2556
+ for a consumer created meanwhile, the reference waits `failed { waiting }` with its last values. `accepts` cannot
2557
+ close the gap within one rollout (the old provider never serves the new version). The recipe: two applies, the
2558
+ provider first (serving the new version and accepting the old one), then its consumers. Admission sources
2559
+ `accept` their previous version (§6): a refused version is a failed source, which seals its readers.
2560
+ - **The app's loader keeps its own duties:** the desired code set, a digest over the facet bundles' content hashes (an
2561
+ unchanged server restart reinstalls nothing), serialized installs, a host that starts or reconnects installing the
2562
+ current set before anything is routed to it, a rejected own install failing its own requests with the reason.
2563
+
2564
+ ### What a user sees during a reload (owner, 2026-11-04)
2565
+
2566
+ The contract between reload and the people using an app: each row is checked end to end through a real page and a
2567
+ worker (the reload suite), not only by unit tests. "The page" is any client over a link (a browser page, a terminal);
2568
+ "a call" is a method call from it.
2569
+
2570
+ | Change rolled out | What stays on screen | Calls | State |
2571
+ | --- | --- | --- | --- |
2572
+ | a plugin whose new build, evaluation or staging fails | everything; the plugin keeps its old code, the error is reported to the app (a page's own evaluation failure is reported in that page) | unaffected | unaffected |
2573
+ | pure code (no natives) on the server or a worker (a restart) | `live` with the last values (and what the old code still commits) while the old code drains, up to `reloadDrainTimeout`; then `loading` briefly; then a fresh snapshot from the new code | running calls, and the calls they cause on any host, finish on the old code (up to `reloadDrainTimeout`, then `released`); calls arriving meanwhile wait (the provider host's `readyTimeout`) and run on the new code; never `not_ready` | documents and tables unchanged; `self.writable` values start over; in-memory job runs end `aborted { reload }`, their `finish` on the new code |
2574
+ | code holding natives (a restart) | as pure code; the old code's natives close (`reload`) at the seal, the new code's open before the fresh snapshot | as pure code | as pure code; natives reopened |
2575
+ | a contract change the new code still `accepts` | the old page keeps working through the mapping | answered through the mapping | unchanged |
2576
+ | code that serves an admission source (slice 14) | nothing while the source only reloads (the last decision is kept); a successor that fails or parks, or a contract the readers' version does not fit, seals the objects that read it until it heals | rejected `unavailable` on a seal | unchanged |
2577
+ | a contract change not accepted, or a type removed | the reference waits with its last values (`failed { waiting }`) until the page's code updates or the type returns | calls fail at once with the cause (`contract_mismatch`, `unavailable` not served; §7) | unchanged |
2578
+ | a web or terminal plugin | the other plugins untouched, scroll kept; the reloaded plugin's components remount; a page fetches the plugin's new stylesheet inactive before the reload (beside its old one, at most 10 s), applies it with the new code and retires the old one a frame after the reload (a plugin whose new script failed keeps its old stylesheet with its old code, the new one never applied); a remounted reference is live at once if it joins an already live eligible remote object (§7), otherwise it sees that object's loading or failure, or makes a fresh hold; limitation: UI an object contributes stays until its successor is live and can show unstyled during that restart | the reloaded plugin's calls as above | component state starts over; `usePageState`/`scope.pageState` survive |
2579
+ | base code (the app's client and worker entries, Chord, React) | applied by restarting the server (the kit builds the base bundles and each worker kind's worker base right after the server listens; no reload applies them, and a worker forked meanwhile runs the server's boot code); the page reconnects to a new base and reloads (the terminal restarts its sandbox): the only case losing what is on screen | calls in flight end with the link | page state lost; in-memory server and worker state lost; stores unchanged |
2580
+
2581
+ Order: the server, then every running worker by the same rules, then the clients' scripts.
2582
+
2583
+ ### Loading plugins and the reload loop (slice 7c)
2584
+
2585
+ - **No dev/prod split** (owner, 2026-10-30): a Chord app is self-modifying (the owner or an agent edits a plugin while
2586
+ it runs), so finding, building, loading, watching and rolling out plugins is core machinery: one component,
2587
+ `chord/plugins` (`src/node/plugins/`, Node-side; the kernel stays portable and takes facets however they
2588
+ were made: static imports in tests and Durable Objects work the same). Reloads stay explicit: the watcher marks,
2589
+ never applies.
2590
+ - **A plugin** is a directory with a `package.json` (its `name` is the plugin's name, npm style) and one file per facet
2591
+ kind the app names; plugins come from roots found by directory listing (no source parsing; the first root wins a
2592
+ duplicate name). Dependencies between plugins resolve by contract name at runtime; names are prefixed
2593
+ (`<plugin>.<name>`; tools `<plugin>_<name>`). A plugin carries the contracts it was written against (decision "Contracts come from where the
2594
+ plugin's code came from"): plugins that change together import each other by relative path within a root
2595
+ (copied into the importer's script); others take contracts as an npm dependency at a fixed version (built in slice 12,
2596
+ which removed slice 10's imports by plugin name).
2597
+ - **Loader D:** one esbuild script per facet (its own files, copied files of other plugins, its npm `dependencies`
2598
+ inlined; host packages, `chord.external` packages and Node builtins external, passed in at evaluation); each facet kind is defined once, `kinds: { <kind>: { platform: "node" | "browser", hostPackages } }` (slice 11); evaluated with
2599
+ `vm.Script` under a stable filename per (plugin, kind, digest); no module map: old generations are reclaimed by the
2600
+ GC; V8's compilation cache turned off when the component is created. `pluginFile(path)` resolves a file of the
2601
+ calling facet's own plugin. A plugin's dependencies are installed into its directory (`installDependencies`, as
2602
+ coding-agent does: `--omit=dev --legacy-peer-deps --ignore-scripts`). esbuild is an optional peer dependency.
2603
+ - **The reload loop:** a watcher marks plugins dirty from the files each facet used (a copied contract dirties every
2604
+ user) and flags changes of base code (the app restarts its hosts): `base` is content-compared (p3 step 0a), true
2605
+ while a file differs from the bytes a running base artifact read (each base bundle hashes what its loader hands
2606
+ esbuild; the server's own code is recorded after the start by bundling its entry, nothing written or run), is gone,
2607
+ or is a source file new in a base directory; compared once when its watch starts and at each event (reads of one
2608
+ path in order, the latest deciding), so a rewrite with the same bytes or a change and its revert leave no mark. One
2609
+ exception, latched: a file of the server's own code whose timestamps show an edit after the process started is
2610
+ recorded as differing whatever its bytes, since Node may have loaded other bytes than the scan read; it marks `base`
2611
+ until the next restart, even when its bytes are restored (the exact rule: `src/node/app/README.md`, "Plugins"). A build is per plugin (a failed one keeps its old code);
2612
+ `rollout` runs the app's steps in order (server, workers, clients; decision "Slice 7b's open points" (3)). A reload
2613
+ control (a button, a CLI, an agent tool) is the app's. One base bundle per surface (host packages and the app runtime)
2614
+ is an app's startup optimization, the web's in slice 11.
2615
+ - Project plugins, trust, snapshots, scopes and npm/git package installs: `apps/p2/docs/plugin-loading.md` (still the
2616
+ reference for those; not in 7c).
2617
+
2618
+ ### The plugin model (2026-11-01; slice 12)
2619
+
2620
+ Decisions "Contracts come from where the plugin's code came from", "Plugins import only the app's versioned API",
2621
+ "The plugin model, points 3, 4, 5 and 8, imports and builds", "Single-file plugins", "Testing a plugin alone". The
2622
+ rule underneath: a plugin carries what it was written against, never the running app's newest file.
2623
+
2624
+ - **What a plugin may import:** its own files; the app's versioned API (`@acme/app/v3`, never Chord directly: Chord is
2625
+ not a host package plugins may name; the API re-exports the Chord surface the app supports); its npm `dependencies`
2626
+ (bundled at the installed version); other plugins' contract files: by relative path within one repository
2627
+ (`../notes/contract.ts`, the same commit holds both sides), by package name across repositories (`@bob/notes`,
2628
+ `@bob/notes/web`, pinned by an npm version or a git ref `github:bob/notes#<commit>`; a plugin inside a
2629
+ multi-plugin repository through a dependency on the whole repository, by path into it or its `exports`). A package
2630
+ lists the plugins it provides in `chord.plugins` (as diffra's manifest). One facet imports one API version only.
2631
+ - **Versions:** the app lists the API versions it provides; an unlisted one is a build error naming the available ones.
2632
+ The process runs one Chord: an older API version is a layer over today's, re-exporting Chord's compatibility module
2633
+ for its previous API while Chord keeps one; contracts bind through `accepts` whatever Chord runs.
2634
+ - **Split by host kind:** the API has a shared module and per-kind modules (`/v3/web`, `/v3/tui`, `/v3/server`,
2635
+ `/v3/worker`); a plugin's contract files mirror it (`contract.ts`, `contract.web.tsx`, `contract.tui.ts`, ...). A
2636
+ contract file mentions native things only through `import type`. The build checks every import by the file it
2637
+ resolves to: a per-kind file or module only for its kind, a package the kind does not provide refused. A token or
2638
+ `local` contract used on one kind lives in that kind's file. Shared UI between plugins: an imported file (inlined,
2639
+ frozen at the importer's build) or a registry entry (one live instance).
2640
+ - **Base code** is the API modules, bootstrap (hosts, store, components such as `createHttp` and `createWorkers`, which
2641
+ take settings and process values and return facets) and one start-data facet serving process values as core
2642
+ objects. Every implementation, the harness and core registry providers included, is a plugin; the app's own root is
2643
+ required (a failure at startup stops the app).
2644
+ - **Single-file plugins:** `<name>.<kind>.ts(x)` at a root's top, grouped by name, no `package.json`, importing only the
2645
+ API; a directory of the same name replaces it as the same plugin.
2646
+ - **Installs** from git (a branch, tag or commit cloned into a root) or npm. **Builds** are one esbuild call per facet
2647
+ from source (TS, TSX, JS, JSON, CSS, assets and WASM by URL); plugins bring no build hooks.
2648
+ - **`testPlugin(dir, { kind, modules, stubs, start?, principal? }, ctx)`:** the plugin built as in production on an
2649
+ in-memory host and store, its dependencies served by stub facets, contributions to registries collected for the
2650
+ test, the contracts nobody serves listed.
2651
+
2652
+ - **UI reload vs. leaving:** "leaving" is never derived from an unmount, only from explicit navigation or presence (a
2653
+ dropped reference); a component unmounted by a reload has not left.
2654
+
2655
+ > **Decision needed: project plugins.** Per-directory plugins with trust and snapshots (`plugin-loading.md`) need their
2656
+ > own pass over this design.
2657
+
2658
+ ---
2659
+
2660
+ ## 22. Wire
2661
+
2662
+ Exposed documents, derives and readables are state members: a snapshot in `bound` when a hold binds, ops per commit
2663
+ (a draft's recorded ops, no diff), ops from diffs for derives, ops of job state documents (slice 5), and failed
2664
+ members in the entry of the message that carries them. **Commits are atomic for consumers:** locally, subscribers are
2665
+ notified once after every document of the commit is adopted; remotely, one `state` message per commit per link and
2666
+ origin carries an entry per touched hold, applied in one batch before listeners run (also when one Durable commit
2667
+ touches several holds), so remote consumers never see a torn commit. Consumers apply ops with `applyImmutable`: no
2668
+ validation, no clone of snapshots or ops.
2669
+
2670
+ - **The protocol version** travels in `hello`; hosts of different versions refuse each other (a web page reloads for
2671
+ a newer server). Error reasons and message kinds are part of it. Until p3 ships, changes keep `PROTOCOL_VERSION` 1
2672
+ (nothing is deployed); after that every message or reason change bumps it.
2673
+ - **One typed `Message`** (owner, 2026-10-22, "Wire protocol"): a diffra-schema schema `MESSAGE`, a tagged union over
2674
+ `kind`, from which the protocol types derive; every decoded message is checked against it (compiled once) unless
2675
+ the link is trusted (section 3). Kinds:
2676
+
2677
+ | Kind | Direction | Fields |
2678
+ | --- | --- | --- |
2679
+ | `hello` | both, first | `protocol`, `incarnation`, `calls?` (the call window N; absent: none, a trusted link's; the binary codec writes 0) |
2680
+ | `hold` | to provider | `origin?`, `hold`, `type`, `version`, `fingerprint`, `params` (part), `address`, `principal?`, `incarnation?`, `chain?` (activation chain, Q5), `limit?` (decoded size limit, 4b) |
2681
+ | `revoke` | parent to child (route link) | the revocation value (4b) |
2682
+ | `release` | to provider | `origin?`, `hold` |
2683
+ | `retry` | to provider | `origin?`, `hold`, `hops` (the retry's hop budget, 1-16: 16 from the first host, one less for each host it passes on from, none sent at 0; audit A5); relays forward it unchanged |
2684
+ | `call` | to provider | `origin?`, `call`, `hold`, `method` (index), `args?` (part; absent: no arguments), `segments?`, `old?` (`true`: old work of a reload, §21) |
2685
+ | `abort` | to provider | `origin?`, `call` (named `cancel` until 2026-10-27) |
2686
+ | `ack` | to provider | `origin?`, `events?`: without `events` one per applied `bound`/`state` message; with `events` (at least 1) the `event` messages of the origin consumed since the last such ack, never combined with a state ack |
2687
+ | `closed` | relay to provider | `origin`: the downstream origin ended |
2688
+ | `bound` | to consumer | `origin?`, `holds: [{ hold, variant, members: [{ member, value }], failed }]`; one batch |
2689
+ | `state` | to consumer | `origin?`, `holds: [{ hold, members: [{ member, ops }], failed, retired }]`; one batch (`retired`: members retired since the last message, slice 6a) |
2690
+ | `failed` | to consumer | `origin?`, `hold`, `cause { kind, error }` (`kind`: `transient`, `broken`, `waiting` (slice 7a) or `denied` (slice 14)), `retryIn?` (a transient cause's backoff; absent: broken, waiting); each new cause of a parked object is a message of its own |
2691
+ | `loading` | to consumer | `origin?`, `hold`: a new attempt after a failure, or a relay's upstream dropped |
2692
+ | `result` | to consumer | `origin?`, `call`, `value?` (part; absent: `null`), `segments?` |
2693
+ | `error` | to consumer | `origin?`, `call`, `error` (a ChordError's JSON or a plugin's code, message, details) |
2694
+ | `gone` | to consumer | `origin?`, `hold`, `error`: the held object ended (revocation 4b; a reload never ends a hold, it unbinds it with `failed`, slice 7b; relays never make one) |
2695
+ | `ping`, `pong` | both | the heartbeat |
2696
+ | `event` | to consumer | `origin?`, `events: [{ hold, member, at, value }]` (decision "Events: fire-and-forget members"): `member` an index into the bound variant's event members (sorted, as state members and methods), `at` an integer, `value` a part; one per event flush per link and origin, possibly empty (a relay's filtered one) |
2697
+
2698
+ A `bound` on a hold that is bound already replaces its replicas in one batch, another variant allowed (re-holds,
2699
+ slice 7b's restarted objects, another variant included).
2700
+ - **Codecs are pluggable per link** (both ends use the same): `binaryCodec` (default: a kind byte with a flag for a
2701
+ following origin varint, varints, raw incarnations and fingerprints, length-prefixed strings and parts; about 23 B
2702
+ for a streamed token) and `textCodec` (Delta-style JSON tuples without field names, a message with an origin wrapped
2703
+ as `["@", origin, tuple]`; for debugging; `describeMessage` prints any message so). Measured: a 2,000-token reply
2704
+ about 46 KiB instead of 196 KiB. No CBOR (revisit only if benchmarks show encoding as a bottleneck). Events: the
2705
+ binary codec adds the kind `event` (a count, then per entry hold, member and `at` as varints and the value as a part:
2706
+ 67 B for one paddle sample) and flags an event `ack` in the kind byte (`0x20`, its count following, so a state ack
2707
+ stays one byte); the text codec writes `["E", [[hold, member, at, value]…]]` (wrapped with its origin as any message)
2708
+ and `["a", events]`. Every bound hold receives all its variant's events (no subscription message); a consumer
2709
+ without listeners drops them on arrival, unparsed.
2710
+ - **Parts are opaque** (slice 4a): `params`, `args`, `value`, snapshot values and ops are a `Part` (JSON text at the
2711
+ origin, its UTF-8 bytes once a binary codec received it). A part is parsed only where it is owned, right when its
2712
+ message is handled (the provider parses params and arguments, the consumer results, snapshots and ops), so a relay
2713
+ forwards it unparsed and a malformed part is still a protocol error. A message naming an unknown id is ignored
2714
+ before its parts are parsed. The text codec re-serializes parts at decode (one parse per part per hop, accepted for
2715
+ a debugging codec).
2716
+ - **Names travel as indexes** into the hold's bound version (each variant's state members and methods sorted; variants
2717
+ sorted). A reload that no longer accepts that version unbinds its holds first (`failed { waiting }`, slice 7b).
2718
+ **Bindings are fenced per acknowledgement** (slice 14: an admission may rebind a hold several times before the
2719
+ first `ack`): a hold keeps one fence per unacknowledged `bound` and decodes a call by what its consumer had
2720
+ applied when it sent it, the names before the oldest `bound` it has not acknowledged; a call sent after the
2721
+ consumer was told a failure is refused with it. A fence goes with the `ack` of its `bound`, so a consumer that
2722
+ only reads state keeps none. A consumer that receives `failed { denied }` drops the hold's
2723
+ replicas. **Every call made before its caller learnt of the denial is answered `forbidden/revoked`** (owner,
2724
+ 2026-11-15): in flight, still waiting for a call-window slot (at the consumer, or at a relay for its upstream
2725
+ window), or crossing the `failed` on the wire; whether it had got a slot is congestion, not access. A call first
2726
+ made after the denial meets the denied reference and gets its plain `forbidden`. `PROTOCOL_VERSION` stays 1.
2727
+ - **Checks by layer:** the codec's structural decode, the `MESSAGE` envelope (skipped on trusted links), the bound
2728
+ version (ids, indexes, order), then the owners (`checkParams`, `checkArgs`, Delta's decoder).
2729
+ - **Unknown ids are ignored on both sides (Q1):** they are normal races (a `result` crossing an `abort`, a `call`
2730
+ crossing `gone`, a state part crossing a `release`); the side that ended a hold or call settles its own pending work
2731
+ (a consumer receiving `gone(h)` rejects its pending calls on `h`; per-direction order guarantees nothing else for `h`
2732
+ follows). Protocol errors close the link and are reported (`protocol_error`): a message failing the schema or the
2733
+ codec, a malformed part, a reused live id, more than N running calls of one origin, a broken handshake (a first
2734
+ message that is no `hello` of the link's codec, a second `hello`, another protocol version).
2735
+ - **Byte segments:** a payload (arguments, a result) whose method's schema has a `bytes()` leaf carries each
2736
+ `Uint8Array` as a raw segment referenced by `{"$bytes": i}` and read back as a view of the received message; `$bytes`
2737
+ is the one reserved key there (`invalid/args`). Never base64. State is JSON only.
2738
+ - **Encoders:** each member of a hold has its own Delta encoder and decoder (path interning end to end between
2739
+ provider and consumer), restarted with every snapshot. Two holds of the same principal (two tabs) encode the same
2740
+ ops separately (O(change) each). A part is encoded once at its origin; relays never re-encode it.
2741
+ - **Sending:** one `state` message per commit per link and origin while the window has a slot; otherwise the ops wait
2742
+ in the members' pending queues and leave as one message when an `ack` frees a slot, or before a call's `result` or
2743
+ `error` of that origin, past the window (section 3, "a call's answer follows its state"; a relay sends its own before
2744
+ each answer it forwards). No message kind or field changes. Events go at the event flush (section 11), within the
2745
+ origin's event window (section 3); a consumer consumes an `event` message once its parts are inflated and parsed and
2746
+ its entries delivered or deliberately dropped (no listener, an unknown or released hold, a part over the limit) and
2747
+ acknowledges it then (`ack { events }`); an index outside the bound version is a protocol error. A value nothing
2748
+ listens to (an unknown hold, one not live, a member without subscriptions) is dropped unopened: neither inflated
2749
+ (the consumer resolves the index and the interest before it schedules an asynchronous inflate) nor parsed.
2750
+ - **Relays** read and rewrite only envelopes (section 3, "Relays").
2751
+ - **Size limits per part (R2, Q2; slice 4b):** limits apply to each part (an event's value too: an oversized one is
2752
+ dropped where it is parsed and counted, its hold stays bound), configurable per
2753
+ link, checked from the part's length before it is parsed or inflated; the decoded limit is enforced in the one
2754
+ decode function. An oversized part fails only its own hold or call (`too_large/part`); the other parts of the message
2755
+ apply; a snapshot over the limit fails its hold with no automatic re-hold. A reference joining a shared remote object
2756
+ (§7) receives no snapshot and checks none (a value grown past the limit by small deltas does not fail it); an
2757
+ oversized snapshot or state part fails the shared object and all its references; only a reference that retries moves
2758
+ to a new private hold. No message, codec or protocol-version change; the per-hold encoder and two-tab rules stay. The decoded limit travels with relayed
2759
+ work: the relay checks the admitting link's wire limit itself and stamps its decoded limit on the upstream `hold`
2760
+ (honoured on the parent link only, never taken from a client; calls inherit their hold's), and the host that
2761
+ inflates enforces the smaller of its own and the stamped one while inflating, after the part's owner and id are
2762
+ known (parts for unknown ids are never inflated, Q1). A relay checks only what arrives from downstream; answers
2763
+ from upstream (the app's own workers) it forwards unchecked and unparsed, and the end that parses them checks them
2764
+ against its own link's limits (owner, 2026-10-24: each end checks what it parses; a relay check needed a re-hold
2765
+ with the same id, which old messages in flight could mistake for the new hold). So IPC carries no limit of its own.
2766
+ A reference failed `too_large/part` is never held again automatically: it leaves its path, so a reconnect does not
2767
+ hold it; only `ref.retry()` puts it back (a new hold). This lives only in the consumer's memory, as long as the
2768
+ reference. The
2769
+ WebSocket's `maxPayload` stays only the transport's hard cap (e.g. 64 MiB; code 1009 closes the connection).
2770
+ Defaults for client WebSockets: 16 MiB on the wire and 64 MiB decoded per part; none on IPC.
2771
+ - **Compression at the origin** (owner, 2026-10-19; slice 4b): a JSON part above a threshold (e.g. 16 KiB) is
2772
+ compressed once by a host with a synchronous compressor when it encodes it (`createHost({ compression })`, Node's
2773
+ zlib adapter in a Node-only subpath), whatever the link (IPC included), only if it shrinks (an event's value too,
2774
+ encoded once per representation for every hold and link); hold params are never
2775
+ compressed; byte segments stay raw; the codec is in the part's envelope (the text codec tags every part, so no JSON
2776
+ value is reserved); relays forward it compressed; the end that owns it inflates it. Option (b) (owner, 2026-10-24):
2777
+ hosts without a compressor (browsers) send uncompressed and inflate asynchronously (`DecompressionStream`), holding
2778
+ later messages of that link in order (bounded by the window and N; acks go out after apply). **Child links refuse
2779
+ compressed parts** (protocol error): honest clients never send them, and a 65 KB part could inflate to 64 MiB on the
2780
+ server; so asynchronous inflate happens only on a host receiving from its parent or a route. Because a host cannot
2781
+ tell whether its parent sees it as a child (a tab) or over a route (a worker), call arguments sent up a parent link
2782
+ are never compressed; results and state going up are. Compressed hold params are a protocol error on every link.
2783
+ The asynchronous inflate runs one part at a time; the queue behind it is bounded by the sending peer's window and N,
2784
+ so only a misbehaving parent or route peer could grow it (accepted: those are the app's own hosts). The adapter reports "too large"
2785
+ and "corrupt" as a tagged result. Limits and the threshold count bytes. No per-link compression.
2786
+ - **Trace carriers (R5; slice 9)** are an optional field `trace` of `call` and `hold`: an adapter's string record of at
2787
+ most 8 keys, keys and values of at most 256 characters of printable ASCII (keys without spaces; W3C's headers and
2788
+ Chord's adapters fit); past the bounds, with a control character or not a string record, the message fails `MESSAGE`
2789
+ as any malformed header and the link closes (a trusted link skips the check; the adapter's `extract` then checks it).
2790
+ A carrier names stored trace and parent ids, so no control character reaches a renderer (and `renderTrace` escapes
2791
+ them anyway). Names a relay records unparsed are bounded the same way: a hold's `type` and its address's `kind` have
2792
+ at most 256 characters. The
2793
+ binary codec flags it in the kind byte (`0x40`, beside the origin's `0x80`) and writes it as JSON after the origin;
2794
+ the text codec writes it as the last element (a hold's after `limit`, absent ones before it `null`; a call's after its
2795
+ payload, whose two fields are then positional, `null` when absent). Relays read it from the envelope and forward
2796
+ their own span's carrier (a relay recording nothing forwards it as it came). `PROTOCOL_VERSION` stays 1.
2797
+ - **Old work across hosts** (decision "Reload restarts every affected object; old work finishes on old code"): a
2798
+ consumer marks a `call` `old: true` when its caller is old work of a reload on its host (§21); the provider honours
2799
+ the mark only from a trusted link (it runs the call on open old attempts, as old work of its own host while it
2800
+ runs) and ignores it otherwise; a relay drops it from a downstream link that is not trusted. The binary codec flags
2801
+ it in the call's kind byte (`0x20`; on any other kind that bit makes an unknown kind); the text codec writes it as a
2802
+ call's seventh element, after the trace carrier (`null` when absent). `PROTOCOL_VERSION` stays 1.
2803
+ - **Adapted bindings get diffs** (slice 7b; decision "References are the only indirection" (5)): a consumer bound
2804
+ through `accepts` attaches to the object instance's shared mapping for its version: per member one derive of the
2805
+ instance's member through `(current) => old` (a changed member), of its whole state (a removed member), or the
2806
+ member itself (unchanged), made on first use, dropped when no reference of that version is left, gone with the
2807
+ instance; one map and one diff per commit per version whatever the number of old references, each hold encoding its
2808
+ own ops, so an old tab never receives a large state whole on every commit. A new instance (a reload) has its own
2809
+ mappings; the references move to them as to any new instance (one frame, never a new mapping applied to the old
2810
+ instance's values). A version the instance does not accept gives no member: the reference waits unbound with its
2811
+ last values.
2812
+ - **A `failed` on a bound hold unbinds it** (slice 7b, model §5): the consumer applies it as a start-over plus the
2813
+ failure (its calls waiting for a slot reject with it; the provider rejects its calls in flight once); the provider
2814
+ detaches the hold's sources, drops its unsent pending ops and a queued `bound`, and keeps the ack slots of `bound`
2815
+ and `state` messages already sent until their `ack` or the link's loss. A reload sends it when the object's type is
2816
+ removed (`not_served`), its version is no longer accepted (`version`), or a restart's successor parks on a failed
2817
+ dependency; a restart (once its old attempt no longer serves the hold's version) or a live failure already retrying
2818
+ sends `loading`; both are followed by a fresh `bound` when the object is live again (applied as a re-binding; a
2819
+ tab's watchers may get a frame for an unchanged member).
2820
+ - **A `loading` unbind keeps the calls in flight** (decision "Calls in flight survive a `loading` unbind"): the
2821
+ provider unbinds the hold as above but rejects none of its calls, and the consumer keeps them (only its calls still
2822
+ waiting for a slot reject `unavailable`). Each kept call gets exactly one answer from what it already waits on: the
2823
+ instance it runs on (its result within the drain, else `released` at the seal) or the gate (the new instance's result, the parked
2824
+ cause, `unavailable` after `readyTimeout`, the object's end); an `abort`, a `release`, `gone` or the link's close
2825
+ ends it as any call. Until its fresh `bound` is sent the hold takes calls by the names it was bound with (sent before
2826
+ its consumer learnt of the `loading`): they wait at the gate too, never `not_ready`; after a `failed` it takes none.
2827
+ The kept call runs by name: a method the new variant lacks fails `invalid/member`; a version the new code no longer
2828
+ binds unbinds the hold (`failed`, `contract_mismatch`), which rejects its calls before the gate lets them run. Kept
2829
+ calls hold their call-window slots meanwhile. A relay forwards `loading` and keeps its forwarded calls (its own
2830
+ `loading` after an upstream drop rejects them first).
2831
+
2832
+ ---
2833
+
2834
+ ## 23. Optional components
2835
+
2836
+ The app kit's Node components (slice 10, `slice-10.md`, decision "Slice 10's points"): `chord/http` and
2837
+ `chord/workers` in `src/node/`; the web page host and the TUI are slice 11. Each is ordinary code on Chord's
2838
+ public API; nothing in the kernel depends on them.
2839
+
2840
+ ### HTTP (`@diffra-ai/chord/http`)
2841
+
2842
+ The core is one Web-standard handler built from the registry `Http` (decision "The HTTP core is a fetch handler"):
2843
+
2844
+ ```ts
2845
+ const http = createHttp(server, { // settings are arguments, fixed for the component's life
2846
+ listen: { host: "127.0.0.1", port: 8788 }, // Chord's own Node listener; none: the app mounts `fetch`
2847
+ links: { path: "/chord", options: (request, principal) => ({ limits, maxPayload }), opened: (request, principal) => onClosed },
2848
+ closeTimeout: 30_000,
2849
+ onError, // HttpError
2850
+ }, ctx);
2851
+ await plugins.load(server, { kind: "server", core: [{ name: "chord.http", facet: http.facet }, appCore], modules }, ctx);
2852
+ // an app with its own server: hono.all("/*", (c) => http.fetch(c.req.raw, { localAddress, localPort, remoteAddress }))
2853
+ // plain Node: nodeRequest(message, res) converts with the listener's checks; server.on("upgrade", http.upgrade)
2854
+ await http.close(ctx); // before host.close: drains running requests
2855
+ ```
2856
+
2857
+ - **The facet** (plugin `chord.http`, passed as the same object at every reload) serves the registries `Http`
2858
+ (`compose` builds the router) and `Authenticators`, and with `listen` the listener: a host-lifetime object whose
2859
+ native is Chord's Node server, opened right after `load`'s publication, so a reload never closes it (decisions "The
2860
+ HTTP server is a native object", "Settings are arguments, extensions are registries"). `fetch` resolves the
2861
+ registries once; requests before the host's `load` answer 503 at once (`host.registry` throws `not_ready` then).
2862
+ - **Contributions to `Http`:** `{ routes?, wraps?, sockets?, maxPayload?, hosts?, framers?, relays?, csp? }`, a value
2863
+ or a writable (a change recomposes the router). A request uses the router as it was when it started.
2864
+ - **The security baseline** (decision "The HTTP component's security baseline", on for every request and upgrade
2865
+ before any plugin code): (1) **provenance**: local only when the connection's local address is loopback, `Host` is
2866
+ a loopback name with the port and no `Forwarded`/`X-Forwarded-*` header; a forwarded request on loopback only
2867
+ through a contributed relay whose `verify` names its origin (`{ kind: "relayed", relay, origin }`); otherwise only a
2868
+ contributed host (https); duplicate or missing `Host`, userinfo in it, absolute-form targets: 403; an unparsable
2869
+ target 400; `TRACE`, `TRACK`, `CONNECT` 501 (a route for them is refused at compose). A mounted handler without
2870
+ `localAddress` and `localPort` is never local. (2) **Foreign requests** (Fetch Metadata) never reach the
2871
+ authenticators: anonymous, except a top-level `GET` navigation to a `page: true` route. (3) A foreign `Origin` is
2872
+ 403; an unsafe method from a browser needs the app's own `Origin`; a `crossSite: true` route opts out and always
2873
+ runs anonymous. (4) **Default headers** on every answer, the component's own included: `no-store`, `nosniff`,
2874
+ `no-referrer`, `X-Frame-Options: DENY` (without framers), a CSP (`default-src 'none'`, scripts `'self'` and a
2875
+ per-response nonce `request.nonce`, `connect-src` self and its WebSocket, `frame-ancestors` the framers or
2876
+ `'none'`, plus contributed `csp` sources); a response's own headers replace same-named ones. (5) `cookie(name,
2877
+ value, { secret, request, sameSite?, maxAge? })` and `readCookie(request, name, secret)`: `HttpOnly`, `Path=/`,
2878
+ `SameSite=Strict` or `Lax`, `Secure` on a remote origin, value and expiry signed. (6) `bytes` refuse foreign
2879
+ requests, are attachments unless `inline` (then with a `sandbox` CSP), download names stripped of control and
2880
+ bidirectional characters.
2881
+ - **Who:** the `Authenticators` registry, in contributor order (an app needing precedence contributes one that
2882
+ decides); the first principal wins, a throwing one is reported and skipped, none: anonymous. They run raced against
2883
+ the request's signal and stop once it aborts. Who someone is stays app policy (D3); the registry replaces D3's
2884
+ single function so plugins (a device pairing, a share) can add credentials.
2885
+ - **A request's scope:** one `host.root` with its principal (an explicit `undefined`: anonymous; an anonymous scope
2886
+ gets no remote object served here, `forbidden` → 403) spans matching, wraps, the route and the response until its
2887
+ body is written or abandoned; its signal aborts on disconnect. `HttpRequest`: `method`, `path`, `params`, `query`,
2888
+ `headers`, `origin`, `provenance`, `nonce`, `json(limit?)` (1 MiB; 400, 413), `body(limit?)`.
2889
+ - **Patterns** (D8): exact segments, `:name`, a trailing `/*`; decoded segments with `/`, `\`, NUL, `.` or `..` are
2890
+ 400; the most specific match wins segment by segment; a pattern from two contributions is a reported conflict, the
2891
+ first by plugin name wins; `HEAD` falls back to `GET`; no route: 404. A route is a function or `{ handler, page?,
2892
+ crossSite? }`. Wraps (D2) as below.
2893
+
2894
+ ```ts
2895
+ type HttpResponse = { readonly headers?: Readonly<Record<string, string | readonly string[]>> } & ( // D5
2896
+ | { kind: "json"; value: JsonValue; status?: number } | { kind: "html"; body: string; status?: number }
2897
+ | { kind: "bytes"; mime: string; size?: number; read(offset, length, ctx): Promise<Uint8Array>; download?: string; inline?: true; ranges?: boolean }
2898
+ | { kind: "redirect"; to: string; status?: 302 | 303 | 307 } | { kind: "error"; status: number; message?: string });
2899
+ ```
2900
+
2901
+ `bytes` are pulled in 256 KiB reads as the consumer reads (ranges 206/416, `HEAD`, chunked without `size`, R6); no
2902
+ read starts once the request's scope is sealed; a short or throwing read destroys the connection. 204, 205 and 304
2903
+ carry no body. `fileResponse(path, { download?, inline?, ranges?, mime?, root? })` stats at once (missing: 404; with
2904
+ `root`, a real path outside it: 403), opens its handle at the first read, closes it when the scope seals. A throwing
2905
+ route or wrap is a 500 without its message.
2906
+
2907
+ ```ts
2908
+ type Wrap = {
2909
+ name: string;
2910
+ phase: "observe" | "headers" | "transform"; // the component's phases, outermost first
2911
+ scope?: "own" | "all"; // default "own": only this contributor's routes
2912
+ route?: string; // only this route; a missing route is a reported conflict
2913
+ wrap: (req, next, ctx) => Promise<HttpResponse>;
2914
+ };
2915
+ ```
2916
+
2917
+ Wraps (D2) run within a phase in contributor order (no numeric priorities: plugins have no single registration
2918
+ order; Fastify's lifecycle phases and encapsulation are the model). Wraps may add a security boundary on top of a
2919
+ route's checks, never instead of them.
2920
+
2921
+ - **Sockets** (D6): `sockets: { "/terminal/:id": (socket, request, ctx) => … }`, a `ws` WebSocket after admission
2922
+ and the authenticators (no principal: 403 before plugin code), `maxPayload` per contribution (1 MiB), pinged after
2923
+ 15 s of silence and terminated 15 s later. **Links:** `links.path` upgrades to `host.accept(webSocketLink(socket), {
2924
+ principal, limits })`; a client that stops reading is cut off past 4 MiB waiting; `links.opened(request, principal, close)`,
2925
+ when given, hears each link opened (`close()` terminates it at once, as a revocation does) and may return what to
2926
+ call when it closes (the kit counts an ephemeral sign-in's
2927
+ links with it; a throw is reported as the hook `links.opened`). **What is removed is closed at
2928
+ once** (decisions Q6, "allowed hosts only through contributions"): a link or socket whose host, relay or socket
2929
+ handler leaves the router is terminated and its scope sealed; an upgrade is checked again against the current router
2930
+ after its authenticators answered.
2931
+ - **`close(ctx)`:** new requests and upgrades refused (503), sockets and links closed (1001, terminated at
2932
+ `closeTimeout`), running requests waited for up to `closeTimeout`, then sealed; before `host.close`.
2933
+ - **Cost** (decision "a route's overhead accepted"): +20-21 µs per request over a plain Node handler (standard bench),
2934
+ +12-13 µs warmed. `ws` is an optional peer dependency (D7).
2935
+
2936
+ ### Workers (`@diffra-ai/chord/workers`)
2937
+
2938
+ `await createWorkers(host, Kind, { kind, entry, execArgv?, env?, authorize, admit?, principal, start, lock, idleMs?,
2939
+ store, plugins, onOutput?, onError }, ctx)` (`admit`: the route's admission, passed through, slice 14: no worker starts
2940
+ for a principal it does not allow; `store`: the server host's, required, `undefined` only without one, see "A
2941
+ worker's exit" below) bundles the kind's worker base, then routes `Kind` itself (`host.route`, keeping its
2942
+ `RouteHandle`): a forked worker per address over IPC, the link made at the fork, a start message `{ address, start,
2943
+ scripts, lock }` with the app's start data and the kind's complete current scripts (`plugins.scripts(kind)`); the 60 s
2944
+ start timer covers fork, lock and connect only (Q4). `workers.state` (a JSON watchable per address key), `inputs`,
2945
+ `stop`, `retry`, `step(name)`, `close`; `workerMain(fn, { hostPackages, redact, onError })` is the child's side
2946
+ (`fn({ address, start, parent, plugins, onClose }, ctx)`, `plugins` a `WorkerPlugins` evaluating the shipped scripts,
2947
+ closers in reverse order). One live worker per address (`processLock`: an abstract socket on Linux, a named pipe on
2948
+ Windows, a socket file elsewhere that fails closed when stale, the stale file cleared by the component before a start
2949
+ and after a child's exit by a signal, decision "Stale lock files are cleared by the starter"; a start waits for a
2950
+ draining old holder without polling).
2951
+
2952
+ - **The worker base** (decision "Workers start from the base code the server booted with"): `entry` and the base code it
2953
+ imports are bundled once by esbuild at `workers.build()` (the kit: right after the server listens, as it builds the
2954
+ surfaces' base bundles; a start waits for it; `built.inputs`: the files read), and every worker of the kind is forked
2955
+ from that snapshot: an edit of the app's source after the build (an agent half way through a change) reaches no
2956
+ worker; a server restart applies it (the kit gives the inputs, each with its bytes' hash as the build read it, to the
2957
+ watcher's `base` mark). A base that does not build fails every start of the kind (the kit reports it as `base_build`;
2958
+ the server runs on). What it holds: the app's files and workspace
2959
+ packages linked into `node_modules` (by their real paths); external, loaded by Node at each fork from where the build
2960
+ resolved them: Node builtins and every package resolved under a `node_modules` directory (native addons and packages
2961
+ reading their own files work as installed; they change only through an install, which needs a restart anyway).
2962
+ Resolution as the child's Node does it (its `execArgv` `--conditions`, `main` only, `tsconfig.json` paths as esbuild
2963
+ reads them); every imported module runs (`sideEffects: false` drops nothing); `import.meta.url`, `.dirname`,
2964
+ `.filename`, `__dirname` and `__filename` name each module's source file. Split at each dynamic `import()` with a
2965
+ literal specifier: the entry and the chunks it imports statically load at each fork, a lazily imported module and the
2966
+ packages it imports only when the worker first imports it (an app's lazily loaded providers stay lazy; a module still
2967
+ runs after its imports, but modules that do not import each other may run in another order than unbundled); a
2968
+ variable-specifier import resolves at run time against its module's source file, outside the snapshot. ES modules,
2969
+ each with its source map beside it (`<name>.mjs.map`, linked), forked without `--enable-source-maps`: Node would
2970
+ parse the whole map at the first stack made text (Chord makes a kept error's stack text at once), about 1M positions
2971
+ and 50 MiB of a p2 session worker's heap for its life; stack traces name the bundle's files and functions, and an app
2972
+ that wants them mapped passes the flag in `execArgv`, at that cost. `execArgv` and `env` apply to every fork as before (modules an `--import` names load from disk at each fork).
2973
+ The files live in one private temporary directory (0700, written again into a new one when a cleaner removed one of
2974
+ them), removed at `close`. The worker's side alone is `@diffra-ai/chord/workers/child` (`workerMain`,
2975
+ `processLock`): a worker entry importing it loads no esbuild. Plugins are unaffected: workers evaluate the server's
2976
+ built scripts. Cost: a build at start (the kit's test worker 55-100 ms, p2's session worker 215-250 ms, 4.2 MB of
2977
+ code); a fork then loads the entry and its static chunks (the kit's test worker 60 ms instead of 360 ms from source,
2978
+ p2's 350 ms instead of 760 ms; on a phone, splitting and the child entry took p2's fork from 690 to 301 loaded
2979
+ modules, no provider SDK or esbuild among them, about 300 ms less to `workerMain`).
2980
+ - **Keep-alive** (D9, R3, Q5): the child reports when `host.activity`'s references, jobs and lingering objects and the
2981
+ app's `busy` counts flip between all zero and not (local calls do not count; the first state with `ready`, which
2982
+ also carries the load report); the server stops a worker idle for `idleMs` (5 min).
2983
+ - **Never restarted by itself** (R2): a crash, a `fatal` or a failed start leaves the address failed; its holders see
2984
+ `failed { waiting }` and stay on the path (Q1); `retry(address)` or a rollout reaching workers clears it and starts
2985
+ the held ones (Q2). `stop` suspends the address while it has holders (R1, Q3). A running worker's lost link (killed
2986
+ after a 5 s grace) is a stop its holders start a new worker after (`worker_link_lost`); a second within a minute of
2987
+ the last recovery fails the address (`worker lost its link`; decision "A lost worker link is recovered from").
2988
+ - **A worker's exit** (decision "A worker's exit is published after its link's work ended", 2026-11-15): when a
2989
+ worker process exits, its link is closed first (what it sent and was not handled yet is dropped; the calls it made
2990
+ are aborted, so a transaction under a call's `ctx` not yet at its commit is refused), then the commits those calls
2991
+ had already queued in the server's store settle (`store`, a required option; the kit passes its own), and only
2992
+ then the exit shows in
2993
+ `state` and the address's next start goes on. Nothing an exited worker reported is handled or lands after `state`
2994
+ says it is gone: **a plugin needs no stale-worker check of its own.** Not covered: a call the server relayed to
2995
+ another host (cancelled there when the cancel arrives) and work started outside the call's `ctx`. A running
2996
+ worker's `state` entry carries its `incarnation` (its host's, the `ctx.incarnation` of its calls) from its link's
2997
+ handshake on, so before its first call is handled, also one its startup makes long before `ready` (the route's
2998
+ `opened`, §3): a store keeping reports across worker runs tags them with `ctx.incarnation` and compares.
2999
+ - **Errors in public and private** (decision "worker errors in public"): `state` and holders get a fixed message
3000
+ (`worker failed to start`, `worker exited (SIGSEGV)`) or the child's redacted `fatal`; the full error and the stderr
3001
+ tail go only to `onError` (`worker_failed`). Every app hook of a start (`start`, `principal`, `lock`, the fork) is
3002
+ inside that boundary; a throwing `authorize` refuses the hold and is reported `authorize_failed`. `worker_exited` is
3003
+ reported only for an exit nobody asked for.
3004
+ - **Workers never build** (D11): the server's plugins component builds every plugin; workers evaluate shipped
3005
+ complete sets (`createPluginRuntime`, no esbuild); `workers.step(name)` ships a rollout's set to every worker (D12:
3006
+ `{ kind: "reloaded", host, report } | { kind: "stopped", host } | { kind: "failed", host, error }` per worker).
3007
+
3008
+ ### The app kit (`chord/app`; slice 13)
3009
+
3010
+ Decisions "The app kit, point 1" to "point 5". `startServer(options)` on the server, `startWorker(options)` in a worker
3011
+ entry. Opinionated and small: an app is its API, its built-in plugins and a start script.
3012
+
3013
+ - **Shape:** the app's layout is fixed: `src/api/v<n>/` (shared and per-kind modules) and the built-in plugins root
3014
+ `plugins/`. The API is a real package (decision "Tutorial gaps" (3)): a workspace package of the app's repository
3015
+ (`"name": "@acme/app"`, `"exports": { "./v1": ..., "./v1/web": ... }`) that npm links, so Node, TypeScript, tests and
3016
+ plugin builds resolve it alike (a test imports a plugin's `contract.ts`). The data directory is a `startServer` option (no environment variables), default a dot directory named after
3017
+ the app in the home directory. One server; worker kinds are a list the app defines, each a host kind with its own
3018
+ params (sharding is the app's) and how it starts (entry, start data, principal, idle time); zero kinds is a server
3019
+ with clients only.
3020
+ - **Principals and users:** the principal is tiny (a kind and an id) and the app's type; the kit needs only the server's
3021
+ principal, each worker's (with worker kinds) and the owner's, values of that type the app chooses (decision "The kit's
3022
+ owner is a principal the app chooses": the owner may be one of the app's users; the kit adds no variant). The owner is
3023
+ strict JSON and never the server's principal (refused at start); the kit serves it as start data (`AppInfo.owner`).
3024
+ User data lives in objects keyed by the user's id. Optional kit plugins: users (accounts with an app-supplied profile
3025
+ schema), authenticators (device pairing, invite links, an ephemeral pick-a-name login).
3026
+ - **Authentication:** no owner by loopback alone: the start script prints a link with a one-time token that sets a
3027
+ signed cookie of the owner's sign-in; the owner link, the owner token file and device pairing sign in as the app's
3028
+ owner principal, and the owner-only routes (pairing's approval, invites) recognize it by canonical JSON, each
3029
+ principal's key computed once per principal object; a change of the owner between starts replaces the owner token file
3030
+ and revokes its old sign-in; deny by default (the HTTP component refuses requests without a principal unless the route
3031
+ or socket is public); `SignIns` issues and revokes sign-ins (one browser or device signed in as a principal: its
3032
+ cookie or token, its expiry, its revocation; decision "Sign-ins, not sessions"); command-line clients send a token in a header (an
3033
+ owner token file readable only by the app's OS user; a device pairing flow from other machines). A token is
3034
+ `<id>.<secret>`, only the secret's hash kept; a browser carries it in the signed cookie `chord-sign-in`. Browser and
3035
+ device sign-ins persist in the server's store and end unused after 400 days (a browser's cookie is renewed once it is
3036
+ a day old); ephemeral ones (the pick-a-name login) live in memory only, at most `limits.ephemeralSignIns` (1,000;
3037
+ past it the oldest ends), each ending with its client's connection (its last link closed and none opened for a
3038
+ minute) and with the server's run.
3039
+ - **Storage:** one store for the server, a directory per worker under its kind and address with its store; plugins
3040
+ never use data-directory paths. `Files`, one per host (decision "Files v2"), is the default file storage: its
3041
+ bytes as immutable blobs in the host's `files/`, its index in tables of the host's store; every file in a space at
3042
+ a path, folders as index entries and moves in the index only, a version per write and copies sharing blobs (a blob
3043
+ goes once nothing references it), small writes and chunked transfers, idempotency keys, fixed indexed metadata
3044
+ (`source`, `ref`, `key`, `mime`, …) plus free `meta`, queries by folder, path, `ref` and `key`, live folder
3045
+ listings (`FilesFolder`), a summary per space a worker pushes to its server's index, caps per host, and
3046
+ `copyFiles` for a new address made from an existing one. Raw directories only where a real path is needed, owned
3047
+ by one object, under the worker's directory. Export and import the data a host created (`exportData`, `importData`): the store's archive plus its
3048
+ files; export stops nothing (a running worker packs its own store; without one the server reads it under the
3049
+ worker's lock), import refuses an address that has data (decision "App kit naming and export").
3050
+ - **Data belonging to the address** (decision "Documents and table rows can belong to a host"; spec
3051
+ `host-keyed/spec.md` §6): the kit's archive format 2 adds `server.archive`, the server's records and rows belonging
3052
+ to the address (`exportHostData`, JSONL). The server's part and the worker's part are taken at two points in time
3053
+ (no transaction spans two stores). `importData(archive, address, ctx, { existing })` refuses an address with data
3054
+ (a directory, or server records or rows), replaces it with `existing: "replace"`, and copies under another address
3055
+ of the kind (host cells and keys rewritten); `deleteData(address, ctx)` (refused while the worker runs) removes the
3056
+ directory and the server's data. **Ordering, no durability promise** (owner, after the delta review: no journal):
3057
+ under the worker's lock an import unpacks whole into staging (nothing changed yet), moves an existing directory
3058
+ aside (replace), renames staging into place, and commits on the server last, the one commit; a failure before it, or
3059
+ a definite refusal, undoes the renames and rejects; an unknown outcome (`storage_failed`) undoes nothing and is
3060
+ reported in the rejection; the aside directory goes only after the commit. A delete commits on the server first,
3061
+ then removes the directory. Crash windows: an import between placing the directory and the server's commit (fix:
3062
+ import again with `existing: "replace"`); a delete after the server's commit (an orphan directory nobody refers to,
3063
+ removed by a repeated `deleteData`); leftover staging directories.
3064
+ - **Plugins:** the app's root (required) and the user's root in the data directory; installs from git or npm; one
3065
+ "apply changes" call builds and rolls out to the server, then every running worker. The kit serves it to the owner
3066
+ as a remote object on the server, `AppChanges` (`chord.app.changes`, params `{}`; decision "The kit serves the reload
3067
+ control", owner, 2026-11-11; not built yet): state `marks` (the plugins component's state: `dirty`, `install`, `set`,
3068
+ `base`) and `apply()`, which runs `applyChanges` and answers each step's host and the plugins whose new code failed
3069
+ and kept the old; any other principal is refused `forbidden`. Pages, terminals and agent tools use the one object.
3070
+ - **Restart needed:** `plugins.state.base` compares base code with what runs by content (§21, the reload loop, with
3071
+ its one latched exception): the app's `base` files and directories hashed at start, the server's own code (a
3072
+ best-effort static scan of its entry, `process.argv[1]`, bundled by esbuild with the server's conditions only to
3073
+ record what it reads: the literal imports of the start script's graph, lazy ones included, never a computed
3074
+ `import(x)` or a loader's module; an unresolved import left out, a failed scan reported), and the bytes each base
3075
+ read (the page's, the terminal's, each worker kind's), compared once when the kit watches them and at every change.
3076
+ The bases' records and the scan are added after the start, off its path (`app.baseWatched`; until it settles `base`
3077
+ is not known; the close does not wait for it): the server answers meanwhile. The latched exception covers the
3078
+ window between Node loading the server's modules and the scan reading them; an edit whose timestamps do not show it
3079
+ (a coarse or skewed file system clock) goes unseen there. The page's and the terminal's base resolve packages with
3080
+ the server process's conditions (`--conditions`/`-C` of its flags and `NODE_OPTIONS`), or the app's
3081
+ `web.conditions`/`tui.conditions`; a worker kind's with its own `execArgv`.
3082
+ - **Startup cost:** `startServer` resolves once the server listens; nothing it built is kept between starts (owner
3083
+ decision "A"). The web and terminal base bundles and each worker kind's worker base are built right after the listen,
3084
+ at once, from the files as they are then (`app.basesBuilt` settles once every build ended): a page request (the page,
3085
+ the surface's files, its `base` hash, a launcher's start) waits for its surface's build, a worker start for its
3086
+ kind's. A base that fails to build is reported (`AppError` `base_build`) and fails only what needs it: the page and
3087
+ the surface's files answer 503, the kind's workers fail their start; the server runs on, and a restart builds again.
3088
+ An Apply waiting at a surface's step for its initial build stops when its context is aborted (the build goes on: it
3089
+ is shared). The scan of the server's own code runs after the builds. Workers are forked with
3090
+ `NODE_COMPILE_CACHE=<dataDir>/cache/node`, and each kind's worker base is written to
3091
+ `<dataDir>/cache/workers/<kind>/` at its first fork (emptied first, removed at close), only while the start holds the
3092
+ data directory's lock: a build that ends after its start closed writes nothing. The path stays the same, so Node's compile
3093
+ cache knows the files (about 18 ms of the first worker's start). The server's own process must get
3094
+ `NODE_COMPILE_CACHE` from its supervisor or start command (its modules load before the kit runs). A minimal server's
3095
+ `startServer` takes about 30 ms; example 53's about 40 ms, its first worker answering about 320 ms after the start
3096
+ began (was about 560 ms with the builds on the start's path); Node's loading of Chord's source before the start script
3097
+ (about 390 ms, about 110 ms with a warm compile cache) is the remaining cost.
3098
+
3099
+ ### Web and TUI (slice 11)
3100
+
3101
+ Decision "Slice 11's points", "Slice 11, P3" to "P9", and "Tutorial gaps" (1) (page state).
3102
+
3103
+ - `chord/surfaces` serves the client surfaces (web and terminal) from the server; `chord/web` is a page's client host
3104
+ with its connection loop (p2's `keepConnected`), loading and applying the plugins' web facets. A base bundle per
3105
+ client kind built on the server from the app's entry (content-hashed; packages resolved with the server process's
3106
+ conditions unless the app gives its own, so a page runs the Chord source the server runs; the fonts, images and
3107
+ WebAssembly its stylesheets name are files under `assets/`, named by their content); at page load the kind's
3108
+ current plugin set as one combined file named by its hash, later changed plugins one script each, each a script that
3109
+ registers itself (no eval); new scripts apply in place (`host.reload` in the page), their stylesheets (named by their
3110
+ content) loaded before and each plugin left with the stylesheet of the code it runs; pages learn of them through an
3111
+ object the web component serves (the current set); a base code change reloads the page. A client starts without its
3112
+ server (a page renders offline, a service worker's kept page): it follows the scripts object in the background and
3113
+ applies the set shown when following begins as well as later ones.
3114
+ - **The connection loop** (`surfaces/connection.ts`, decision "Slice 11, P6"; the same loop in a page and a terminal's
3115
+ sandbox, its clock, timers and wakes given): after a drop it reconnects after 250 ms doubling to 5 s (reset by a
3116
+ connection open 10 s; the longest pause while the device is offline), at once on a wake (visible again, back online,
3117
+ restored from the back/forward cache, a network change) and for the first drop after a wake (the socket that was
3118
+ away); on a wake it replaces an open socket silent past the server's pings (25 s) once its next ping is overdue (at
3119
+ least 1 s, for frames held while frozen); it gives up a socket not open after 20 s. After a close it asks the app's
3120
+ `canRetry` beside the next attempt, never before it (a page's check asks the server's base over HTTP: seconds on a
3121
+ network just woken), one question at a time (closes while one is open ask nothing more); a "no" stops the loop, and
3122
+ an attempt it ends is reported `waiting`. A client asks the server's base there: another one stops the loop, then
3123
+ calls `outdated` (a page reloads). States: `connecting`, `connected` (the socket opened), `waiting`.
3124
+ - An app with an HTTP stack of its own (p2) serves the surface's files itself (`webSurface(..., { routes: false })`:
3125
+ the surface contributes no `Http` routes and gives `file`, `pageAssets` and `base`); a page styling itself turns the
3126
+ kit's themes off (`startPage({ themes: false })`: no `Themes` provider, nothing written on `:root`); a page built
3127
+ offline and served elsewhere (p2's Cloud Brain page)
3128
+ is static (`startPage({ follow: false })`: its combined plugins only, no updates, never outdated); a server whose
3129
+ loader resolves packages through a tsconfig's `paths` (a source checkout without `dist/`) names it (`tsconfig`), and
3130
+ the base resolves through them too. Decision "Surfaces for an app with its own HTTP stack and styling".
3131
+ - **Looks and themes** (decision "Looks and themes", 2026-11-02; `src/surfaces/`): a theme is data in one registry,
3132
+ `Themes` (version 1; `Theme`: `{ id, name, mode, colors, web?, tui? }`), with the base roles `accent`, `bg`, `fg`,
3133
+ `muted`, `error`, `warning`, `success` (apps add roles; a later role is a version bump mapping old entries from the
3134
+ fallback theme); plugins contribute themes, never the app's base CSS or components. A principal picks one dark and
3135
+ one light theme (`ThemeChoice`, remote on the server, a preference kept per principal key like the locale choice),
3136
+ the system preference chooses between them; a page writes the active theme as CSS variables on `:root`
3137
+ (`--<role>`, its `web` extras), a terminal looks a role up (`terminalColor`: true colour or the nearest of 256).
3138
+ Plugins scope their CSS with CSS modules.
3139
+ - `chord/react`: `HostProvider`, `useHold`, `useWatch`, `useRegistry`, `useRefState`, `useEvents(member, listener)`
3140
+ (an event member subscribed while mounted, below "Channels"), and `usePageState(key, initial)`:
3141
+ `useState`'s pair kept by the page's host under a key, so a component remounted by a plugin reload (a new function)
3142
+ keeps it (§21, "UI on client hosts"). `useVariant(ref, variant)` (decision "C15 stands; the UI bindings follow
3143
+ the variant"): the reference narrowed to `variant` while it is live in it, `undefined` otherwise (loading, failed
3144
+ or denied, ended, another variant), re-rendering when that changes: a held reference binds after the first render,
3145
+ an admission's other allowed value binds another variant while the component is mounted (§6), and a reference
3146
+ keeps its last variant while it loads, so `ref.variant === "editor"` alone would keep an editor's controls up.
3147
+ The terminal's is `TuiScope.variant(ref, variant)`, a reader. References themselves get no such helper (§5,
3148
+ C15).
3149
+ - `chord/tui/launcher`: a Node client connecting with a token, always running the downloaded code (the app's terminal
3150
+ entry on `chord/tui`) in a sandbox (decision "The terminal's sandbox is a child process": a child process on pipes
3151
+ with an empty environment, `--permission` granting nothing and no SQLite; the builtin allowlist and a frozen
3152
+ substitute `process` inside; a bridge terminal; the trusted launcher outside, confirming copy, open and attach on its
3153
+ own prompt); a component scope (`hold`, `watch`, `registry`, `on` (an event member's listener), released on dispose,
3154
+ one `changed` callback for the
3155
+ app's redraw; `pageState(key, initial)`, the host's page state shared with `usePageState`; `optimistic(read, reduce?)`,
3156
+ a reader showing optimistic actions while their calls are pending, with `add` and `pending`, React's `useOptimistic`,
3157
+ §3), no diffra-tui dependency.
3158
+
3159
+ ### Messages and languages (built after slice 11)
3160
+
3161
+ Decision "Messages and languages in the app kit", refined in the build (2026-11-03). Text people read is rendered per
3162
+ viewer, never by a server. The shared parts are in Chord's root (`src/surfaces/`, portable), `useMessages` in
3163
+ `chord/react`, `scope.messages` in `chord/tui`, `lang` and `dir` in `chord/web`; the kit serves `Translations` on the
3164
+ server, workers, pages and terminals and `LocaleChoice` on the server. Apps re-export what their plugins use.
3165
+
3166
+ ```ts
3167
+ // plugins/notes/messages.ts: one shared file every facet that renders imports
3168
+ export const messages = defineMessages("notes", {
3169
+ en: { newNote: "New note", count: (n: number) => (n === 1 ? "1 note" : `${n} notes`), saved: (title: string, at: string) => `Saved "${title}" at ${formatTime(at)}` },
3170
+ de: { newNote: "Neue Notiz", count: (n) => `${n} Notizen`, saved: (title, at) => `„${title}“ um ${formatTime(at)} gespeichert` },
3171
+ });
3172
+ // plugins/notes/web.tsx
3173
+ const { t, locale } = useMessages(messages); // re-renders on a locale or translation change
3174
+ self.contribute(Translations, messages.translations); // in the facet: the plugin's own catalogs
3175
+ // plugins/notes/worker.ts: a message as data (state member `notice: union([MessageSchema, nul()])`)
3176
+ draft.notice = messages.message("saved", note.title, note.at); // { namespace: "notes", key: "saved", params }
3177
+ // any client: t.render(notes.notice.value)
3178
+ ```
3179
+
3180
+ - **Messages in code:** `defineMessages(namespace, catalogs)` (a namespace is a name like a type's; catalog keys are
3181
+ language tags, canonicalized) returns `t`, typed by the first catalog: the others take their functions' parameter
3182
+ types from it, and a missing key, an unknown one or a wrong argument is a type error (when only strings differ,
3183
+ TypeScript may report a missing key at the first catalog's line). Values are strings or functions; `formatTime(at,
3184
+ options?)` (a `Date`, milliseconds or an ISO string; `timeStyle: "short"` by default) and `formatNumber(value,
3185
+ options?)` use `Intl` with the locale being rendered, the platform's outside a render (a language's default
3186
+ formatters are made once, kept in a `WeakMap` by the language).
3187
+ - **`t` is per host** (refinement (3)): `useMessages(t)` returns `{ t, locale }` bound to the `HostProvider`'s host and
3188
+ its language; `scope.messages(t)` returns a `t` reading the host's language at each call, its change calling
3189
+ `changed`; `t.in(language)` binds to any `Language`. The plain `t(key, ...args)` renders in the language of the
3190
+ render under way (a **render scope**: synchronous, set while a bound `t` calls a message function, so a nested plain
3191
+ `t` or `formatTime` follows it), and outside one in the first catalog (servers, tests, logs). No module-level current
3192
+ language: one process runs many hosts, and a server renders per recipient.
3193
+ - **Rendering a key:** down the language's chain (`pt-BR`, `pt`): the host's `Translations` catalog for the namespace
3194
+ and locale, else the plugin's own; else the first catalog. Each key found further down is reported (`fallback`), a
3195
+ contributed message that throws is reported (`failed`, naming its plugin) and the chain goes on (use sites guard
3196
+ contributions, §17).
3197
+ - **Translations** (refinements (1), (2)): a registry (`chord.translations`, version 1) whose contribution is a list of
3198
+ `{ namespace, locale, messages, override? }` (a contributor contributes once per registry, and one translation
3199
+ plugin translates several namespaces). A plugin's own catalogs are its built-in contributions literally: each
3200
+ rendering facet contributes `t.translations`, so the registry knows every locale offered (for the device default and
3201
+ a settings list); `t` still renders its own catalogs if a facet forgot. The composed `TranslationIndex` keeps one
3202
+ catalog per namespace and canonical locale: the first by plugin name wins and the other is reported
3203
+ (`registry_conflict`), `override: true` wins over a catalog without it; an invalid locale is left out, reported;
3204
+ `locales` lists every locale offered. Catalogs may be partial (`MessagesOf<typeof t>` is the full shape a translation
3205
+ fills); contributions are per host, so a translation plugin keeps them in a shared file and contributes them from
3206
+ each facet that renders. Catalogs never cross links.
3207
+ - **The locale:** `LocaleChoice` (remote on the server, params `{}`, per principal: `pick`, a language tag of at most 35
3208
+ characters or `null`, and `choose`), kept like the theme choice: both are a **preference** (`preferenceContract`,
3209
+ `preferenceFacet`: one persisted document of picks by principal key, the last 10,000 choosers). A client's
3210
+ `followActiveLanguage(host, preferred, changed, report, ctx)` resolves the locale: the pick when a catalog offers it
3211
+ (or a base or another region of its language), else the first of the device's languages offered (`navigator.languages`
3212
+ on a page, followed on `languagechange`; the system locale in the terminal: the launcher's `locales`, by default
3213
+ `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG`, then `Intl`'s, passed in the bridge's start), else English (the source
3214
+ of truth), else the first offered. The result, a `Language` (`{ locale, dir, chain, translations, report }`; `dir`
3215
+ from the locale's likely script), is the host's page state under `chord.language`, which `useMessages` and
3216
+ `scope.messages` follow; it changes only when the locale or the index does, nothing reloads. A page writes `lang`
3217
+ and `dir` on its root element. Reports go to the client's `onError` once each (`{ kind: "messages", report }`).
3218
+ - **Messages as data:** `t.message(key, ...args)` returns `MessageData<"notes", "saved">` (`{ namespace, key, params }`;
3219
+ `Message` is the link protocol's), only for keys whose arguments are JSON scalars (`MessageParam`), so a `Date`
3220
+ argument does not compile. A contract member uses `MessageSchema` (any namespace and key). `t.render(message)`
3221
+ refuses another literal namespace at the type level and checks at runtime what crossed a link: another namespace, a
3222
+ key the first catalog lacks or params that are no list show the key (reported `unknown`), a message that throws on
3223
+ its params shows the key (reported `failed`). Prompts, model output, logs and error codes are never translated.
3224
+
3225
+ ### Channels
3226
+
3227
+ WebSocket byte channels with acknowledged windows, separate from object links, wait for a second user after the
3228
+ terminals (slice 10 D6); they would be built on top of plugin sockets. Game-like traffic (positions, cursors, samples
3229
+ interpolated by their own timeline) is events (section 11, decision "Events: fire-and-forget members"): lossy JSON
3230
+ values over the object links, subscribed in React with `useEvents(member, listener)` (subscribed while mounted, the
3231
+ latest committed listener called: updated in a layout effect, so an event delivered between a render's commit and its
3232
+ passive effects reaches that render's listener) and in a terminal with `TuiScope.on(member, listener)` (stopped on dispose); inputs go up as
3233
+ calls through the client's own latest-only outbox. A WebSocket is TCP: one lost packet stalls everything behind it
3234
+ for a round trip; WebTransport datagrams are the later path.
3235
+
3236
+ ### Chunked transfers
3237
+
3238
+ Large byte transfers are chunked by the owning object: `begin`, `append({ upload, offset, bytes })`, `finish`,
3239
+ `read({ id, offset, length })`, about 1 MiB per chunk. The awaited `append` is the backpressure; after a drop the
3240
+ writer asks for the stored offset and resumes; unfinished uploads expire (the owner's routine). A helper wraps the
3241
+ loop. Chord has no stream type (it would need its own rules for drops, cancellation, relays and restarts).
3242
+
3243
+ ---
3244
+
3245
+ ## 24. Durable integration and portability
3246
+
3247
+ ### Durable
3248
+
3249
+ - Durable keeps importing today's Chord's `context`, `delta`, `json`, `output` and `sqlite`; `next/` imports the same
3250
+ modules, so `Context`, `Draft` and `JsonValue` are one type. Durable's conversation view, task graph and documents
3251
+ are `Watchable`s through Durable's watches (Durable's `WatchHandle` now lives in Chord); Durable adopts and dispatches
3252
+ them synchronously inside the storage's commit (S1, W1; with `StoreStorage` that is the store's commit step), so a derive over a Durable view travels with it. This needs Durable to publish a commit when it adopts it (owner, 2026-10-26; a diffra change, upstream first; explainer `durable-observers/`): inside `adopt`, its trackers, telemetry events and internal observers (view mounts, task graph, scheduler, submissions) run, and the host `observeCommits` observers are dispatched in one microtask queued before the observers, so they run before every wait the commit resolves and every abort it queues, but after the storage's synchronous step, never inside Chord's batch; host listeners and watch listeners have no order between them (owner, 2026-10-26). Durable's public primitive for adapters is a synchronous observer, `observeConversation`, `observeTaskGraph`, `observeDoc` (its `advance(call, ctx)` gets a `WatchCall` and runs inside `adopt`: record only, no awaits, no Session calls, no throws); `watchXXX` is built on it for app code. Chord's `self.follow(attach)` (slice 6b D9) is a source over it. Otherwise a derive over two Durable views computes between their frames of one commit. With `StoreStorage`, Durable's `adopt` runs inside the host's batch; the store knows nothing of Durable (no special cases) and needs only its step and flush to stay synchronous. Durable's
3253
+ state getters (`documentState`, `viewState`, `taskGraph()`) and the `replicatedState` family are removed (W14). Only
3254
+ plain data crosses between Durable and v2 objects.
3255
+ - **The harness is an object in the core facet** (base code): a `Harness` `local` object with empty params, so host lifetime (it runs for the worker's whole life,
3256
+ whether or not anyone holds it) opens Durable paused with `self.open` during the barrier and gets model
3257
+ access and execution environments from registry entries, looked up at each use:
3258
+
3259
+ ```ts
3260
+ const models = self.registry(HarnessModels); // declared dependencies (slice 8 S3): activation waits
3261
+ const envs = self.registry(HarnessEnvironments);
3262
+ const extensions = self.registry(HarnessExtensions);
3263
+ const harness = self.open(async (context) => Harness.open(await StoreStorage.open(store, Harness.name, context), {
3264
+ models: () => models.value, // read at use
3265
+ env: (target) => envs.value(target.cwd),
3266
+ settings: () => currentSettings(),
3267
+ registry: registryReader(extensions, context), // Durable's RegistryReader over the composed value (slice 8)
3268
+ }, context), (h, _reason, context) => h.close(context));
3269
+ ```
3270
+
3271
+ Durable's `models` and `settings` accept functions (diffra `7ec1f648e`). Durable opens with scheduling paused; base code
3272
+ calls `harness.resume()` after `await host.load(...)`; the worker connects to its parent first (W6), so host-lifetime
3273
+ stores can reference server types during the barrier; requests arriving during `load` park like any call to a
3274
+ loading object (refines R17). A missing tool gives its call an error result the model sees; a missing model makes the generation
3275
+ report "model unavailable" and wait (not fail) until a model contribution appears; a task whose definition is missing
3276
+ stays blocked (`missing_task`) until the plugin is installed or the task is aborted, as Durable does.
3277
+ - **Durable's views from other objects** (slice 8 §5): the harness object contributes its `Native<Harness>` to a
3278
+ registry of p3's; another object declares that registry (`self.registry`), wakes on it (`self.retryOn`) and follows
3279
+ a view through its value (`self.follow`). A Session close ends Durable's synchronous observers `failed` ("session
3280
+ closed"; decision "Slice 8 S1"; app watches still end `ended`), so the follower fails `transient` and follows the
3281
+ next Harness once its contribution arrives. `registryReader`'s listener runs inside Chord's batch: it only wakes
3282
+ Durable's scheduler (a Chord call there throws `invalid/reentrant`).
3283
+ - `HarnessModels` and `HarnessEnvironments` start with one contribution each, from the models and envs plugins'
3284
+ objects that own the natives; several providers or environment kinds are their `compose`. After a models reload
3285
+ the next request uses the new runtime; a running stream finishes on the old one.
3286
+ - **Chord from Durable code (Q6):** tools, hooks and sections get Durable's `ToolExecutionApi` and a `Context`, never a
3287
+ Chord `ctx`. p3's core opens the harness with a base context holding the host under a typed key
3288
+ (`withContextValue(ChordHostKey, host, …)`); every phase context inherits it. A core helper opens a call scope from
3289
+ any Durable context: `chord(async (ctx) => …, context)` = `host.root(fn, context)` (host principal; attribution as
3290
+ data; references released when `fn` settles; slice 8 D3). No wrapping of
3291
+ tools and no p3 `defineTool`. Clients are never reachable this way (they are not addressable): a tool that needs the
3292
+ user goes through an owner's state, e.g. the Questions service (`apps/p2/docs/questions.md`): the model-facing
3293
+ `ask_user` tool and any other tool call `Questions.ask`/`wait`, tabs render the open questions and `answer` them.
3294
+ Documented with this example.
3295
+ - **Code mode** (a plugin) keeps owning its `diffra-codemode` sandbox; its tool entry looks up the current sandbox when
3296
+ `execute()` starts, so a call pinned by a phase before a reload (e.g. waiting in an approval hook) starts on the new
3297
+ sandbox; on `reload` and `close` its `close` detaches the old sandbox, returns at once and disposes of it when its
3298
+ scripts finish or after `closeTimeout` (30 s at most, R16, Q7); after a worker stop Durable replays as today.
3299
+ - **Telemetry:** `HarnessOptions.telemetry`; submissions and tasks store an optional carrier (section 29).
3300
+
3301
+ ### Portability
3302
+
3303
+ Adopted in the kernel: host = identity plus incarnation; the loader is an adapter; values independent of the
3304
+ transport; durable state only in persisted documents. A Durable Object deployment
3305
+ (`apps/p2/docs/research/chord-on-durable-objects.md`) would map a logical host to a DO, compose plugins at build time
3306
+ (Workers forbid `eval`), replace the relaying tree with edge routing and use alarms for routines.
3307
+
3308
+ > **Decision needed: a Durable Object profile.** Problem: a DO can lose its memory while clients stay connected
3309
+ > (hibernation); routines need wake-ups (one alarm per DO); links between DOs are RPC stubs. Hot reload is not needed
3310
+ > there; plugin composition is. For later.
3311
+
3312
+ ---
3313
+
3314
+ ## 25. Apps: ownership and porting
3315
+
3316
+ - **Every thing has one owner, the smallest object it belongs to;** ownership nests; rules set at creation are written
3317
+ in the creating commit (Durable `createConversation` with `init`).
3318
+ - **Core owners are always present;** a plugin owner may be missing (optional dependencies are registries owned by the
3319
+ dependent, section 7). Avoid a core god object: each core owner owns only what belongs to it.
3320
+ - **Revocation of work in shared stores:** a store that runs work on behalf of a principal stores the grant (or device)
3321
+ as data with the work and reconciles from the grant owner's live grants (a routine aborts jobs, withdraws questions,
3322
+ drops queued input whose grant no longer exists); no revocation hook. The window between a revocation and the
3323
+ routine's run is accepted (R10): a step started in it still runs; there is always some window.
3324
+ - **Reading without starting a worker** is plain pub/sub in an ordinary plugin: a host-lifetime object of its worker facet
3325
+ records the summary locally and publishes it to the plugin's server object (a method call from a routine on the source); clients read
3326
+ the server object, which never starts a worker; it keeps the latest value per session (a document if it must
3327
+ survive a server restart) and ignores reports from an older worker incarnation. **The caller's incarnation is
3328
+ stamped by Chord (R20):** a call arriving over a link carries the calling host's incarnation from the link handshake
3329
+ (`ctx.incarnation`, next to `ctx.principal`, not part of the principal or its key, so object identities do not
3330
+ change with restarts); nobody sends it as data and it cannot be forged. On relayed calls it is the **origin** host's
3331
+ incarnation (Q13, owner, 2026-10-21): the relay takes it from the link the hold came in on and sends it in
3332
+ the upstream `hold` (a client's value is ignored, like its principal); calls inherit their hold's (section 4). Session list, status, children, unread and
3333
+ artifact lists follow this.
3334
+ - **Porting guideline:** what core enforces on data lives in a format core owns, written by the plugin that creates
3335
+ the data; a plugin's private document is read only by that plugin. Example: subagents mark one-shot and
3336
+ cwd-following child conversations in a core per-conversation policy document (`readOnly`, `followsSessionCwd`);
3337
+ chat and relocation read it; `ReadOnlyConversations` and `SessionCwdFollowers` go away.
3338
+ - **p3 is built next to p2,** fully isolated (`apps/p3`, own data directory), without migrating p2 data; plugins are
3339
+ derived from the functionality map (`apps/p2/docs/p3-functions/`), not ported one to one.
3340
+ - **Session lifecycle:** archive retires nothing (stops the worker, ends guest access, closes forwards); a session
3341
+ delete removes the whole session (tagged documents, the worker's databases, files, the catalog entry).
3342
+
3343
+ ---
3344
+
3345
+ ## 26. Decisions needed
3346
+
3347
+ Open, decided with the slice named or a concrete case (numbers kept stable; everything else is decided and folded into
3348
+ this document):
3349
+
3350
+ | # | Topic | Section | When |
3351
+ | --- | --- | --- | --- |
3352
+ | 11 | where a flow lives | 20 | when login is ported |
3353
+ | 14 | project plugins | 21 | own pass over `plugin-loading.md` |
3354
+ | 16 | a Durable Object profile | 24 | when a DO target becomes concrete |
3355
+ | 24 | a per-type drain override: a host option or fixed (no install watchdog: `reload` takes the app's context, decision "Slice 7b's open points" (4); a restart's old attempt is bounded by `reloadDrainTimeout`; a failing job `finish` backs off 1-60 s and blocks after five failures, decided) | 3 | if a real case needs it |
3356
+ | 28 | Astra's circuit breaker (a hard transport-buffer cap plus a stall deadline); the heartbeat is built, the cap was never decided | 3 | if a real case needs it |
3357
+
3358
+ Apps (p3), from the functionality map, decided per domain when p3 is designed:
3359
+
3360
+ | # | Topic | Problem and options |
3361
+ | --- | --- | --- |
3362
+ | 17 | session files | one owner `SessionFiles {session}` on the server for uploads, sent-file snapshots and artifact versions (caps per kind, index readable without a worker, copy on clone/fork, delete with the session); proposed, sub-points: one preview limit, fork's artifact list, copying attachments into remote environments |
3363
+ | 18 | session delete | per-session objects plus `SessionTag` plus a session directory, or owner hooks through a registry; search index per session or global plus a hook |
3364
+ | 20 | connection pools | SSH connections to one environment exist four times: one owner with a pool, or per-use connections |
3365
+ | 21 | config files with a single writer | settings, models and auth are watched by every process and written by two: one owner on the server, others follow its state |
3366
+ | 22 | file formats as versioned interfaces | `envs.json`, downloads, uploads have no version: version them like documents, or keep each internal to one owner |
3367
+ | 23 | the terminal host process | a detached process with its own code: part of the revision (reloaded or restarted with it) or deliberately outside |
3368
+
3369
+ ---
3370
+
3371
+ ## 27. Versions and adapters
3372
+
3373
+ | Surface | Version | On change |
3374
+ | --- | --- | --- |
3375
+ | object type | `version` plus contract fingerprint | every change bumps; forward evolution and `checkAccepts` (Q10); otherwise `contract_mismatch` |
3376
+ | registry | `version` | `accepts` adapter on contributions |
3377
+ | document | `version` plus schema fingerprint | pure `migrate`, on access; a schema change without a bump fails the object `broken` |
3378
+ | job | `version` | `accepts` maps older args and results forwards (`finish`, `running`); the state document's own `migrate`; `blocked` without an adapter or for a newer version |
3379
+ | native | none | the object restarts on reload |
3380
+ | column set (slice 14) | none | checked by column name and type when a read opens, and again when its binding changes |
3381
+ | named query (slice 14) | its contract's (the argument schemas are in the fingerprint) | as any member; edits and `accepts` for named queries are carry-over |
3382
+ | admission (slice 14) | none on the wire | `evolve`'s `admission(schema)`; a reload's staging compares its fingerprint |
3383
+ | Durable tasks and documents | `version` | Durable's `migrate` |
3384
+ | link protocol | protocol version | refused; hosts update together |
3385
+ | UI components, Chord and app APIs | none yet | exposed as they are; versioned with an SDK later |
3386
+
3387
+ **Contract evolution in code (Q10; implemented in `packages/chord/src/contracts/`, see its README):**
3388
+
3389
+ ```ts
3390
+ export const NotesV1 = remote("notes", { version: 1, params, variants: {
3391
+ editor: { state: { notes: arr(NoteV1) }, methods: { add: method(NoteV1, Id) } },
3392
+ } });
3393
+ export const NotesV2 = evolve(NotesV1, (e) => e.state("editor", "notes", arr(NoteV2)).args("add", NoteV2));
3394
+
3395
+ const accepted = checkAccepts(NotesV2, {
3396
+ 1: { state: { editor: { notes: (current) => current.map(toV1) } }, methods: { add: { args: (old) => toV2(old) } } },
3397
+ });
3398
+ ```
3399
+
3400
+ - A history starts with a base written in full with an explicit version (`remote()` / `local()`; `local` has flat
3401
+ `members` and no variants). `evolve(prev, (e) => …)` always continues it with structured edits: `state`,
3402
+ `addState`, `removeState`, `args`, `result`, `method(name, args, result)`, `addMethod`, `removeMethod` (local: no
3403
+ variant argument), for a local contract's keyed members `keyed`, `addKeyed`, `removeKeyed` (slice 7b; owner,
3404
+ 2026-10-26: keyed members' versions are mapped per key), and for event members `event`, `addEvent`, `removeEvent`
3405
+ (decision "Events: fire-and-forget members"; local: no variant argument). Every version is materialized and fingerprinted at declaration, so an old plugin's own copy of
3406
+ v1 computes the same fingerprint; no build step, no generated files, no hand-copied fingerprints.
3407
+ - **A new history base** (a params change or a change of the variant set) is a new `remote()`/`local()` with an
3408
+ explicit version and no accepts for older versions: old plugins get `contract_mismatch` and must update.
3409
+ - **Mappings live with the provider,** never in the contract: the pure `checkAccepts(contract, accepts)` (called by
3410
+ the objects layer) requires, at type level and again at runtime, a mapping for every member that exists in the old
3411
+ version and changed or was removed since: changed state `(currentMember) => oldMember`, removed state `(current
3412
+ variant state) => oldMember` or `"refuse"`, `args: (old) => current`, `result: (current) => old`, removed methods
3413
+ `{ call }` or `"refuse"`, changed keyed members `(current document) => old document` or `"refuse"` (mapped per key
3414
+ for an older local consumer), removed keyed members `"refuse"`, changed event members `(current value) => old
3415
+ value` or `"refuse"` (section `events`, by variant then member for a remote contract, flat for a local one: `{ 1: {
3416
+ events: { player: { paddle: (current) => old } } } }`; `"refuse"` refuses that version's binding, as a refused state
3417
+ member does); added members need nothing, and neither does a removed event member (the exception to the rule above:
3418
+ an older consumer binds and receives none of it; an event has no value to hydrate). No-op edits need identity
3419
+ mappings. Untyped JavaScript providers fail at declaration naming the member; unknown keys and wrong shapes are
3420
+ rejected. An older consumer gets each event mapped by its version's mapping, run once per emit per bound older
3421
+ version (the instance keeps one mapping per version while a reference of it is bound, dropped with the last one and
3422
+ at the instance's end); a mapping that throws drops that emit for that version only, reported once per failure
3423
+ episode (`event_mapping_failed { object, member, version, error }`), and is tried again at the next emit.
3424
+ - **The fingerprint** is a hash (`hash64`, portable, not a security boundary) of a schema-aware, data-only normal form
3425
+ (`NORMAL_FORM_VERSION`, tied to the protocol; each member a node of its kind: `{ state }`, `{ args, result }`,
3426
+ `{ keyed }`, `{ event }`, so a contract without keyed or event members keeps its fingerprint): annotations dropped only on schema nodes, `required`/`enum` sorted,
3427
+ union and intersection order kept (it is meaning: defaults), a whitelist of JSON Schema keywords, executable features
3428
+ rejected; bytes are a `{ type: "bytes" }` data marker. Schemas are deep-copied into a private history (never frozen; immutable by convention).
3429
+ - **Schema helpers:** `str num int bool nul lit oneOf union obj arr map opt bytes unknown` and `type Static`.
3430
+ - Chord wraps state mappings as a derive and diffs per object and version (section 22); members an old consumer does not know do
3431
+ not appear.
3432
+ ---
3433
+
3434
+ ## 28. Building: slices
3435
+
3436
+ Chord v2 is built in vertical slices; the plan, the feature map (every feature of this document assigned to the slice
3437
+ that builds it) and the carry-over of deferred obligations are in `slices.md`. Slice specs (`slice-N.md`) stay as the
3438
+ history of how each slice was specified; this document states the current rules. The first layered build (kernel steps
3439
+ 1-6) was deleted on 2026-10-22 and survives only in git history. Done in diffra: `diffra-telemetry` (propagation, links,
3440
+ metrics, the store interface, the renderer), `chord/context` (`Context.telemetry`), diffra-ai and Durable telemetry,
3441
+ `chord/telemetry-sqlite` (section 29), Chord's shared `Watch`/`NativeWatch`/`PendingOps`, Delta's `appendText`.
3442
+
3443
+ **Rules for every slice** (owner, 2026-10-22): the code follows the root `AGENTS.md` section "Chord v2 Code Style";
3444
+ one test file per source file, one `describe` per mechanism, the spec's test list case by case; cost guards through the
3445
+ in-memory telemetry adapter (section 30); GC tests for every cache and binding; one or more runnable examples
3446
+ (`packages/chord/test/examples/NN-topic.ts`); hot-path slices add a light benchmark script
3447
+ (`test/bench/`, by hand) with results in `benchmarks.md`; `npm run check` and the slice's tests before reporting.
3448
+ Caches are `WeakMap`s keyed by their owner; no module-level strong caches; no hot-path work no decision asked for. The
3449
+ function doing counted work counts it through its context; call sites never count for others; plain totals without
3450
+ site labels.
3451
+
3452
+ **Testing the core:** every slice spec contains an explicit test list, one group per mechanism with its edge cases,
3453
+ tested individually and exhaustively: activation and parked dependencies (the dependency model: unbound requests, waits without timers, wakes on every
3454
+ change, retry passing on, a dependency failing while live, cycles, the start barrier's first outcomes), revocation over running jobs (R11), compatibility (R6), params
3455
+ and arguments for every caller (R7), migration results and old calls on migrated documents (R8, R15), flow control
3456
+ (the window per origin, folding, relays forwarding and returning acks), the incarnation fence (R20), the harness start
3457
+ after the barrier (R17), native restart patterns (R16), and W1's publication list (a throwing derive, a chain A→B→C
3458
+ where B throws, two owners alternating with a derive over both, reentrancy, a watch started after 150 frames, stop
3459
+ during a running call, a retire with a derive over it, a reload during a routine call, GC counts of retained
3460
+ revisions).
3461
+
3462
+ ---
3463
+
3464
+ ## 29. Telemetry
3465
+
3466
+ Chord reports traces, events and metrics through `@diffra-ai/telemetry`; one adapter per host
3467
+ (`createHost({ telemetry })`, NOOP by default) decides sampling, buffering, export and filtering.
3468
+
3469
+ - **Types:** the adapter is a `TelemetryContext` (`startSpan` plus optional readonly `metrics` and `propagation`
3470
+ capabilities); only hosts hold it, to start roots. `Context.telemetry` is always a `TelemetrySpan` (the NOOP span by
3471
+ default); every span carries its adapter's `metrics` and `propagation`, so code with a context can record metrics
3472
+ and inject carriers. `withTelemetry(span, context)`, `traceIn(options, fn, context)` (context last; diffra change with S1); `value()` and keys stay.
3473
+ `Ctx` extends `Context`, so `ctx.telemetry` is the current span; app values such as the principal stay out of
3474
+ Durable's context. `ctx.trace(name, attributes, fn)` creates a child span and gives `fn` a child `ctx`.
3475
+ - **Adapters trust typed inputs:** no validation of malformed caller values and no try/catch around recording; only
3476
+ carriers from another process are checked (keys present, strings), else the root. Callers never protect themselves
3477
+ against broken adapters.
3478
+ - **Across links:** `call` and `hold` carry the caller's carrier as a bounded header field (section 22); the provider
3479
+ extracts it and runs the method under it; relays add a `chord.relay` span.
3480
+
3481
+ ```
3482
+ chord.call Notes.add [tab A]
3483
+ └─ chord.relay [server]
3484
+ └─ chord.method Notes.add [session:S1] principal=guest
3485
+ · event chord.commit docs=2 ops=5
3486
+ ```
3487
+
3488
+ - **Shared work** (one activation for several getters, a worker start, a remote object's hold shared by references,
3489
+ §7) is its own root span linked to its first trigger; each waiting span links to it. Routine runs, job runs, eviction, backoff retries and background closes are
3490
+ root spans linked to their trigger where one exists.
3491
+ - **Tiers:** spans for calls, methods, relays, holds, activations, opens, closes, loads, revocations, resolves, routine
3492
+ runs and job runs; events for commits inside methods, retries and parking; metrics for state messages, WebSocket
3493
+ bytes, commit durations, in-flight calls, active holds, open links, park durations and backpressure waits. IDs are
3494
+ attributes of spans, never of metrics.
3495
+ - **Nothing is measured or walked for telemetry:** only sizes the code already has. Errors carry a fixed category and
3496
+ a message truncated to 500 characters; cancelling is not an error.
3497
+ - **A typed telemetry schema** ships with Chord, as diffra-ai (`AI_TELEMETRY_SCHEMA`) and Durable
3498
+ (`DURABLE_TELEMETRY_SCHEMA`) have; call sites that only have a context use the generic `addEvent`.
3499
+ - **Storage and reading:** `@diffra-ai/chord/telemetry-sqlite` over `chord/sqlite` (Node and Cloudflare): one
3500
+ row per settled span (events and links inline), metrics aggregated per series per 10 s, a 1 s batched flush with
3501
+ retention (7 days), a bounded queue (dropped and counted). The shared read interface `TelemetryStore` (Jaeger
3502
+ style): `findTraces` (name, attributes, errors, time window, limit, cursor) returns complete traces, `getTrace`,
3503
+ `findMetrics`. Spans carry global ids and a trace id; links carry trace and span id. One renderer
3504
+ (`diffra-telemetry/render`) prints links and never follows them. A web trace viewer in the playground reads the store.
3505
+ - **Durable** (done): submit and phase spans, stored carriers on submissions and tasks (`TaskOptions.trace`, creation
3506
+ links), events after commit, report events; diffra-ai emits `diffra.ai.request`/`diffra.ai.poll` from one observer in
3507
+ `lazyStream`. Persisted Chord jobs store their start carrier. A worker's Harness gets its host's adapter
3508
+ (`HarnessOptions.telemetry`) and a method that submits input passes its `ctx` (its `telemetry` the `chord.method`
3509
+ span), so `diffra.durable.submit` links to it and starts its own trace, as decided.
3510
+
3511
+ **Built (slice 9, `slice-9.md`; `src/telemetry.ts`):**
3512
+
3513
+ - **The schema:** `CHORD_TELEMETRY_SCHEMA` (root export, `defineTelemetrySchema`) declares every span, event and metric
3514
+ Chord records with its attributes; the cost counters (`chord.data.*`, `chord.link.*`, `chord.store.*`,
3515
+ `chord.query.runs`, `chord.query.probes`, `chord.query.skips`, `chord.query.rows` (rows returned to Chord: output,
3516
+ not what the backend scanned), `chord.cycle.visits`, `chord.derive.*`, `chord.registry.*`, `chord.contract.adapts`) are recorded
3517
+ through it (`chordMetrics(metrics)`: typed instruments made once per adapter's metrics object and name, a `WeakMap`;
3518
+ the NOOP metrics share one set). Ids (object labels, run ids, address keys) are span attributes only.
3519
+ - **Spans:** `chord.call` (a consumer's call of a remote member, until its reply), `chord.method` (a provider running a
3520
+ method: under the call's carrier over a link, the caller's span on the same host; in `Attempt.call`, so local and
3521
+ remote calls alike), `chord.relay` (a relayed hold until it is held upstream, a relayed call until its reply is
3522
+ forwarded; the member is `hold` or `#<index>`: a relay never knows names), `chord.hold` (a remote object's hold
3523
+ until its first `bound` or failure: shared work, a root on the host's adapter whatever its first getter's context,
3524
+ linked to that getter's span when traced; a joining getter links to it while it is open; its carrier rides on the reference's first hold only: a re-hold after a reconnect
3525
+ is a fresh `chord.hold` root of the host's adapter linked to the first, and a relay's re-hold upstream after a drop a
3526
+ fresh `chord.relay` root linked to its first, so a page kept open for days never adds children under a span long
3527
+ ended), `chord.activate`,
3528
+ `chord.open` (under the activation), `chord.close` (a root), `chord.load`, `chord.reload` (a `chord.reload.fate`
3529
+ event per object), `chord.resolve`, `chord.revoke` (recorded after the synchronous revocation, its `count`),
3530
+ `chord.routine` (a root per call), `chord.job` (`intent` under the starter, `run` and `finish` under the start's
3531
+ carrier), `chord.http`. Every span Chord starts, `ctx.trace`'s too, names the host that recorded it: `chord.host`, the
3532
+ host's address key (`list|groceries`, `server`), `client` without an address, capped like the other attributes (a
3533
+ viewer tells hosts apart by it, never by a store's span ids). Outcomes are attributes; a failure is `status: "error"` with a fixed category (`call_failed`,
3534
+ `method_failed`, `relay_failed`, `hold_failed`, `activation_failed`, `open_failed`, `close_failed`, `load_failed`,
3535
+ `reload_failed`, `resolve_failed`, `routine_failed`, `job_failed`, `http_failed` for a status of 500 or more,
3536
+ `trace_failed`) and the message cut at 500 characters; a cancel (the caller's signal, `aborted`, an open its attempt
3537
+ abandoned) sets status ok explicitly (an adapter marks a span failed when its callback throws). String attributes a
3538
+ peer chose (an object's label with its params key, an address key, a principal's kind, names from the wire) are cut
3539
+ at 256 characters: stores keep them for days.
3540
+ - **Admissions** (slice 14): a decision is an event `chord.admit { outcome }` (`allow`, `deny`) of the admitted
3541
+ attempt's activation span, a route's of its hold's `chord.relay` (or `chord.hold`) span.
3542
+ - **Activations:** one span per attempt on the host's adapter, linked to the object's first trigger (the span that
3543
+ created it, or a hold's carrier), a retry's to the attempt before it; it ends `live`, `failed` (a transient failure's
3544
+ backoff a `chord.retry` event) or `ended`, or `parked` with a `chord.park { cause }` event, and a parked attempt's own
3545
+ steps resume in a new span linked to the parked one (spans stay short); one that fails or ends while still parked
3546
+ records it in a short span linked to the parked one. A getter binding to an object while it
3547
+ activates links its span to the activation (shared work); a route's first hold links to its resolve and back.
3548
+ - **Parents across processes are carriers, not spans:** a settled span starts no recorded children, so whatever runs
3549
+ later under work that has ended (a job's run and finish, a re-hold) goes through a carrier extracted with the host's
3550
+ adapter. Every job run keeps its start's carrier (a persisted one stores it): a run resumed in a new attempt or
3551
+ process stays in its trace.
3552
+ - **`ctx.trace`** gives `fn` a child of the same kind (a job run's keeps `jobId` and `state`), and a synchronous throw of
3553
+ `fn` rejects whether or not anything records: recording changes nothing `fn` sees but its span.
3554
+ - **Routines:** each call's span links to the span of the commit that changed its source when the watch frame's
3555
+ context names one (the newest folded frame's; the first call, with the current value, has none), and a call that
3556
+ threw carries its backoff as a `chord.retry` event.
3557
+ - **Cost (§30):** a span site checks `untraced(parent)` (the parent starts spans as the NOOP context does: no adapter can
3558
+ record) and then
3559
+ starts no span, builds no attribute object and injects no carrier; with the NOOP adapter a call over a link is within
3560
+ noise of the code before slice 9 (`benchmarks.md`). A recording host's call costs its spans (`OpenSpan`, a span kept
3561
+ open until its work's promise settles).
3562
+ - **Events and metrics:** `chord.commit { documents, ops, rows, duration }` on the span of the context a transaction
3563
+ ran under (a method, a routine, a job phase, an HTTP request), only for a commit that changed something; `rows` is the
3564
+ table rows its writes changed, as the commit step already counts them (a `put` one, an update or delete the rows its
3565
+ statement changed; nothing is measured for it); the host-wide
3566
+ metrics go to the host's adapter (`host.metrics`), not to a context: `chord.link.bytes { direction }` (every encoded
3567
+ message of the host's links), `chord.link.state_messages`, `chord.commit.duration`, `chord.calls.in_flight`,
3568
+ `chord.holds.active`, `chord.links.open`, `chord.park.duration`, `chord.backpressure.wait`, and the events' (decision
3569
+ "Events: fire-and-forget members"; an emit takes no context): `chord.events.emitted` (values emitted),
3570
+ `chord.events.sent` (entries sent, one per hold), `chord.events.dropped { reason: "window" | "too_large" | "mapping" }`
3571
+ (entries dropped; a mapping's one per emit and version) and `chord.events.encodes` (value encodes), nothing measured
3572
+ or walked for them. The cost counters still
3573
+ count through the context of the work; a host with an adapter gives its links' and root scopes' work, when the app
3574
+ passed a context without a span (`BACKGROUND_CONTEXT`, as the kit does), a span that records nothing but carries the
3575
+ adapter's metrics (`countingOnly`), so they reach the adapter in an app too.
3576
+ - **Components:** `createHttp({ telemetry })` makes each routed request a `chord.http` root (method, route pattern,
3577
+ status; never the path), its scope's `ctx` under it; a W3C `traceparent` (with its `tracestate`) is extracted (as the
3578
+ carrier `{ traceparent, tracestate }`) only from a request a contributed relay verified, each header at most 256 and
3579
+ 512 characters of printable ASCII (else ignored). A verified relay vouches for the proxy, not the browser behind it:
3580
+ an app's proxy must strip `traceparent` and `tracestate` from browsers' requests (or set its own), or a browser
3581
+ chooses the trace its requests join. `startServer({ telemetry })` passes the store to its host and HTTP and serves
3582
+ the ingest objects; workers and recording pages send it their spans (below). The SQLite store orders spans of one
3583
+ microsecond as their recorder started them (by start time, then id length and id).
3584
+ - **Span times (after slice 9):** a span's start is `telemetryNow()` (diffra-telemetry): wall-clock milliseconds at
3585
+ microsecond resolution from `performance.now()` anchored to the wall clock, anchored anew when the two part by more
3586
+ than 10 ms (a clock set, a sleep the monotonic clock did not count); its end and its events' times are the monotonic
3587
+ clock's from there. The in-memory adapter and the SQLite store share it, and `renderTrace` prints lengths to the
3588
+ microsecond. The SQLite store keeps span times in whole microseconds (`started_us`, `ended_us`): store version 2, to
3589
+ which a recorder migrates a version 1 file in place (its rows' milliseconds multiplied), since several processes
3590
+ share one file and a new store version would strand the rows already there.
3591
+ - **The server is the one place telemetry is stored** (decisions "Telemetry from browser pages", "The server is the
3592
+ one place telemetry is stored", "Who a span was for"; `src/telemetry-ingest/`, exported as
3593
+ `@diffra-ai/chord/telemetry-ingest` for an app with its own hosts): the server's store is the only
3594
+ writer of its file. Pages and workers record with Chord's in-memory `TelemetryRecorder` (the SQLite store records
3595
+ with it too: one carrier format, one bounded queue of settled spans and metric aggregates per 10 s) and send finished
3596
+ spans in batches over the link they already have to the server's `PageTelemetry` and `WorkerTelemetry`
3597
+ (`ingest(batch)`), served by the kit when `startServer` has a telemetry store (`TelemetryContext` with the store's
3598
+ `ingest`). A worker sends every second (and its last spans and partial metrics when it closes), written as they are,
3599
+ stamped with its host (`chord.host`: its address key, known from the principal its link stamps). A page records
3600
+ when `startPage({ telemetry: true })` and sends spans only, every 3 s and when hidden, if the app admits its
3601
+ principal (`telemetryIngestFacet({ admit(principal) })`, a refused page's hold fails `forbidden`: the per-page budget
3602
+ bounds one page, not one principal, who may open many; the kit admits every signed-in page); the server treats it as
3603
+ untrusted: the batch schema bounds everything (100 spans; names 128 characters; 32 attributes, keys 64, values 256
3604
+ characters or numbers or booleans; 16 events; 8 links; error messages 500; ids printable ASCII; no control
3605
+ characters anywhere), a span counts only when its id, trace and parent are under the page's own prefix
3606
+ (`browser:<its host's incarnation>:`, so it neither writes into another sender's trace nor poses as a server span),
3607
+ 1,200 spans per page and minute (past it dropped, counted in the answer), each marked `chord.host: browser` and
3608
+ stamped with the principal attributes of its link (the hook called per span), the page's own `chord.*` attributes
3609
+ dropped, so a page never claims a host or a principal. The store writes ingested spans
3610
+ with `INSERT OR IGNORE`: a stored span is never replaced. The ingest objects' calls start no `chord.method`
3611
+ (`ServeOptions.untraced`): a span per batch would be telemetry about telemetry. A trace of a page's own starts with
3612
+ `host.root(fn, ctx, { trace: { name, attributes } })`, a root span of the host's adapter (`trace_failed` on a throw).
3613
+ A viewer clamps a page's spans against the server spans under them (the page's clock may be off).
3614
+ - **Who a span was for:** `chord.method` and `chord.call` record their principal's attributes: by default
3615
+ `chord.principal`, its principal key (capped); a host's `principalAttributes(principal)` hook replaces them (none,
3616
+ the key, more: a user's name the app resolves; `{}` records nothing). Chord calls it for every span it records with
3617
+ a principal and never when nothing records (the NOOP adapter), so it is synchronous and cheap; Chord caches none of
3618
+ its results, any caching is the hook's own; the kit passes `startServer`'s and `startWorker`'s to their hosts, and
3619
+ the server stamps a page's spans with it for the link's principal. `Host` exposes `principalAttributes`,
3620
+ `incarnation` and `address` for the kit and the page recorder.
3621
+ - **Reading a shared file:** `openTelemetryStore(path)` (`@diffra-ai/chord/telemetry-sqlite/node`) implements
3622
+ `TelemetryStore` only, on a read-only SQLite connection (`openNodeSqliteDatabase(path, { mode: "read-only" })`:
3623
+ deferred transactions, nothing configured or checkpointed): it never writes, creates or migrates the file, and
3624
+ refuses one without a store or with a store of another version.
3625
+
3626
+ ## 30. Cost model
3627
+
3628
+ As little compute and memory as possible while staying correct; Delta was built for this (its own primitives are
3629
+ practically free: `diffRevisions` on shared subtrees 0.018 ms, `applyImmutable` per small change 0.004 ms). Measured
3630
+ before/after per hop: `apps/p2/docs/p3-reviews/v2-cost-model.md`.
3631
+
3632
+ | Hop | Work |
3633
+ | --- | --- |
3634
+ | commit | Delta's `prepare` (copies and checks only placed values), adopt by pointer swap; storage writes the delta |
3635
+ | reads in a transaction | the draft overlay, no copy; unchanged = no write |
3636
+ | subscribers on the same host | the same value and ops by reference |
3637
+ | derives | compute plus `diffRevisions`; unchanged parts stay the same objects (`mapShared`, cookbook) |
3638
+ | send | one encode per touched hold member per commit at its origin (the member's Delta encoder); while the window is full, per op one path key and one map lookup (leaf index), and one encode per waiting member per freed slot |
3639
+ | relay, per message | decode the envelope, swap the origin (one shallow copy), encode the envelope; parts copied once into the outgoing buffer, never parsed; per `bound`/`state` one FIFO entry; two bytes of origin per message upstream |
3640
+ | relay, per hold | the address's params checked once (route admission, `authorize`) |
3641
+ | receive | the compiled `MESSAGE` check on untrusted links; arguments validated once at the provider (compiled closed schema), params checked; one `ack` per `bound`/`state` message |
3642
+ | heartbeat | one timestamp write per received message; one timer per host |
3643
+ | apply | `applyImmutable`, structure shared |
3644
+ | new hold | the value encoded once (unavoidable) |
3645
+ | remote references of one host (§7) | per reference: one key (its type, params and address parts and its principal's JSON, cached per principal object) and one table lookup, its own watches, subscriptions and calls, no message; per shared remote object: one hold, snapshot and encoder at the provider, one decoder and replica per member here (measured, `benchmarks.md`: a joining reference 13 µs got and released, a commit to ten references one encode and 23 B) |
3646
+ | emit | one entry on the host's list, no Delta encoder, pending queue or diff; at the flush each value JSON-encoded (and compressed above the threshold) once per representation sent (the current version, each mapped version), the part reused for every hold and link; each `event` envelope then writes it, per recipient (measured, `benchmarks.md`: 13 µs delivered to one client, 64 µs to ten, one encode either way) |
3647
+ | relay, per event message | as any message (envelope only, parts never parsed), one ticket per message; never an ack of its own |
3648
+ | contracts without events | nothing per binding: no event record on a reference, no event nodes on a remote binding, no taps on a hold, shared empty event names (measured against the commit before events, `benchmarks.md`: equal time, a few dozen bytes per binding for the added fields) |
3649
+ | a commit writing a table nothing reads live | one map lookup per written table |
3650
+ | a commit writing a table with reads (slice 14) | per read the skip test: a set lookup, then at most one keyed probe (about 4 µs through Chord, `benchmarks.md`); one run per read not skipped. Linear in the reads the assigned columns cannot rule out |
3651
+ | `exists` | one index probe per row tested |
3652
+ | a join | the own rows the own condition admits, one key lookup each, a sort when the order uses a partner column (a team page of 300: 0.4 ms a run) |
3653
+ | a count | every row matching its condition, on each run |
3654
+ | an admitted object (slice 14) | its admission's references and derives; per change of a source one read of the decision (canonical JSON of an allowed value); one more attempt per changed value |
3655
+ | a route admission (slice 14) | one decision per (principal key, address) with holds; per denial a `release`, per allow after it one `ping` |
3656
+ | memory | one authoritative value per document per host; replicas and derived values share structure; one cached value per adapted member, object instance and version (while a reference of the version holds it); events: the host's list until the flush, per link and origin the ticket FIFO (one entry per `event` message in flight), per mapped version one mapping while bound |
3657
+
3658
+ **Cost guards:** Chord reports full-value walks, deep copies, encodes, schema validations and materializations as
3659
+ ordinary telemetry metrics, always on (no test mode; with the NOOP adapter they cost an empty call where such work
3660
+ happens). Tests use the in-memory adapter and assert them per hop (e.g. one appended note to a 500 KB document with
3661
+ 10 viewers: no walks, no copies, one encode per hold part at its origin and none at relays, no validations); a `vitest bench` suite measures the hops.
3662
+
3663
+ ---
3664
+
3665
+ ## 31. Rejected
3666
+
3667
+ `replicatedState` and its source family as public API; a separate IndexedDB backend; generic JSON rows and
3668
+ store-maintained index entries; last-write-per-row compaction; recording raw SQL statements or SQLite changesets;
3669
+ plugins' own databases holding source data; rollback after losing the driver role; JSON-field operands in bulk
3670
+ updates (until needed); a lazy-lifetime flag; a `lifetime` option; derive `previous`. Drain-based handover; version fences without transactions; object restart for state changes (one exception, slice
3671
+ 14: an admitted object restarts when its admitted value changes, the caller's standing, kept small by rule); Durable's Session as the
3672
+ object store; volatile documents; per-group lines; generic call or request ids; optimistic transactions; an outbox for
3673
+ transient delivery errors; revoking proxies on `.value`; resources replaced in place (`replace`, `deps`, stale
3674
+ handles); registries created at runtime and entries resolved through mutable indirection (contributions that change
3675
+ with their contributor, readable contributions and readers looking up the current value at use are fine, R25); generic
3676
+ registry keys with a `conflict` flag;
3677
+ `restart_required`; detached references counting toward presence; contracts taken from the running app; ceremony
3678
+ (`native/` directories, `defineNative`, lints); weakening type checking; "magic" input-field matching for delete; a
3679
+ factory trial; a migrate dry run; principal field patterns and re-stamping for revocation; `storeKey`; a consumer contract check during staging; reload votes; `defaultProjectTrust: "always"`; loader variants A and B; a topology layer above the host API; a stream type in
3680
+ Chord for byte and backpressured streams (events, section 11, are lossy JSON values without backpressure, replay or
3681
+ restart rules: no stream type either); callbacks as method arguments; `opaque` members; numeric middleware priorities; host addresses as data naming an
3682
+ input field; host-name strings in app code; host values (start data and platform bindings are core objects);
3683
+ consumer-side linger; registry composition as a staging check; a JSONL document storage; `tx.get` for documents; validating state and documents on commits or reads (migration results are validated once, R8); copying values on same-host calls; op-rewriting projections and a
3684
+ view algebra; keeping natives across reloads by name; Chord ending the process on a storage failure; an `optional`
3685
+ flag on references; cross-relay reset coordination; count limits that refuse calls or holds; relays acking per hop, relay resets
3686
+ (`reset { hold }`, `reset { holds }`), relay recovery and id renumbering at relays (replaced by flow control per
3687
+ origin); a byte window, credit messages, snapshot admission and debt; `reset` from a consumer; a round-robin of
3688
+ relayed calls at the relay; `state: false` on references (C8); `inVariant`/`expectVariant` (C15); per-call deadlines; references shared between UI
3689
+ components across a remount (decision "A reloaded UI part shows its loading state"): references held at the same time
3690
+ share their host's hold (decision "References share one wire hold"), but no hold is kept past its last release, and
3691
+ there are no borrowed references or leases.