pi-web-ui 0.116.0 → 0.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +38 -4
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +138 -70
  4. package/dist/server/agent-service-daemon.js +52 -6
  5. package/dist/server/agent-service.js +495 -141
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +35 -6
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +48 -1
  11. package/dist/server/device-center/collab-service.js +26 -8
  12. package/dist/server/device-center/collab-tool.js +394 -18
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +15 -5
  18. package/dist/server/device-center/executor.js +47 -5
  19. package/dist/server/device-center/hub-conversations.js +14 -4
  20. package/dist/server/device-center/hub-deliveries.js +120 -15
  21. package/dist/server/device-center/hub-integration.js +655 -334
  22. package/dist/server/device-center/hub-page.js +5 -4
  23. package/dist/server/device-center/hub-setup.js +23 -1
  24. package/dist/server/device-center/hub-transaction-log.js +197 -0
  25. package/dist/server/device-center/hub.js +772 -354
  26. package/dist/server/device-center/integration-verification.js +113 -0
  27. package/dist/server/device-center/local-hub.js +6 -2
  28. package/dist/server/device-center/local-publication.js +423 -0
  29. package/dist/server/device-center/local-verification-job.js +97 -0
  30. package/dist/server/device-center/local-verification.js +274 -0
  31. package/dist/server/device-center/local.js +107 -12
  32. package/dist/server/device-center/main.js +4 -1
  33. package/dist/server/device-center/partition-log.js +62 -25
  34. package/dist/server/device-center/publication-journal.js +312 -0
  35. package/dist/server/device-center/publish-intent.js +379 -0
  36. package/dist/server/device-center/relay.js +134 -24
  37. package/dist/server/device-center/runtime.js +426 -42
  38. package/dist/server/device-center/store.js +225 -47
  39. package/dist/server/device-center/task-outcome.js +81 -0
  40. package/dist/server/device-center/task-recovery.js +603 -178
  41. package/dist/server/device-center/task-settlement.js +353 -0
  42. package/dist/server/device-center/task-workspace.js +443 -0
  43. package/dist/server/device-center/verification-limits.js +10 -0
  44. package/dist/server/device-center/work-contract.js +995 -0
  45. package/dist/server/dispatch-domain-handlers.js +15 -0
  46. package/dist/server/dsh/dsh-agent-service.js +9 -2
  47. package/dist/server/index.js +26 -1
  48. package/dist/server/patch-node-pty.js +3 -2
  49. package/dist/server/patch-remote-catalog.js +3 -2
  50. package/dist/server/preset-fields.js +17 -1
  51. package/dist/server/preset-share.js +1 -0
  52. package/dist/server/protocol-version.js +1 -1
  53. package/dist/server/quick-ask-settings.js +28 -0
  54. package/dist/server/quick-ask.js +164 -0
  55. package/dist/server/resolve-global-sdk.js +61 -11
  56. package/dist/server/scheduler-tasks.js +35 -8
  57. package/dist/server/session-list-scan.js +223 -0
  58. package/dist/server/session-open.js +93 -0
  59. package/dist/server/session-parser.js +4 -0
  60. package/dist/server/session-scan.js +90 -38
  61. package/dist/server/settings-service.js +9 -1
  62. package/dist/server/soft-cap.js +5 -0
  63. package/dist/server/transcript-prepare.js +73 -0
  64. package/dist/server/universal/drivers/claude-code.js +98 -34
  65. package/dist/server/universal/universal-session.js +4 -0
  66. package/dist/server/workspace-handle.js +428 -0
  67. package/docs/architecture-plugins.md +18 -5
  68. package/docs/device-center.md +30 -22
  69. package/package.json +3 -4
  70. package/plugin-sdk/README.md +16 -8
  71. package/plugin-sdk/client.d.ts +27 -0
  72. package/plugin-sdk/client.mjs +82 -0
  73. package/plugin-sdk/index.d.ts +10 -0
  74. package/plugin-sdk/index.mjs +4 -683
  75. package/plugin-sdk/package.json +15 -4
  76. package/plugin-sdk/testing.d.ts +10 -0
  77. package/plugin-sdk/testing.mjs +566 -0
  78. package/themes/flow-cristallo.css +168 -0
  79. package/themes/flow-ink.css +169 -0
  80. package/themes/flow-obsidian.css +169 -0
  81. package/themes/flow-zurich.css +169 -0
  82. package/web/dist/.build-assets.json +1 -1
  83. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
  84. package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
  85. package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  86. package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
  87. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  88. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  89. package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
  90. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  91. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  92. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
  93. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  94. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  95. package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  96. package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  97. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  98. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  99. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
  100. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  101. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  102. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
  103. package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  104. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  105. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  106. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  107. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  108. package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
  109. package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
  110. package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  112. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  113. package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
  114. package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
  115. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  116. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  117. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  118. package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
  119. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  120. package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
  121. package/web/dist/index.html +11 -11
  122. package/web/dist/sw.js +1 -1
  123. package/dist/gh-comment-781.md +0 -5
  124. package/dist/server/device-center/local-page.js +0 -17
  125. package/dist/server/device-center/smoke-preview.js +0 -3
  126. package/dist/server/durable/durable-capabilities.js +0 -11
  127. package/dist/server/markers/builtins/services.js +0 -123
  128. package/dist/server/markers/builtins/todo.js +0 -189
  129. package/dist/server/markers-list-tool.js +0 -34
  130. package/dist/server/orchestrator.js +0 -109
  131. package/dist/server/patch-turn-end-boundary.js +0 -77
  132. package/dist/server/system-prompt-soul.js +0 -41
  133. package/dist/server/univer-service.js +0 -448
  134. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  135. package/dist/test-artifact.md +0 -9
  136. package/dist/test-preview-modal.md +0 -11
  137. package/dist/test-report.html +0 -20
  138. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  139. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  140. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  141. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  142. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  143. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  144. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  145. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  146. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  147. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  148. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  149. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  150. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  151. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  152. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  153. package/web/dist/assets/index-C6DwztqE.css +0 -1
  154. package/web/dist/assets/index-CuN802Sj.js +0 -93
  155. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
@@ -8,11 +8,9 @@ import { join } from "node:path";
8
8
  * {"v":1,"op":"upsert","value":{...}}
9
9
  * {"v":1,"op":"del","ids":["..."]}
10
10
  *
11
- * Durability model: the owner persists its index file first and calls `commit` afterwards, so a log
12
- * entry always describes state that is already durable. Deletions are appended as tombstones and
13
- * compacted away once they outnumber live rows, which keeps steady-state growth O(1) per mutation.
14
- * A crash can only leave a partial trailing line (repaired on load) or un-tombstoned rows (trimmed
15
- * by the caller's retention on load), never a torn index file.
11
+ * The owner commits its WAL before projecting collections here. Failed projections can be replayed
12
+ * from that WAL. Deletions use tombstones; compaction atomically replaces a partition with live rows.
13
+ * Cache misses reload and repair disk state before any further append.
16
14
  */
17
15
  const PARTITION = /^[A-Za-z0-9_-]{1,128}$/;
18
16
  const PARTITION_SUFFIX = ".jsonl";
@@ -47,17 +45,30 @@ export class PartitionedAppendLog {
47
45
  * `sweep` removes log files whose parent no longer exists (crash leftovers); read-only callers skip it.
48
46
  */
49
47
  async load(partitions, options = {}) {
50
- await mkdir(this.dir, { recursive: true, mode: 0o700 });
48
+ if (!options.readOnly) {
49
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
50
+ }
51
51
  const existing = new Set();
52
52
  for (const partition of partitions)
53
53
  if (PARTITION.test(partition))
54
54
  existing.add(partition);
55
55
  // Files whose parent was removed by a committed transaction (crash between the two writes).
56
- for (const entry of options.sweep === false ? [] : await readdir(this.dir)) {
57
- const partition = entry.endsWith(PARTITION_SUFFIX) ? entry.slice(0, -PARTITION_SUFFIX.length) : "";
58
- if (!partition || !PARTITION.test(partition) || existing.has(partition))
59
- continue;
60
- await unlink(join(this.dir, entry)).catch(() => { });
56
+ const shouldSweep = options.sweep !== false && !options.readOnly;
57
+ if (shouldSweep) {
58
+ let entries = [];
59
+ try {
60
+ entries = await readdir(this.dir);
61
+ }
62
+ catch (error) {
63
+ if (error.code !== "ENOENT")
64
+ throw error;
65
+ }
66
+ for (const entry of entries) {
67
+ const partition = entry.endsWith(PARTITION_SUFFIX) ? entry.slice(0, -PARTITION_SUFFIX.length) : "";
68
+ if (!partition || !PARTITION.test(partition) || existing.has(partition))
69
+ continue;
70
+ await unlink(join(this.dir, entry)).catch(() => { });
71
+ }
61
72
  }
62
73
  const rows = [];
63
74
  for (const partition of existing) {
@@ -65,9 +76,9 @@ export class PartitionedAppendLog {
65
76
  if (!loaded)
66
77
  continue;
67
78
  rows.push(...loaded.values);
68
- // Repair a partition left oversized by a lost tombstone/compaction.
79
+ // Repair a partition left oversized by a lost tombstone/compaction (skip if read-only).
69
80
  const overRetention = this.retention !== undefined && loaded.rawRows > this.retention;
70
- if (loaded.needsRepair || overRetention || loaded.deletes > this.maxDeletes)
81
+ if (!options.readOnly && (loaded.needsRepair || overRetention || loaded.deletes > this.maxDeletes))
71
82
  await this.rewrite(partition, loaded.values);
72
83
  }
73
84
  return rows;
@@ -157,8 +168,8 @@ export class PartitionedAppendLog {
157
168
  }
158
169
  /**
159
170
  * Apply the diff between what is on disk (cache) and `next`. Partitions that no longer exist are
160
- * removed. When the write fails partway, each touched file is truncated back to its previous size
161
- * so a rejected transaction cannot leave phantom rows behind.
171
+ * removed. Failed appends are rolled back where possible; completed deletes/rewrites are retained
172
+ * because the owner's committed WAL can replay them. A retry reloads and repairs actual disk state.
162
173
  */
163
174
  async commit(next, partitions) {
164
175
  await mkdir(this.dir, { recursive: true, mode: 0o700 });
@@ -171,24 +182,45 @@ export class PartitionedAppendLog {
171
182
  bucket.push({ value, digest: this.digest(value) });
172
183
  grouped.set(partition, bucket);
173
184
  }
174
- const removedPartitions = [...this.cache.keys()].filter((partition) => !partitions.has(partition) && PARTITION.test(partition));
175
- // Partitions whose rows were all removed may have no `grouped` bucket; they still need tombstones.
176
- const touched = new Set([...grouped.keys(), ...this.cache.keys(), ...removedPartitions]);
177
- // Pre-append sizes so a rejected transaction cannot leave phantom rows behind.
185
+ // Cache invalidation must not hide existing files, including parents removed by this transaction.
186
+ const knownPartitions = new Set(this.cache.keys());
187
+ for (const entry of await readdir(this.dir)) {
188
+ if (entry.endsWith(PARTITION_SUFFIX)) {
189
+ const partition = entry.slice(0, -PARTITION_SUFFIX.length);
190
+ if (PARTITION.test(partition))
191
+ knownPartitions.add(partition);
192
+ }
193
+ }
194
+ const removedPartitions = new Set([...knownPartitions].filter((partition) => !partitions.has(partition)));
195
+ // Empty retained parents also need a disk reload and tombstones after cache invalidation.
196
+ const touched = new Set([...partitions, ...knownPartitions]);
197
+ // Only append offsets are safe to roll back; never truncate an atomically replaced snapshot.
178
198
  const rollback = new Map();
179
199
  try {
180
200
  for (const partition of removedPartitions) {
181
201
  const file = this.file(partition);
182
202
  if (file)
183
- await unlink(file).catch(() => { });
203
+ await unlink(file).catch((error) => {
204
+ if (error.code !== "ENOENT")
205
+ throw error;
206
+ });
184
207
  this.cache.delete(partition);
185
208
  this.deletes.delete(partition);
186
209
  this.lines.delete(partition);
187
210
  }
188
211
  for (const partition of [...touched].sort()) {
189
212
  const file = this.file(partition);
190
- if (!file || removedPartitions.includes(partition))
213
+ if (!file || removedPartitions.has(partition))
191
214
  continue;
215
+ if (!this.cache.has(partition)) {
216
+ const loaded = await this.readPartition(partition);
217
+ if (loaded &&
218
+ (loaded.needsRepair ||
219
+ (this.retention !== undefined && loaded.rawRows > this.retention) ||
220
+ loaded.deletes > this.maxDeletes)) {
221
+ await this.rewrite(partition, loaded.values);
222
+ }
223
+ }
192
224
  const previous = this.cache.get(partition) ?? new Map();
193
225
  const bucket = grouped.get(partition) ?? [];
194
226
  const present = new Set(bucket.map((entry) => this.idOf(entry.value)));
@@ -219,11 +251,8 @@ export class PartitionedAppendLog {
219
251
  this.deletes.set(partition, deletes);
220
252
  this.lines.set(partition, lines);
221
253
  if (deletes >= this.maxDeletes || (this.retention && lines > this.retention * 2)) {
254
+ rollback.delete(file);
222
255
  await this.rewrite(partition, bucket.map((entry) => entry.value));
223
- this.deletes.set(partition, 0);
224
- this.lines.set(partition, bucket.length);
225
- // The file is a full snapshot now; rollback must not truncate it to the old append offset.
226
- rollback.set(file, await this.size(file));
227
256
  }
228
257
  }
229
258
  }
@@ -281,6 +310,8 @@ export class PartitionedAppendLog {
281
310
  for (const value of values)
282
311
  cache.set(this.idOf(value), this.digest(value));
283
312
  this.cache.set(partition, cache);
313
+ this.deletes.set(partition, 0);
314
+ this.lines.set(partition, values.length);
284
315
  }
285
316
  /** Re-read a partition after an external change (used by tests and failure recovery). */
286
317
  async reload(partitions) {
@@ -290,4 +321,10 @@ export class PartitionedAppendLog {
290
321
  this.lines.delete(partition);
291
322
  }
292
323
  }
324
+ /** Invalidate all in-memory caches so subsequent commits reload actual disk state. */
325
+ invalidateCache() {
326
+ this.cache.clear();
327
+ this.deletes.clear();
328
+ this.lines.clear();
329
+ }
293
330
  }
@@ -0,0 +1,312 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { link, lstat, mkdir, open, opendir, readFile, rename, unlink } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { validatePublishIntent } from "./publish-intent.js";
5
+ import { canonicalizeJson } from "./work-contract.js";
6
+ export const PUBLICATION_WRITER_EPOCH = randomUUID();
7
+ export const PUBLICATION_JOURNAL_LIMITS = {
8
+ entries: 512,
9
+ bytes: 512 * 1024,
10
+ headerBytes: 448 * 1024,
11
+ events: 16,
12
+ };
13
+ const queues = new Map();
14
+ /** One writer per data directory. Rejections do not poison subsequent read-only diagnostics. */
15
+ export async function serializePublication(dataDir, run) {
16
+ const key = resolve(dataDir);
17
+ const pending = (queues.get(key) ?? Promise.resolve()).catch(() => { }).then(run);
18
+ queues.set(key, pending);
19
+ try {
20
+ return await pending;
21
+ }
22
+ finally {
23
+ if (queues.get(key) === pending)
24
+ queues.delete(key);
25
+ }
26
+ }
27
+ export function publicationJournalDirectory(dataDir) {
28
+ return join(dataDir, "publication-journal-v1");
29
+ }
30
+ function fileName(intent) {
31
+ return (createHash("sha256")
32
+ .update(canonicalizeJson([intent.accountId, intent.targetDeviceId, intent.integrationId]))
33
+ .digest("hex") + ".jsonl");
34
+ }
35
+ function digest(event) {
36
+ return createHash("sha256").update(canonicalizeJson(event)).digest("hex");
37
+ }
38
+ async function inspectDirectory(dataDir, create) {
39
+ const dir = publicationJournalDirectory(dataDir);
40
+ if (create)
41
+ await mkdir(dir, { recursive: true });
42
+ let names;
43
+ try {
44
+ const stat = await lstat(dir);
45
+ if (!stat.isDirectory() || stat.isSymbolicLink())
46
+ throw new Error("Publication journal directory is unsafe");
47
+ names = [];
48
+ for await (const entry of await opendir(dir)) {
49
+ names.push(entry.name);
50
+ if (names.length > PUBLICATION_JOURNAL_LIMITS.entries * 3)
51
+ throw new Error("Publication journal directory capacity exceeded");
52
+ }
53
+ }
54
+ catch (error) {
55
+ if (!create && error.code === "ENOENT")
56
+ return [];
57
+ throw error;
58
+ }
59
+ if (names.filter((name) => name.endsWith(".jsonl")).length > PUBLICATION_JOURNAL_LIMITS.entries ||
60
+ names.some((name) => !/^[a-f0-9]{64}\.jsonl(?:\.tmp-[a-f0-9-]{36})?$/.test(name)))
61
+ throw new Error("Publication journal capacity or directory integrity failure");
62
+ return names;
63
+ }
64
+ function assertProof(intent, proof) {
65
+ if (proof.intentId !== intent.id ||
66
+ proof.intentDigest !== intent.digest ||
67
+ proof.candidateSha !== intent.candidateSha)
68
+ throw new Error("Publication journal proof identity mismatch");
69
+ }
70
+ /** Strict and bounded: unreadable, malformed and partial files are never interpreted as absence. */
71
+ export async function readPublicationJournal(dataDir, input) {
72
+ const intent = validatePublishIntent(input);
73
+ const directory = publicationJournalDirectory(dataDir);
74
+ let stat;
75
+ const path = join(directory, fileName(intent));
76
+ try {
77
+ const parent = await lstat(directory);
78
+ if (!parent.isDirectory() || parent.isSymbolicLink())
79
+ throw new Error("Publication journal directory is unsafe");
80
+ stat = await lstat(path);
81
+ }
82
+ catch (error) {
83
+ if (error.code === "ENOENT")
84
+ return undefined;
85
+ throw error;
86
+ }
87
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > PUBLICATION_JOURNAL_LIMITS.bytes || stat.size === 0)
88
+ throw new Error("Publication journal file integrity failure");
89
+ const raw = await readFile(path, "utf8");
90
+ return parsePublicationJournal(raw, intent);
91
+ }
92
+ function parsePublicationJournal(raw, intent) {
93
+ if (!raw.endsWith("\n") || Buffer.byteLength(raw) > PUBLICATION_JOURNAL_LIMITS.bytes)
94
+ throw new Error("Publication journal is incomplete");
95
+ const lines = raw.slice(0, -1).split("\n");
96
+ if (lines.length > PUBLICATION_JOURNAL_LIMITS.events)
97
+ throw new Error("Publication journal event capacity exceeded");
98
+ let journal;
99
+ for (const [sequence, line] of lines.entries()) {
100
+ const event = JSON.parse(line);
101
+ const { hash, ...facts } = event;
102
+ if (event.version !== 1 ||
103
+ event.sequence !== sequence ||
104
+ event.previous !== (journal?.hash ?? "") ||
105
+ hash !== digest(facts))
106
+ throw new Error("Publication journal chain integrity failure");
107
+ if (sequence === 0) {
108
+ if (!event.intent || !["prepared", "closed"].includes(event.phase))
109
+ throw new Error("Invalid publication journal header");
110
+ const original = validatePublishIntent(event.intent);
111
+ if (canonicalizeJson(original) !== canonicalizeJson(intent))
112
+ throw new Error("Publication journal immutable intent mismatch");
113
+ if (event.phase === "prepared" && !event.repository)
114
+ throw new Error("Publication repository identity missing");
115
+ if (event.repository &&
116
+ (event.repository.repositoryId !== intent.repositoryId ||
117
+ event.repository.objectFormat !== intent.objectFormat ||
118
+ typeof event.repository.repoRoot !== "string" ||
119
+ typeof event.repository.commonDir !== "string"))
120
+ throw new Error("Publication repository identity mismatch");
121
+ journal = { intent: original, repository: event.repository, phase: event.phase, sequence, hash };
122
+ }
123
+ else {
124
+ if (event.intent || event.repository)
125
+ throw new Error("Publication journal identity replacement");
126
+ assertTransition(journal, event.phase, event.receipt, event.stop, event.processStopped);
127
+ journal = { ...journal, phase: event.phase, sequence, hash };
128
+ }
129
+ if (event.phase === "cas_started" && !event.processStopped) {
130
+ if (typeof event.processEpoch !== "string" || !/^[a-f0-9-]{36}$/.test(event.processEpoch))
131
+ throw new Error("Publication CAS process identity missing");
132
+ journal.casStarted = true;
133
+ journal.processEpoch = event.processEpoch;
134
+ journal.processStopped = false;
135
+ }
136
+ if (event.processStopped === true)
137
+ journal.processStopped = true;
138
+ if (event.receipt) {
139
+ assertProof(intent, event.receipt);
140
+ if (event.receipt.outcome !== "applied" ||
141
+ !["cas_exit", "target_exact", "target_descendant"].includes(event.receipt.proof) ||
142
+ !Number.isFinite(event.receipt.observedAt))
143
+ throw new Error("Invalid publication receipt");
144
+ if (journal.receipt && canonicalizeJson(journal.receipt) !== canonicalizeJson(event.receipt))
145
+ throw new Error("Publication receipt is immutable");
146
+ journal.receipt = event.receipt;
147
+ }
148
+ if (event.stop) {
149
+ assertProof(intent, event.stop);
150
+ if (event.stop.closed !== true ||
151
+ !["applied", "not_applied", "unknown"].includes(event.stop.pastEffect) ||
152
+ typeof event.stop.stopConfirmed !== "boolean" ||
153
+ !Number.isFinite(event.stop.fencedAt) ||
154
+ (event.stop.stopConfirmed && !Number.isFinite(event.stop.stoppedAt)) ||
155
+ (!event.stop.stopConfirmed && event.stop.stoppedAt !== undefined))
156
+ throw new Error("Invalid publication stop");
157
+ journal.stop = event.stop;
158
+ }
159
+ if (event.receipt?.proof === "cas_exit" && event.processStopped !== true)
160
+ throw new Error("Publication actual-exit stop proof missing");
161
+ if (event.phase === "cas_rejected" && event.processStopped !== true)
162
+ throw new Error("Publication rejection stop proof missing");
163
+ if (journal.receipt && journal.stop?.pastEffect === "not_applied")
164
+ throw new Error("Contradictory publication proof");
165
+ if (journal.phase === "applied" && !journal.receipt)
166
+ throw new Error("Publication applied receipt missing");
167
+ if (journal.phase === "closed" && !journal.stop)
168
+ throw new Error("Publication stop missing");
169
+ }
170
+ return journal;
171
+ }
172
+ /** Admission must consult the independent journal, even after sessions were removed. */
173
+ export async function loadPublicationJournals(dataDir) {
174
+ const names = await inspectDirectory(dataDir, false);
175
+ const journals = [];
176
+ for (const name of names.filter((name) => name.endsWith(".jsonl"))) {
177
+ const path = join(publicationJournalDirectory(dataDir), name);
178
+ const stat = await lstat(path);
179
+ if (!stat.isFile() || stat.isSymbolicLink() || !stat.size || stat.size > PUBLICATION_JOURNAL_LIMITS.bytes)
180
+ throw new Error("Publication journal integrity failure during admission");
181
+ const raw = await readFile(path, "utf8");
182
+ const header = JSON.parse(raw.split("\n", 1)[0]);
183
+ const intent = validatePublishIntent(header.intent);
184
+ if (fileName(intent) !== name)
185
+ throw new Error("Publication journal filename identity mismatch");
186
+ const journal = await readPublicationJournal(dataDir, intent);
187
+ if (!journal)
188
+ throw new Error("Publication journal disappeared during admission");
189
+ journals.push(journal);
190
+ }
191
+ return journals;
192
+ }
193
+ function assertTransition(journal, next, proof, stop, processStopped) {
194
+ if (journal.phase === "cas_started" && next === "cas_started" && processStopped === true)
195
+ return;
196
+ if (journal.phase === "closed" && next === "closed" && !journal.stop?.stopConfirmed && stop?.stopConfirmed)
197
+ return;
198
+ if (!journal.receipt && next === "applied" && proof && ["target_exact", "target_descendant"].includes(proof.proof))
199
+ return;
200
+ if (journal.stop || (journal.receipt && next !== "closed"))
201
+ throw new Error("Publication journal is terminal");
202
+ const allowed = {
203
+ prepared: ["cas_started", "closed"],
204
+ cas_started: ["cas_rejected", "applied", "closed"],
205
+ cas_rejected: ["cas_started", "closed"],
206
+ applied: ["closed"],
207
+ closed: [],
208
+ };
209
+ if (!allowed[journal.phase].includes(next))
210
+ throw new Error("Invalid publication journal transition");
211
+ }
212
+ async function flushDirectory(path) {
213
+ let handle;
214
+ try {
215
+ handle = await open(path, "r");
216
+ await handle.sync();
217
+ }
218
+ catch (error) {
219
+ // Windows cannot fsync directory handles. Files are fsynced: process-crash durability,
220
+ // with best-effort directory flushing, not a portable power-loss guarantee.
221
+ if (process.platform !== "win32" ||
222
+ !["EPERM", "EISDIR", "EINVAL", "EBADF", "EACCES"].includes(error.code ?? ""))
223
+ throw error;
224
+ }
225
+ finally {
226
+ await handle?.close();
227
+ }
228
+ }
229
+ async function writeAtomicJournal(path, content, exclusive) {
230
+ const temp = `${path}.tmp-${randomUUID()}`;
231
+ const handle = await open(temp, "wx", 0o600);
232
+ try {
233
+ try {
234
+ await handle.writeFile(content);
235
+ await handle.sync();
236
+ }
237
+ finally {
238
+ await handle.close();
239
+ }
240
+ if (exclusive) {
241
+ await link(temp, path);
242
+ await unlink(temp);
243
+ }
244
+ else
245
+ await rename(temp, path);
246
+ await flushDirectory(resolve(path, ".."));
247
+ }
248
+ finally {
249
+ await unlink(temp).catch((error) => {
250
+ if (error.code !== "ENOENT")
251
+ throw error;
252
+ });
253
+ }
254
+ }
255
+ export async function createPublicationJournal(dataDir, input, repository, stop) {
256
+ const intent = validatePublishIntent(input);
257
+ const existing = await readPublicationJournal(dataDir, intent);
258
+ if (existing)
259
+ return existing;
260
+ const names = await inspectDirectory(dataDir, true);
261
+ if (names.length >= PUBLICATION_JOURNAL_LIMITS.entries * 3 - 1)
262
+ throw new Error("Publication journal temporary capacity exhausted");
263
+ if (names.filter((name) => name.endsWith(".jsonl")).length >= PUBLICATION_JOURNAL_LIMITS.entries)
264
+ throw new Error("Publication journal is full");
265
+ const facts = {
266
+ version: 1,
267
+ sequence: 0,
268
+ previous: "",
269
+ phase: stop ? "closed" : "prepared",
270
+ intent,
271
+ ...(repository ? { repository } : {}),
272
+ ...(stop ? { stop } : {}),
273
+ };
274
+ const event = { ...facts, hash: digest(facts) };
275
+ const line = JSON.stringify(event) + "\n";
276
+ // Reserve enough space for every terminal event before objects, refs or CAS are written.
277
+ if (Buffer.byteLength(line) > PUBLICATION_JOURNAL_LIMITS.headerBytes)
278
+ throw new Error("Publication journal intent exceeds reserved capacity");
279
+ parsePublicationJournal(line, intent);
280
+ await writeAtomicJournal(join(publicationJournalDirectory(dataDir), fileName(intent)), line, true);
281
+ return (await readPublicationJournal(dataDir, intent));
282
+ }
283
+ export async function appendPublicationJournal(dataDir, journal, phase, proof) {
284
+ const current = await readPublicationJournal(dataDir, journal.intent);
285
+ if (!current || current.hash !== journal.hash)
286
+ throw new Error("Publication journal changed concurrently");
287
+ assertTransition(current, phase, proof?.receipt, proof?.stop, proof?.processStopped);
288
+ // Two slots always remain for a receipt and cancellation after any CAS start.
289
+ if (current.sequence >=
290
+ PUBLICATION_JOURNAL_LIMITS.events - (phase === "cas_started" && !proof?.processStopped ? 5 : 1))
291
+ throw new Error("Publication journal reserved capacity exhausted");
292
+ const facts = {
293
+ version: 1,
294
+ sequence: current.sequence + 1,
295
+ previous: current.hash,
296
+ phase,
297
+ ...proof,
298
+ };
299
+ const line = JSON.stringify({ ...facts, hash: digest(facts) }) + "\n";
300
+ if (Buffer.byteLength(line) > 4096)
301
+ throw new Error("Publication journal event too large");
302
+ const names = await inspectDirectory(dataDir, false);
303
+ if (names.length >= PUBLICATION_JOURNAL_LIMITS.entries * 3 - 1)
304
+ throw new Error("Publication journal temporary capacity exhausted");
305
+ const path = join(publicationJournalDirectory(dataDir), fileName(journal.intent));
306
+ const raw = await readFile(path, "utf8");
307
+ if (Buffer.byteLength(raw) + Buffer.byteLength(line) > PUBLICATION_JOURNAL_LIMITS.bytes)
308
+ throw new Error("Publication journal capacity exceeded");
309
+ parsePublicationJournal(raw + line, journal.intent);
310
+ await writeAtomicJournal(path, raw + line, false);
311
+ return (await readPublicationJournal(dataDir, journal.intent));
312
+ }