@narumitw/pi-sync 0.63.1 → 0.65.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 (140) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +86 -10
  3. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  4. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  8. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
  9. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
  10. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  11. package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
  13. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
  16. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  17. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
  18. package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
  19. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
  20. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  21. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
  22. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  23. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
  24. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
  25. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  26. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  28. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  29. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
  30. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
  31. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
  32. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
  33. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
  34. package/dist/daemon/dist/cli.js +2 -0
  35. package/dist/daemon/dist/client-transport.js +66 -0
  36. package/dist/daemon/dist/client.js +222 -354
  37. package/dist/daemon/dist/consent.js +33 -11
  38. package/dist/daemon/dist/daemon-debug.js +33 -0
  39. package/dist/daemon/dist/daemon-recovery.js +158 -0
  40. package/dist/daemon/dist/daemon-startup.js +257 -0
  41. package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
  42. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  43. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  44. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  45. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
  46. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  47. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  49. package/dist/daemon/dist/engine/debug-log.js +134 -0
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  62. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  63. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
  66. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  67. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  68. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  69. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  70. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  71. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  72. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  73. package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
  74. package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
  75. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  76. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  77. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  78. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  79. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  80. package/dist/daemon/dist/engine-service.js +122 -10
  81. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  82. package/dist/daemon/dist/identity.js +36 -6
  83. package/dist/daemon/dist/index.js +2 -1
  84. package/dist/daemon/dist/monitor.js +21 -1
  85. package/dist/daemon/dist/paged-review.js +177 -0
  86. package/dist/daemon/dist/participant-ledger.js +149 -0
  87. package/dist/daemon/dist/protocol.js +4 -0
  88. package/dist/daemon/dist/server.js +340 -127
  89. package/dist/daemon/dist/service-host.js +83 -15
  90. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  91. package/dist/daemon/dist/state-wait.js +34 -0
  92. package/dist/daemon/package.json +1 -1
  93. package/dist/index.ts +128 -48
  94. package/dist/index.ts.map +2 -2
  95. package/docs/continuous-sync-verification.md +2 -0
  96. package/docs/daemon-migration.md +31 -6
  97. package/docs/tui-contract.md +7 -1
  98. package/package.json +2 -2
  99. package/skills/configure-pi-sync/references/configuration.md +23 -13
  100. package/src/commands/command-execution.ts +67 -5
  101. package/src/commands/command-handler.ts +12 -3
  102. package/src/commands/command.ts +4 -2
  103. package/src/daemon/client-debug.ts +45 -0
  104. package/src/daemon/directional-recovery.ts +103 -0
  105. package/src/daemon/ownership-recovery.ts +50 -0
  106. package/src/daemon/pi-client.ts +399 -71
  107. package/src/daemon/startup-bootstrap-client.ts +26 -0
  108. package/src/settings/config.ts +1 -0
  109. package/src/sync/automatic-sync.ts +61 -18
  110. package/src/sync/startup-check.ts +13 -5
  111. package/src/sync-extension.ts +46 -8
  112. package/src/ui/cancellable-operation.ts +5 -2
  113. package/src/ui/manager-state.ts +31 -23
  114. package/src/ui/manager-ui.ts +45 -25
  115. package/src/ui/merge-review.ts +53 -18
  116. package/src/ui/settings-ui.ts +2 -2
  117. package/src/ui/sync-confirmation.ts +14 -17
  118. package/src/ui/sync-setups-ui.ts +15 -12
  119. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  120. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  121. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  122. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  123. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  124. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  125. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  126. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  127. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  128. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  129. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  130. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  131. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  132. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  133. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  134. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  135. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  136. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  137. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  138. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  139. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  140. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -23,6 +23,7 @@ export function createMonitor(root, host) {
23
23
  const retryOwner = (peer) => JSON.stringify([peer.generation, peer.cwd, peer.sessionId, peer.sessionFile, peer.sessionDir, peer.model]);
24
24
  let epoch;
25
25
  const timingOwners = new WeakMap();
26
+ const cycleOutcomes = new Map();
26
27
  const loaders = createEngineLoaders();
27
28
  let continuous;
28
29
  function schedule() {
@@ -116,7 +117,25 @@ export function createMonitor(root, host) {
116
117
  const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
117
118
  if (!available())
118
119
  return;
119
- continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }));
120
+ continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }), {
121
+ timing: (ctx, report) => timingOwners.get(ctx)?.debug?.({ event: "startup-timings", report }),
122
+ cycle(ctx, setup, outcome) {
123
+ const debug = timingOwners.get(ctx)?.debug;
124
+ if (!debug)
125
+ return;
126
+ const key = `${outcome.outcome}:${outcome.reason ?? ""}`;
127
+ if (outcome.outcome !== "completed" && cycleOutcomes.get(setup) === key)
128
+ return;
129
+ cycleOutcomes.delete(setup);
130
+ cycleOutcomes.set(setup, key);
131
+ if (cycleOutcomes.size > 64) {
132
+ const oldest = cycleOutcomes.keys().next().value;
133
+ if (oldest !== undefined)
134
+ cycleOutcomes.delete(oldest);
135
+ }
136
+ debug({ event: "continuous-cycle", ...outcome });
137
+ },
138
+ });
120
139
  // Re-enter every eligibility branch after importing the full engine graph.
121
140
  return start();
122
141
  }
@@ -268,6 +287,7 @@ export function createMonitor(root, host) {
268
287
  schedule,
269
288
  lifetime,
270
289
  blockAutomatic,
290
+ foregroundRecoveryAllowed: () => !authorizationFailed,
271
291
  explicitSync(config, execution) {
272
292
  const peer = execution.facts();
273
293
  if (closed || !peer)
@@ -0,0 +1,177 @@
1
+ import { createHash } from "node:crypto";
2
+ import { MAX_REVIEW_BYTES, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
3
+ const SUMMARY_ROWS = 12;
4
+ const SUMMARY_ROW_CHARS = 240;
5
+ const HASH = /^[a-f0-9]{64}$/u;
6
+ export function reviewScope(identity, facts, callback) {
7
+ return {
8
+ instance: identity.instance,
9
+ client: facts.id,
10
+ generation: facts.generation,
11
+ id: callback.id,
12
+ job: callback.job,
13
+ };
14
+ }
15
+ function commitment(scope, summary, body) {
16
+ return createHash("sha256")
17
+ .update(JSON.stringify([
18
+ "pi-sync-merge-review-v1",
19
+ scope.instance,
20
+ scope.client,
21
+ scope.generation,
22
+ scope.id,
23
+ scope.job,
24
+ summary.title,
25
+ summary.confirmationLabel ?? null,
26
+ summary.summaryLines,
27
+ body.pages,
28
+ body.bytes,
29
+ body.sha256,
30
+ ]))
31
+ .digest("hex");
32
+ }
33
+ function exactHash(content) {
34
+ return createHash("sha256").update(content, "utf16le").digest("hex");
35
+ }
36
+ function presentation(value) {
37
+ return (record(value) &&
38
+ typeof value.title === "string" &&
39
+ value.title.length > 0 &&
40
+ value.title.length <= 512 &&
41
+ (value.confirmationLabel === undefined ||
42
+ (typeof value.confirmationLabel === "string" && value.confirmationLabel.length <= 256)));
43
+ }
44
+ export function createPagedReviewOffer(scope, data, content, bytes) {
45
+ if (!presentation(data))
46
+ return undefined;
47
+ const supplied = data.summaryLines;
48
+ const candidates = Array.isArray(supplied) && supplied.length > 0
49
+ ? supplied.slice(0, SUMMARY_ROWS)
50
+ : content.slice(0, SUMMARY_ROWS * SUMMARY_ROW_CHARS).split("\n", SUMMARY_ROWS);
51
+ const summaryLines = Object.freeze(candidates
52
+ .filter((line) => typeof line === "string")
53
+ .map((line) => line.slice(0, SUMMARY_ROW_CHARS)));
54
+ const summary = Object.freeze({ title: data.title, confirmationLabel: data.confirmationLabel, summaryLines });
55
+ const body = { pages: Math.ceil(content.length / REVIEW_PAGE_CHARS), bytes, sha256: exactHash(content) };
56
+ const reference = Object.freeze({ ...body, offer: commitment(scope, summary, body) });
57
+ let nextPage = 0;
58
+ return {
59
+ summary,
60
+ reference,
61
+ generation: scope.generation,
62
+ page(params) {
63
+ const index = params.index;
64
+ if (params.client !== scope.client ||
65
+ params.generation !== scope.generation ||
66
+ params.id !== scope.id ||
67
+ params.offer !== reference.offer ||
68
+ typeof index !== "number" ||
69
+ !Number.isSafeInteger(index) ||
70
+ index < 0 ||
71
+ index > nextPage ||
72
+ index >= reference.pages)
73
+ throw new Error("Stale, foreign, or invalid review page.");
74
+ if (index === nextPage)
75
+ nextPage++;
76
+ const start = index * REVIEW_PAGE_CHARS;
77
+ return { id: scope.id, index, offer: reference.offer, content: content.slice(start, start + REVIEW_PAGE_CHARS) };
78
+ },
79
+ approved(value) {
80
+ if (!record(value) || value.approvedReview !== reference.offer || nextPage !== reference.pages)
81
+ throw new Error("Exact review approval did not match the complete current offer.");
82
+ return true;
83
+ },
84
+ };
85
+ }
86
+ function verifyPagedReview(scope, payload, reference) {
87
+ if (!presentation(payload) ||
88
+ payload.content !== undefined ||
89
+ !Array.isArray(payload.summaryLines) ||
90
+ payload.summaryLines.length > SUMMARY_ROWS ||
91
+ !payload.summaryLines.every((line) => typeof line === "string" && line.length <= SUMMARY_ROW_CHARS) ||
92
+ !record(reference) ||
93
+ typeof reference.pages !== "number" ||
94
+ !Number.isSafeInteger(reference.pages) ||
95
+ reference.pages < 1 ||
96
+ reference.pages > Math.ceil(MAX_REVIEW_BYTES / REVIEW_PAGE_CHARS) ||
97
+ typeof reference.bytes !== "number" ||
98
+ !Number.isSafeInteger(reference.bytes) ||
99
+ reference.bytes <= REVIEW_PAGE_CHARS ||
100
+ reference.bytes > MAX_REVIEW_BYTES ||
101
+ typeof reference.sha256 !== "string" ||
102
+ !HASH.test(reference.sha256) ||
103
+ typeof reference.offer !== "string" ||
104
+ !HASH.test(reference.offer))
105
+ throw new Error("Invalid exact-review offer.");
106
+ const summary = Object.freeze({
107
+ title: payload.title,
108
+ confirmationLabel: payload.confirmationLabel,
109
+ summaryLines: Object.freeze([...payload.summaryLines]),
110
+ });
111
+ const verified = Object.freeze({
112
+ pages: reference.pages,
113
+ bytes: reference.bytes,
114
+ sha256: reference.sha256,
115
+ offer: reference.offer,
116
+ });
117
+ if (commitment(scope, summary, verified) !== verified.offer)
118
+ throw new Error("Exact-review offer changed; approval was refused.");
119
+ return { summary, reference: verified };
120
+ }
121
+ async function loadPagedReview(scope, reference, signal, pageRequest) {
122
+ const pages = [];
123
+ const { client, generation, id } = scope;
124
+ for (let index = 0; index < reference.pages; index++) {
125
+ signal.throwIfAborted();
126
+ const page = await pageRequest({ client, generation, id, offer: reference.offer, index });
127
+ signal.throwIfAborted();
128
+ if (!record(page) ||
129
+ page.id !== id ||
130
+ page.index !== index ||
131
+ page.offer !== reference.offer ||
132
+ typeof page.content !== "string" ||
133
+ page.content.length < 1 ||
134
+ page.content.length > REVIEW_PAGE_CHARS ||
135
+ (index < reference.pages - 1 && page.content.length !== REVIEW_PAGE_CHARS))
136
+ throw new Error("Invalid exact-review page.");
137
+ pages.push(page.content);
138
+ }
139
+ const content = pages.join("");
140
+ if (Buffer.byteLength(content) !== reference.bytes || exactHash(content) !== reference.sha256)
141
+ throw new Error("Exact-review contents changed; approval was refused.");
142
+ return content;
143
+ }
144
+ export async function presentPagedReview(scope, callback, signal, present, requestPage) {
145
+ if (callback.kind !== "merge-review")
146
+ throw new Error("Invalid exact-review callback.");
147
+ const { summary, reference } = verifyPagedReview(scope, callback.payload, callback.review);
148
+ const lifetime = new AbortController();
149
+ const owned = AbortSignal.any([signal, lifetime.signal]);
150
+ let loading;
151
+ let verified = false;
152
+ try {
153
+ owned.throwIfAborted();
154
+ const approved = await present({ ...callback, payload: summary, review: reference }, (requestSignal) => {
155
+ const pageSignal = requestSignal ? AbortSignal.any([owned, requestSignal]) : owned;
156
+ if (!loading) {
157
+ loading = loadPagedReview(scope, reference, pageSignal, (params) => requestPage(params, pageSignal)).then((content) => {
158
+ pageSignal.throwIfAborted();
159
+ verified = true;
160
+ return content;
161
+ });
162
+ void loading.catch(() => { });
163
+ }
164
+ return loading;
165
+ }, owned);
166
+ owned.throwIfAborted();
167
+ if (approved === false)
168
+ return false;
169
+ if (approved !== true || !verified)
170
+ throw new Error("Exact review details were not verified before approval.");
171
+ return { approvedReview: reference.offer };
172
+ }
173
+ finally {
174
+ lifetime.abort();
175
+ await loading?.catch(() => { });
176
+ }
177
+ }
@@ -0,0 +1,149 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import { randomUUID } from "node:crypto";
54
+ import fs from "node:fs/promises";
55
+ import path from "node:path";
56
+ import { processExists } from "./identity.js";
57
+ import { MAX_MESSAGE_BYTES, record, validateFacts, validateHandoff, } from "./protocol.js";
58
+ export function createParticipantLedger(paths, participants, onFailure) {
59
+ const file = path.join(paths.directory, "clients.json");
60
+ let writes = Promise.resolve();
61
+ let published;
62
+ let failed = false;
63
+ async function write(candidate, allowNoop) {
64
+ const bytes = JSON.stringify({
65
+ version: 1,
66
+ root: paths.root,
67
+ clients: [...participants()]
68
+ .filter((peer) => processExists(peer.facts.pid))
69
+ .map((peer) => ({ ...(candidate?.peer === peer ? candidate.facts : peer.facts), handoff: peer.handoff })),
70
+ });
71
+ if (allowNoop && !failed && bytes === published)
72
+ return;
73
+ const temporary = path.join(paths.directory, `.${randomUUID()}.clients`);
74
+ const handle = await fs.open(temporary, "wx", 0o600);
75
+ try {
76
+ await handle.writeFile(bytes);
77
+ await handle.sync();
78
+ await handle.close();
79
+ await fs.rename(temporary, file);
80
+ published = bytes;
81
+ }
82
+ finally {
83
+ await handle.close().catch(() => { });
84
+ await fs.rm(temporary, { force: true });
85
+ }
86
+ }
87
+ return {
88
+ get failed() {
89
+ return failed;
90
+ },
91
+ drain: () => writes,
92
+ save(candidate, allowNoop) {
93
+ const operation = writes.then(() => write(candidate, allowNoop));
94
+ writes = operation.catch(() => {
95
+ failed = true;
96
+ onFailure();
97
+ });
98
+ return operation;
99
+ },
100
+ async restore() {
101
+ try {
102
+ const env_1 = { stack: [], error: void 0, hasError: false };
103
+ try {
104
+ const before = await fs.lstat(file);
105
+ if (!before.isFile() ||
106
+ before.isSymbolicLink() ||
107
+ before.size > MAX_MESSAGE_BYTES ||
108
+ (process.getuid && before.uid !== process.getuid()) ||
109
+ (process.platform !== "win32" && before.mode & 0o077))
110
+ throw new Error("Unsafe daemon client record.");
111
+ const handle = __addDisposableResource(env_1, await fs.open(file, "r"), true);
112
+ const opened = await handle.stat();
113
+ if (opened.dev !== before.dev || opened.ino !== before.ino)
114
+ throw new Error("Daemon client record changed while opening.");
115
+ const data = JSON.parse(await handle.readFile("utf8"));
116
+ if (!record(data) ||
117
+ data.version !== 1 ||
118
+ data.root !== paths.root ||
119
+ !Array.isArray(data.clients) ||
120
+ data.clients.length > 64)
121
+ throw new Error("Invalid daemon client record; evidence retained.");
122
+ return data.clients.map((stored) => {
123
+ if (!record(stored))
124
+ throw new Error("Invalid stored participant.");
125
+ const { handoff, ...facts } = stored;
126
+ validateFacts(facts);
127
+ if (handoff !== undefined)
128
+ validateHandoff(handoff);
129
+ return { facts, handoff };
130
+ });
131
+ }
132
+ catch (e_1) {
133
+ env_1.error = e_1;
134
+ env_1.hasError = true;
135
+ }
136
+ finally {
137
+ const result_1 = __disposeResources(env_1);
138
+ if (result_1)
139
+ await result_1;
140
+ }
141
+ }
142
+ catch (error) {
143
+ if (error.code === "ENOENT")
144
+ return [];
145
+ throw error;
146
+ }
147
+ },
148
+ };
149
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  export const PROTOCOL_VERSION = 1;
4
+ export const OWNERSHIP_CLEANUP_REQUIRED = "DAEMON_OWNERSHIP_CLEANUP";
4
5
  /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
5
6
  export class DaemonStoppingError extends Error {
6
7
  name = "DaemonStoppingError";
@@ -27,6 +28,9 @@ export function validateHandoff(value) {
27
28
  ["file", "cwd"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])))
28
29
  throw new Error("Invalid client handoff.");
29
30
  }
31
+ export const DAEMON_JOB_CAPACITY = 64;
32
+ export const UNKNOWN_JOB_RESULT = "Operation is unknown or its result expired; reconcile journals instead of replaying.";
33
+ export const STATE_WAIT_HEARTBEAT_MS = 1_000;
30
34
  export function record(value) {
31
35
  return typeof value === "object" && value !== null && !Array.isArray(value);
32
36
  }