toolroll 0.9.129 → 0.9.131

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 +44 -0
  2. package/dist/agent-fence.js +0 -2
  3. package/dist/agent-state.js +1 -1
  4. package/dist/agents-board.js +0 -3
  5. package/dist/assignment.js +4 -3
  6. package/dist/backup-ui.js +6 -3
  7. package/dist/bounded-spawn.js +0 -1
  8. package/dist/browser/manifest.json +57 -0
  9. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  10. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  11. package/dist/browser/{terminal.js → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js} +1 -1
  12. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.br +0 -0
  13. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.gz +0 -0
  14. package/dist/browser/{workspace.js → workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js} +25 -25
  15. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.br +0 -0
  16. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.gz +0 -0
  17. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  18. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  19. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  20. package/dist/browser-shell.js +271 -25
  21. package/dist/builder-restart.js +13 -4
  22. package/dist/builder.js +4 -1
  23. package/dist/canvas-freshness.js +122 -0
  24. package/dist/canvas-fs.js +273 -0
  25. package/dist/canvas-reads.js +747 -0
  26. package/dist/canvas-state-key.js +45 -0
  27. package/dist/canvas-state-worker.js +12 -0
  28. package/dist/central-recovery-stage.js +3 -3
  29. package/dist/chat-actions.js +26 -0
  30. package/dist/chat-channel.js +4 -3
  31. package/dist/chat-follow.js +4 -0
  32. package/dist/chat-task-actions.js +1 -1
  33. package/dist/chat-warmth.js +0 -1
  34. package/dist/check-report.js +0 -6
  35. package/dist/commit-extract.js +79 -40
  36. package/dist/companion/access.js +1 -0
  37. package/dist/companion/actions.js +79 -16
  38. package/dist/companion/canvas.js +141 -0
  39. package/dist/companion/chat-origin.js +92 -0
  40. package/dist/companion/chat.js +571 -0
  41. package/dist/companion/daemon.js +46 -5
  42. package/dist/companion/finish.js +51 -0
  43. package/dist/companion/reads.js +5 -1
  44. package/dist/companion/schema.js +64 -0
  45. package/dist/companion/service.js +1 -0
  46. package/dist/companion/store.js +1 -0
  47. package/dist/companion/webauthn.js +11 -2
  48. package/dist/console-instance.js +0 -4
  49. package/dist/contracts/console-api.js +1 -1
  50. package/dist/converse.js +0 -1
  51. package/dist/coordinator.js +1 -1
  52. package/dist/db-tuning.js +16 -0
  53. package/dist/desktop-config.js +156 -0
  54. package/dist/desktop-host.js +6 -152
  55. package/dist/desktop-update.js +1 -1
  56. package/dist/discord.js +9 -3
  57. package/dist/dispatch.js +32 -4
  58. package/dist/doctor.js +30 -0
  59. package/dist/evidence.js +49 -3
  60. package/dist/exec.js +3 -0
  61. package/dist/finished-task-sql.js +14 -0
  62. package/dist/flexible-answers.js +0 -1
  63. package/dist/git-views.js +7 -1
  64. package/dist/github-read.js +41 -0
  65. package/dist/guides.js +4 -3
  66. package/dist/invoke.js +12 -2
  67. package/dist/lead-doors.js +50 -3
  68. package/dist/lead-queue-runtime.js +18 -6
  69. package/dist/lead-queue.js +25 -0
  70. package/dist/lead-status.js +3 -3
  71. package/dist/live-backup-change.js +93 -0
  72. package/dist/live-backup.js +75 -31
  73. package/dist/live-bus.js +3 -2
  74. package/dist/live-records.js +0 -1
  75. package/dist/local-owner.js +0 -1
  76. package/dist/loop-recovery.js +40 -0
  77. package/dist/maintenance.js +29 -1
  78. package/dist/model-choices.js +0 -11
  79. package/dist/needs-you.js +2 -0
  80. package/dist/nightly-check.js +0 -3
  81. package/dist/nightly-github.js +1 -2
  82. package/dist/notification-retention.js +119 -0
  83. package/dist/observations.js +0 -1
  84. package/dist/operate.js +393 -56
  85. package/dist/planner.js +4 -1
  86. package/dist/pull-request-flow.js +56 -15
  87. package/dist/qr.js +0 -25
  88. package/dist/query-index-schema.js +10 -0
  89. package/dist/read-executor-worker.js +9 -7
  90. package/dist/read-executor.js +18 -1
  91. package/dist/read-worker-connection.js +7 -0
  92. package/dist/release-adapters.js +63 -48
  93. package/dist/release-auto.js +17 -13
  94. package/dist/release-card.js +0 -4
  95. package/dist/release-cli.js +58 -10
  96. package/dist/release-next.js +1 -1
  97. package/dist/release-stops.js +71 -0
  98. package/dist/release-supersede.js +125 -0
  99. package/dist/release-supervise.js +90 -0
  100. package/dist/release.js +265 -42
  101. package/dist/restore-retirement.js +4 -1
  102. package/dist/result-review.js +0 -3
  103. package/dist/retention-ui.js +1 -1
  104. package/dist/retention.js +14 -21
  105. package/dist/review-context.js +0 -5
  106. package/dist/route-rules.js +1 -5
  107. package/dist/runner.js +36 -1
  108. package/dist/sandbox-runtime.js +0 -1
  109. package/dist/scope.js +1 -13
  110. package/dist/scout.js +4 -7
  111. package/dist/serve.js +122 -12
  112. package/dist/server/kit.js +1 -0
  113. package/dist/server/live.js +9 -2
  114. package/dist/server/pages.js +3 -2
  115. package/dist/server/phone-engine-api.js +22 -2
  116. package/dist/server/render-pages.js +1 -11
  117. package/dist/server/render-results.js +0 -1
  118. package/dist/server/render-tasks.js +0 -68
  119. package/dist/server/route-table.js +1 -1
  120. package/dist/server/settings-phone.js +32 -9
  121. package/dist/server/settings-scripts.js +1 -1
  122. package/dist/server/settings-section-table.js +0 -3
  123. package/dist/server/settings-sections.js +4 -2
  124. package/dist/server/settings.js +20 -5
  125. package/dist/server/terminals.js +2 -1
  126. package/dist/shutdown-proof.js +29 -0
  127. package/dist/slack.js +9 -3
  128. package/dist/sqlite-telemetry.js +26 -14
  129. package/dist/statement-cache.js +137 -0
  130. package/dist/store.js +86 -14
  131. package/dist/structured-output.js +0 -1
  132. package/dist/style-asset.js +20 -7
  133. package/dist/tailnet.js +0 -3
  134. package/dist/task-control.js +5 -0
  135. package/dist/task-sizing.js +0 -1
  136. package/dist/task-status.js +1 -1
  137. package/dist/teams.js +9 -3
  138. package/dist/teardown-git.js +10 -1
  139. package/dist/telegram.js +4 -1
  140. package/dist/toolroll-update-cli.js +19 -3
  141. package/dist/toolroll-update-ui.js +2 -2
  142. package/dist/toolroll-update.js +95 -15
  143. package/dist/up-processes.js +16 -1
  144. package/dist/up-role-child.js +2 -0
  145. package/dist/wake-hub.js +15 -6
  146. package/dist/work-index.js +101 -44
  147. package/dist/work-reads.js +53 -9
  148. package/dist/work-snapshots.js +185 -0
  149. package/dist/worker-statement-cache.js +83 -0
  150. package/dist/workspace-revision.js +145 -21
  151. package/package.json +1 -1
  152. package/dist/companion/webauthn-test-support.js +0 -44
  153. package/dist/contracts/contract-test.js +0 -55
  154. package/dist/unfenced-test-support.js +0 -6
  155. /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
@@ -1,4 +1,4 @@
1
- import { executeSharedAction, sharedActionPayload, sharedActionAllowsChallenge, sharedActionNeedsReview, startFromTerminalWords, typedStartOpens } from './chat-actions.js';
1
+ import { executeSharedAction, sharedActionPayload, sharedActionAllowsChallenge, sharedActionNeedsReview, startFromTerminalWords, typedStartOpens, phoneSharedActionAllowed, PHONE_CARDS_LIVE, PHONE_CARDS_LATER, PHONE_NOT_CONFIRMABLE } from './chat-actions.js';
2
2
  import { TYPED_START_REFUSED, typedStartCard, typedStartOf } from "./typed-start.js";
3
3
  import { closedQuestionWords } from "./decision.js";
4
4
  import { steerDestinationWords } from "./steer-status.js";
@@ -44,6 +44,7 @@ function payloadPlanning(payload) {
44
44
  }
45
45
  const VIA_WORDS = {
46
46
  web: "From the lead chat", cli: "From the command line", telegram: "From Telegram", slack: "From Slack", discord: "From Discord", teams: "From Teams",
47
+ phone: "From the iPhone app",
47
48
  };
48
49
  const CARD_WORDS = {
49
50
  task: "New task", next: "Queue priority", reserve: "Worker assignment", hold: "Pause work", unhold: "Resume work",
@@ -116,6 +117,11 @@ export function confirmLeadProposal(store, who, proposalId, now, options) {
116
117
  }
117
118
  if (proposal.kind === "control")
118
119
  return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: "Open the linked control to complete this action." };
120
+ if (options.via === "phone") {
121
+ const refusal = phoneDoorRefusal(proposal.kind, proposal.payload, options);
122
+ if (refusal !== null)
123
+ return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: refusal };
124
+ }
119
125
  if (options.typedStart !== undefined && proposal.kind !== "action")
120
126
  return { ok: false, kind: proposal.kind, reason: "refused", said: TYPED_START_REFUSED };
121
127
  if (proposal.kind === "action") {
@@ -129,7 +135,7 @@ export function confirmLeadProposal(store, who, proposalId, now, options) {
129
135
  const typed = typedStartOpens(store, proposal.id, action, { via: options.via, ...(options.typedStart === undefined ? {} : { typedStart: options.typedStart }), authority: localDoor(options) ? "local-owner" : "full" });
130
136
  if (options.typedStart !== undefined && !typed)
131
137
  return { ok: false, kind: proposal.kind, reason: "refused", said: TYPED_START_REFUSED };
132
- const challenged = options.via !== "web" && options.via !== "cli" && ((options.confirm === true && sharedActionAllowsChallenge(action, options.via)) || typed);
138
+ const challenged = options.via !== "web" && options.via !== "cli" && options.via !== "phone" && ((options.confirm === true && sharedActionAllowsChallenge(action, options.via)) || typed);
133
139
  if (sharedActionNeedsReview(action) && !challenged && (options.via !== "web" || options.actionReview === undefined || options.confirm !== true))
134
140
  return { ok: false, kind: proposal.kind, reason: "needs-confirm", said: "Review this action in the secure confirmation screen." };
135
141
  }
@@ -287,6 +293,11 @@ export function confirmCoordinatorProposal(store, who, proposalId, now, options)
287
293
  if (proposal.kind === "cancel") {
288
294
  return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: "Cancel from the task page." };
289
295
  }
296
+ if (options.via === "phone") {
297
+ const refusal = phoneDoorRefusal(proposal.kind, proposal.payload, options);
298
+ if (refusal !== null)
299
+ return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: refusal };
300
+ }
290
301
  const needsConfirm = proposal.kind === "answer" && proposal.payload["reversible"] === false && options.confirm !== true;
291
302
  if (needsConfirm)
292
303
  return { ok: false, kind: proposal.kind, reason: "needs-confirm", said: "an irreversible choice must be confirmed explicitly" };
@@ -316,6 +327,11 @@ export function dismissCoordinatorProposal(store, who, proposalId, now) {
316
327
  function executeProposal(store, actor, kind, payload, now, options) {
317
328
  if (!isVerifiedApprover(actor) || !reproveApprover(store, actor).ok)
318
329
  return { ok: false, kind, reason: "standing", said: "Your sign-in changed. Sign in again." };
330
+ if (options.via === "phone") {
331
+ const refusal = phoneDoorRefusal(kind, payload, options);
332
+ if (refusal !== null)
333
+ return { ok: false, kind, reason: "not-confirmable", said: refusal };
334
+ }
319
335
  if (options.via !== "web" && options.via !== "cli") {
320
336
  const solo = soloChatSeatRefusal(store, { provider: options.via, binding: options.binding, approver: actor.name });
321
337
  if (solo !== null)
@@ -382,6 +398,8 @@ function executeProposal(store, actor, kind, payload, now, options) {
382
398
  }
383
399
  if (!chosen.reversible && options.confirm !== true)
384
400
  return refuse("needs-confirm", "an irreversible choice must be confirmed explicitly");
401
+ if (options.via === "phone")
402
+ return refuse("not-confirmable", chosen.reversible ? PHONE_CARDS_LATER : PHONE_NOT_CONFIRMABLE);
385
403
  const answered = store.answerDecision({ id: decision.id, choice: chosen.id, by: actor.name, via: options.via }, now);
386
404
  if (!answered.ok || answered.duplicate === true) {
387
405
  return !answered.ok && answered.reason !== "already-answered"
@@ -396,7 +414,7 @@ function executeProposal(store, actor, kind, payload, now, options) {
396
414
  if (ref === null || !admitted(ref.repo))
397
415
  return refuse("unknown-task", "no such task in your projects");
398
416
  if (kind === "task_action") {
399
- const result = applyChatTaskAction(store, actor, payload, now, options.via !== "cli", { deferSignal: options.deferSignal, via: options.via, person: options.via === "web" ? options.person === true : options.via !== "cli", ...(options.evidenceRoot === undefined ? {} : { evidenceRoot: options.evidenceRoot }), ...(options.binding === undefined ? {} : { binding: options.binding }) });
417
+ const result = applyChatTaskAction(store, actor, payload, now, options.via !== "cli", { deferSignal: options.deferSignal, via: options.via, person: doorPerson(options), ...(options.evidenceRoot === undefined ? {} : { evidenceRoot: options.evidenceRoot }), ...(options.binding === undefined ? {} : { binding: options.binding }) });
400
418
  return result.ok ? { ok: true, kind, taskId: result.taskId, said: result.said } : refuse("stale", result.message);
401
419
  }
402
420
  if (kind === "review") {
@@ -698,3 +716,32 @@ export function confirmTypedStart(store, who, typed, now, options) {
698
716
  return settle("refused", null, outcome.ok ? TYPED_START_REFUSED : `${TYPED_START_REFUSED} (${outcome.said.replace(/\.$/, "")}.)`);
699
717
  });
700
718
  }
719
+ const PHONE_CARD_KINDS = new Set(["task", "next", "reserve", "hold", "steer", "answer", "task_action", "action"]);
720
+ export const PHONE_TASK_ACTIONS = new Set(["stop", "retry", "plan", "wait_for", "stop_waiting", "run_checks", "run_full_checks", "add_tests"]);
721
+ export function phoneConfirmable(kind, payload) {
722
+ if (!PHONE_CARD_KINDS.has(kind))
723
+ return false;
724
+ if (kind === "answer")
725
+ return payload["reversible"] !== false;
726
+ if (kind === "task_action")
727
+ return typeof payload["operation"] === "string" && PHONE_TASK_ACTIONS.has(payload["operation"]);
728
+ if (kind === "action") {
729
+ const action = sharedActionPayload(payload);
730
+ return action !== null && phoneSharedActionAllowed(action);
731
+ }
732
+ return true;
733
+ }
734
+ export function phoneDoorRefusal(kind, payload, options) {
735
+ if (options.person !== undefined || options.typedStart !== undefined)
736
+ return PHONE_NOT_CONFIRMABLE;
737
+ if (options.confirm !== undefined && !(kind === "answer" && payload["reversible"] !== false))
738
+ return PHONE_NOT_CONFIRMABLE;
739
+ if (!phoneConfirmable(kind, payload))
740
+ return PHONE_NOT_CONFIRMABLE;
741
+ return PHONE_CARDS_LIVE ? null : PHONE_CARDS_LATER;
742
+ }
743
+ export function doorPerson(options) {
744
+ if (options.via === "web")
745
+ return options.person === true;
746
+ return options.via !== "cli" && options.via !== "phone";
747
+ }
@@ -3,8 +3,11 @@ import { createHash, randomUUID } from "node:crypto";
3
3
  import { runLeadTurn } from "./lead.js";
4
4
  import { PersonalQueue } from "./lead-queue.js";
5
5
  import { verifyApproverStanding } from "./principal.js";
6
+ import { briefly } from "./store.js";
6
7
  import { updateAdmissionPaused } from "./desktop-update-gate.js";
7
8
  import { TURN_WALL_CLOCK_MS } from "./converse.js";
9
+ import { withActor } from "./actor.js";
10
+ import { cancelFallenPhoneWork, PHONE_ORIGIN_GONE, phoneOriginStands } from "./companion/chat-origin.js";
8
11
  export function leadTurnContext(store, context, names) {
9
12
  if (context === null)
10
13
  return undefined;
@@ -49,6 +52,8 @@ export function createPersonalQueueRuntime(options) {
49
52
  const thread = store.getLeadThread(row.thread);
50
53
  if (thread === null || thread.closedAt !== null)
51
54
  return { ok: false, why: "Not sent: this conversation was closed before it ran." };
55
+ if (row.origin === "phone" && !phoneOriginStands(store, row.message))
56
+ return { ok: false, why: PHONE_ORIGIN_GONE };
52
57
  if (row.context !== null && !options.contextStands(row.approver, row.context))
53
58
  return { ok: false, why: "Not sent: the task it was about is no longer available." };
54
59
  return { ok: true, who: verified.who };
@@ -78,7 +83,7 @@ export function createPersonalQueueRuntime(options) {
78
83
  let held = false;
79
84
  const session = store.getLeadSession(claim.session), thread = store.getLeadThread(claim.thread);
80
85
  const context = leadTurnContext(store, claim.context, options.names);
81
- outcome = await runLeadTurn({
86
+ outcome = await withActor({ account: claim.approver, lead: true }, () => (options.runTurn ?? runLeadTurn)({
82
87
  store, who: proof.who, session, thread, config: provider.config, key: provider.key, message: claim.text, requestId: claim.requestId,
83
88
  queuedMessageId: claim.message, queueClaim: { message: claim.message, runner: claim.runner, generation: claim.generation },
84
89
  onAdmitted: turn => {
@@ -97,7 +102,7 @@ export function createPersonalQueueRuntime(options) {
97
102
  },
98
103
  ...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
99
104
  ...(options.subscriptionRunner === undefined ? {} : { subscriptionRunner: options.subscriptionRunner }),
100
- });
105
+ }));
101
106
  if (outcome.ok) {
102
107
  queue.finish(claim, { status: "answered", turnId: outcome.turn }, clock());
103
108
  return;
@@ -130,9 +135,12 @@ export function createPersonalQueueRuntime(options) {
130
135
  return;
131
136
  passing = true;
132
137
  try {
133
- queue.reconcile(clock(), TURN_WALL_CLOCK_MS + 60_000);
138
+ briefly(store, () => {
139
+ queue.reconcile(clock(), TURN_WALL_CLOCK_MS + 60_000);
140
+ cancelFallenPhoneWork(store, clock());
141
+ });
134
142
  for (;;) {
135
- const claim = queue.claimNext(runner, clock(), row => waiting.get(row.message) !== stamp(row));
143
+ const claim = briefly(store, () => queue.claimNext(runner, clock(), row => waiting.get(row.message) !== stamp(row)));
136
144
  if (claim === null)
137
145
  break;
138
146
  waiting.delete(claim.message);
@@ -151,13 +159,17 @@ export function createPersonalQueueRuntime(options) {
151
159
  const scope = detached;
152
160
  if (scope === null || closed)
153
161
  return;
154
- scope.runInAsyncScope(() => { setImmediate(() => { void pass(); }); });
162
+ scope.runInAsyncScope(() => { setImmediate(() => { void pass().catch(() => undefined); }); });
163
+ },
164
+ async drain() {
165
+ await pass();
166
+ await Promise.allSettled([...active]);
155
167
  },
156
168
  start() {
157
169
  if (timer !== null || closed)
158
170
  return;
159
171
  detached = new AsyncResource("lead-queue-runtime");
160
- detached.runInAsyncScope(() => { timer = setInterval(() => { void pass(); }, options.everyMs ?? 2_000); timer.unref(); });
172
+ detached.runInAsyncScope(() => { timer = setInterval(() => { void pass().catch(() => undefined); }, options.everyMs ?? 2_000); timer.unref(); });
161
173
  },
162
174
  async close() { closed = true; if (timer !== null)
163
175
  clearInterval(timer); timer = null; await Promise.allSettled([...active]); },
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { chatReceiptOf, insertChatOrigin } from "./companion/chat-origin.js";
2
3
  export const LEAD_QUEUE_MAX_MESSAGES = 10;
3
4
  export const LEAD_QUEUE_MAX_CHARS = 20_000;
4
5
  export const LEAD_QUEUE_EXPIRY_MS = 7 * 86_400_000;
@@ -13,6 +14,7 @@ const readRow = (row) => ({
13
14
  revision: Number(row["revision"]), generation: Number(row["generation"]), runner: row["runner"] === null ? null : String(row["runner"]),
14
15
  turnId: row["turn_id"] === null ? null : Number(row["turn_id"]), error: row["error"] === null ? null : String(row["error"]),
15
16
  createdAt: String(row["created_at"]), text: String(row["text"] ?? ""),
17
+ origin: row["origin"] === "phone" ? "phone" : "console",
16
18
  });
17
19
  const SELECT = "SELECT q.*, m.text FROM lead_queue q JOIN lead_message m ON m.id = q.message";
18
20
  export class PersonalQueue {
@@ -98,6 +100,29 @@ export class PersonalQueue {
98
100
  return true;
99
101
  });
100
102
  }
103
+ queueFromPhone(input, now) {
104
+ return this.store.transact(() => {
105
+ const receipt = chatReceiptOf(this.db, input.origin.deviceId, input.origin.idempotencyKey);
106
+ if (receipt !== null) {
107
+ const row = receipt.requestHash === input.origin.requestHash ? this.get(receipt.message) : null;
108
+ return row === null ? { kind: "conflict" } : { kind: "queued", row, already: true };
109
+ }
110
+ const waiting = this.backlog(input.approver);
111
+ if (waiting.length >= LEAD_QUEUE_MAX_MESSAGES)
112
+ return { kind: "full", message: `${LEAD_QUEUE_MAX_MESSAGES} messages are already waiting. Wait for a reply, then send again.` };
113
+ if (waiting.reduce((sum, one) => sum + one.text.length, 0) + input.text.length > LEAD_QUEUE_MAX_CHARS) {
114
+ return { kind: "full", message: "The messages waiting are already long. Wait for a reply, then send again." };
115
+ }
116
+ const hash = leadQueuePayloadHash(input.thread, input.text, input.context);
117
+ const message = this.store.appendLeadMessage({ thread: input.thread, turn: null, role: "operator", text: input.text, pending: true }, now);
118
+ this.db.prepare(`INSERT INTO lead_queue (message, thread, approver, approver_generation, session, ceiling_digest, request_id, payload_hash, context_json, status, created_at, origin)
119
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, 'phone')`).run(message, input.thread, input.approver, input.approverGeneration, input.session, input.ceilingDigest, input.requestId, hash, input.context === null ? null : JSON.stringify(canonical(input.context)), now.toISOString());
120
+ insertChatOrigin(this.db, { ...input.origin, message, createdAt: now.toISOString() });
121
+ this.store.recordAction({ at: now.toISOString(), actor: input.approver, repo: null, taskId: input.context?.task ?? null, runId: null,
122
+ action: "phone chat message", outcome: "queued", source: "request", detail: `device ${input.origin.deviceId} · message ${message}` });
123
+ return { kind: "queued", row: this.get(message), already: false };
124
+ });
125
+ }
101
126
  defer(claim, error) {
102
127
  return Number(this.db.prepare(`UPDATE lead_queue SET status = 'queued', generation = generation + 1, revision = revision + 1, runner = NULL, claimed_at = NULL, error = ?
103
128
  WHERE message = ? AND status = 'running' AND turn_id IS NULL AND runner = ? AND generation = ?`).run(error, claim.message, claim.runner, claim.generation).changes) === 1;
@@ -122,9 +122,9 @@ export function taskWaitSnapshot(store, taskId, now, watchedRun) {
122
122
  if (!approvedNow || scope["profile_state"] !== "resolved")
123
123
  return answer("Needs a person", "Approve task", true, 1, "needs-person");
124
124
  if (state === "running" && attempt === undefined) {
125
- const liveClaim = store.handle.prepare(`SELECT 1 AS hit FROM claim INDEXED BY claim_by_task
125
+ const liveClaim = store.handle.prepare(`SELECT 1 AS hit FROM claim
126
126
  WHERE task_ref = ? AND released_at IS NULL AND expires_at > ?
127
- AND lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest INDEXED BY claim_by_task WHERE newest.task_ref = ?)
127
+ AND lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest WHERE newest.task_ref = ?)
128
128
  LIMIT 1`).get(taskRef, now.toISOString(), taskRef);
129
129
  if (liveClaim !== undefined)
130
130
  return answer("Queued", "Wait for attempt to start", false, null, null);
@@ -172,7 +172,7 @@ export function installationStatus(store, now, viewer = currentActor()?.account
172
172
  JOIN task_ref AS ref ON ref.id = run.task_ref
173
173
  JOIN claim ON claim.lease_id = run.lease_id
174
174
  WHERE run.outcome IS NULL AND claim.released_at IS NULL AND claim.expires_at > ?
175
- AND claim.lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest INDEXED BY claim_by_task WHERE newest.task_ref = run.task_ref)
175
+ AND claim.lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest WHERE newest.task_ref = run.task_ref)
176
176
  ORDER BY run.id`).all(now.toISOString()).filter(admitted);
177
177
  const phases = new Map();
178
178
  const runningTasks = runningRows.map(row => {
@@ -0,0 +1,93 @@
1
+ import { Worker } from "node:worker_threads";
2
+ export const LIVE_FULL_CHECK_EVERY_MS = 86_400_000;
3
+ export const QUICK_SUFFIX = ".quick.db";
4
+ export function liveCheckOf(file) {
5
+ return file.endsWith(QUICK_SUFFIX) ? "quick" : "integrity";
6
+ }
7
+ export const LIVE_ONLY_TABLES = Object.freeze(["live_backup", "service_lifecycle", "latency_timeline", "agent_view", "run_efficiency"]);
8
+ export const LIVENESS_COLUMNS = Object.freeze({
9
+ runner: ["heartbeat_at"], claim: ["heartbeat_at", "expires_at"], watch_lease: ["heartbeat_at", "expires_at"], watch_episode: ["ticks"],
10
+ provider_readiness: ["observed_at"], web_session: ["last_seen"], backup_lease: ["holder", "held_until"],
11
+ });
12
+ export const EXACT_TABLES = Object.freeze({
13
+ schema_version: [], service_cursor: [], wake: [], sqlite_sequence: [],
14
+ notification_delivery: [], push_delivery: [], chat_message_ref: [], team_read: [], team_request: [],
15
+ chat_runtime: ["owner", "lease_until", "generation", "heartbeat", "retry_at"],
16
+ });
17
+ export const MARKER_SOURCE = `
18
+ function backupMarker(db, crypto) {
19
+ const LIVE_ONLY = new Set(${JSON.stringify(LIVE_ONLY_TABLES)});
20
+ const EXACT = ${JSON.stringify(EXACT_TABLES)};
21
+ const LIVENESS = ${JSON.stringify(LIVENESS_COLUMNS)};
22
+ const quote = name => '"' + String(name).replaceAll('"', '""') + '"';
23
+ const plain = (key, value) => typeof value === "bigint" ? String(value) : value instanceof Uint8Array ? Buffer.from(value).toString("base64") : value;
24
+ const hash = crypto.createHash("sha256");
25
+ const put = (...parts) => { hash.update(JSON.stringify(parts, plain)); hash.update("\\n"); };
26
+ db.exec("BEGIN");
27
+ try {
28
+ // The schema itself, not its cookie: an online backup doesn't carry the cookie over, and the marker must read the
29
+ // same on the copy as on the database it copied.
30
+ put("user_version", db.prepare("PRAGMA user_version").get().user_version);
31
+ for (const one of db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name").all()) put("schema", one.type, one.name, one.tbl_name, one.sql);
32
+ const objects = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index') ORDER BY name").all();
33
+ const owner = new Map(objects.map(one => [one.name, one.tbl_name]));
34
+ const tables = new Set(objects.filter(one => one.type === "table").map(one => one.name));
35
+ for (const table of Object.keys(EXACT).sort()) {
36
+ if (!tables.has(table)) { put("absent", table); continue; }
37
+ const columns = db.prepare("PRAGMA table_info(" + quote(table) + ")").all().map(row => row.name).filter(column => !EXACT[table].includes(column));
38
+ const rows = db.prepare("SELECT " + columns.map(quote).join(", ") + " FROM " + quote(table) + " ORDER BY rowid");
39
+ rows.setReturnArrays?.(true);
40
+ put("rows", table, columns);
41
+ for (const row of rows.iterate()) {
42
+ if (table === "sqlite_sequence" && LIVE_ONLY.has(Array.isArray(row) ? row[0] : row.name)) continue;
43
+ put(row);
44
+ }
45
+ }
46
+ // Every other real table: rows, highest rowid, and each column's total length (liveness columns aside).
47
+ for (const one of objects) {
48
+ if (one.type !== "table" || one.name.startsWith("sqlite_") || LIVE_ONLY.has(one.name) || Object.hasOwn(EXACT, one.name)) continue;
49
+ if (/^CREATE\\s+VIRTUAL\\b/i.test(one.sql ?? "")) continue; // its shadow tables are real tables, read here
50
+ const skip = LIVENESS[one.name] ?? [];
51
+ const columns = db.prepare("PRAGMA table_info(" + quote(one.name) + ")").all().map(row => row.name).filter(column => !skip.includes(column));
52
+ const rowid = !/WITHOUT\\s+ROWID/i.test(one.sql ?? "");
53
+ const parts = ["count(*)", rowid ? "max(rowid)" : "NULL", ...columns.map(column => "total(length(" + quote(column) + "))")];
54
+ const totals = db.prepare("SELECT " + parts.join(", ") + " FROM " + quote(one.name));
55
+ totals.setReturnArrays?.(true);
56
+ put("table", one.name, columns, totals.get());
57
+ }
58
+ for (const tree of db.prepare("SELECT name, pageno, ncell, payload, unused FROM dbstat WHERE aggregate = TRUE ORDER BY name").all()) {
59
+ const table = owner.get(tree.name) ?? tree.name;
60
+ if (LIVE_ONLY.has(table) || Object.hasOwn(EXACT, table)) continue;
61
+ put("tree", tree.name, tree.pageno, tree.ncell, tree.payload, tree.unused);
62
+ }
63
+ } finally { db.exec("COMMIT"); }
64
+ return hash.digest("hex");
65
+ }
66
+ `;
67
+ const MARKER_THREAD = `
68
+ const { workerData, parentPort } = require("node:worker_threads");
69
+ const { DatabaseSync } = require("node:sqlite");
70
+ const crypto = require("node:crypto");
71
+ ${MARKER_SOURCE}
72
+ try {
73
+ const db = new DatabaseSync(workerData.source, { readOnly: true });
74
+ try { db.exec("PRAGMA busy_timeout = 5000"); parentPort.postMessage({ ok: true, marker: backupMarker(db, crypto) }); } finally { db.close(); }
75
+ } catch (error) {
76
+ parentPort.postMessage({ ok: false, problem: String((error && error.message) || error).slice(0, 300) });
77
+ }
78
+ `;
79
+ export function markerOffThread(source) {
80
+ return new Promise(done => {
81
+ const thread = new Worker(MARKER_THREAD, { eval: true, workerData: { source } });
82
+ let settled = false;
83
+ const finish = (answer) => { if (!settled) {
84
+ settled = true;
85
+ done(answer);
86
+ } };
87
+ thread.once("message", (message) => finish(message.ok && typeof message.marker === "string"
88
+ ? { ok: true, marker: message.marker } : { ok: false, problem: message.problem ?? "the change check failed" }));
89
+ thread.once("error", (error) => finish({ ok: false, problem: String(error.message).slice(0, 300) }));
90
+ thread.once("exit", () => finish({ ok: false, problem: "the change check stopped before it finished" }));
91
+ });
92
+ }
93
+ export const newLiveCopyMemory = () => ({ covered: null, lookedAt: null });
@@ -5,7 +5,7 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { Worker } from "node:worker_threads";
6
6
  import { checkBackupFolder, databaseTag } from "./backup.js";
7
7
  import { holdLiveBackup, liveBackupState, recordLiveBackup, releaseLiveBackup } from "./store.js";
8
- export const LIVE_EVERY_MINUTES = [1, 5, 15, 30];
8
+ import { LIVE_FULL_CHECK_EVERY_MS, liveCheckOf, MARKER_SOURCE, markerOffThread, newLiveCopyMemory, QUICK_SUFFIX } from "./live-backup-change.js";
9
9
  export const LIVE_DAILY_DAYS = 7;
10
10
  const LEASE_MS = 15 * 60_000;
11
11
  export function defaultLiveFolder(databaseFile) {
@@ -58,7 +58,7 @@ export function liveFolderProblem(folder, forbidden, protectedRoot) {
58
58
  return `${folder} goes through a link; choose its real path (${real}).`;
59
59
  return null;
60
60
  }
61
- const NAME = (tag) => new RegExp(`^live-${tag}-(\\d{4}-\\d{2}-\\d{2})-(\\d{6})(?:-(\\d+))?\\.db$`);
61
+ const NAME = (tag) => new RegExp(`^live-${tag}-(\\d{4}-\\d{2}-\\d{2})-(\\d{6})(?:-(\\d+))?(?:\\.quick)?\\.db$`);
62
62
  const PARTIAL = (tag) => new RegExp(`^\\.live-${tag}-.*\\.partial$`);
63
63
  const stampOf = (now) => now.toISOString().replace(/\.\d+Z$/, "").replace("T", "-").replace(/:/g, "");
64
64
  export function liveCopies(folder, tag) {
@@ -81,8 +81,12 @@ export function liveCopies(folder, tag) {
81
81
  catch {
82
82
  return [];
83
83
  }
84
- return [{ name, path: join(folder, name), day: m[1], order: `${m[1]}-${m[2]}-${(m[3] ?? "1").padStart(6, "0")}` }];
85
- }).sort((a, b) => a.order < b.order ? 1 : a.order > b.order ? -1 : 0).map(({ name, path, day }) => ({ name, path, day }));
84
+ const time = m[2], madeAt = `${m[1]}T${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4, 6)}.000Z`;
85
+ return [{ name, path: join(folder, name), day: m[1], check: liveCheckOf(name), madeAt, order: `${m[1]}-${m[2]}-${(m[3] ?? "1").padStart(6, "0")}` }];
86
+ }).sort((a, b) => a.order < b.order ? 1 : a.order > b.order ? -1 : 0).map(({ name, path, day, check, madeAt }) => ({ name, path, day, check, madeAt }));
87
+ }
88
+ export function lastFullCheckAt(folder, tag) {
89
+ return liveCopies(folder, tag).find(one => one.check === "integrity")?.madeAt ?? null;
86
90
  }
87
91
  export function pruneLiveCopies(folder, tag, keep, now, protect) {
88
92
  const copies = liveCopies(folder, tag);
@@ -94,8 +98,9 @@ export function pruneLiveCopies(folder, tag, keep, now, protect) {
94
98
  days.add(one.day);
95
99
  kept.add(one.path);
96
100
  }
97
- if (protect !== null)
98
- kept.add(resolve(protect));
101
+ for (const one of typeof protect === "string" || protect === null ? [protect] : protect)
102
+ if (one !== null)
103
+ kept.add(resolve(one));
99
104
  let removed = 0;
100
105
  for (const one of copies)
101
106
  if (!kept.has(one.path)) {
@@ -119,8 +124,9 @@ const COPY_THREAD = `
119
124
  const { workerData, parentPort } = require("node:worker_threads");
120
125
  const { DatabaseSync, backup } = require("node:sqlite");
121
126
  const fs = require("node:fs"), crypto = require("node:crypto"), path = require("node:path");
127
+ ${MARKER_SOURCE}
122
128
  (async () => {
123
- const { source, partial, target } = workerData;
129
+ const { source, partial, target, check } = workerData;
124
130
  try {
125
131
  const db = new DatabaseSync(source);
126
132
  db.exec("PRAGMA busy_timeout = 5000");
@@ -129,29 +135,32 @@ const fs = require("node:fs"), crypto = require("node:crypto"), path = require("
129
135
  try { await backup(db, partial, { rate: 1000000 }); } finally { db.close(); }
130
136
  fs.chmodSync(partial, 0o600);
131
137
  const copy = new DatabaseSync(partial);
132
- let schemaVersion;
138
+ let schemaVersion, marker;
133
139
  try {
134
140
  copy.exec("PRAGMA journal_mode = DELETE");
135
- const check = copy.prepare("PRAGMA integrity_check").all();
136
- if (check.length !== 1 || check[0].integrity_check !== "ok") throw new Error("the copy failed SQLite's integrity check");
141
+ const pragma = check === "integrity" ? "integrity_check" : "quick_check";
142
+ const answer = copy.prepare("PRAGMA " + pragma).all();
143
+ if (answer.length !== 1 || answer[0][pragma] !== "ok") throw new Error(check === "integrity" ? "the copy failed SQLite's integrity check" : "the copy failed SQLite's quick check");
137
144
  schemaVersion = Number(copy.prepare("SELECT version FROM schema_version").get()?.version);
138
145
  if (!Number.isSafeInteger(schemaVersion) || schemaVersion < 1) throw new Error("the copy has no settled schema version");
146
+ // A marker that can't be read (no dbstat in this SQLite) only means the next pass copies again.
147
+ try { marker = backupMarker(copy, crypto); } catch { marker = null; }
139
148
  } finally { copy.close(); }
140
149
  const hash = crypto.createHash("sha256"), buffer = Buffer.alloc(1 << 20), fd = fs.openSync(partial, "r");
141
150
  try { let n; while ((n = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, n)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
142
151
  fs.renameSync(partial, target);
143
152
  const dir = fs.openSync(path.dirname(target), "r");
144
153
  try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
145
- parentPort.postMessage({ ok: true, sha256: hash.digest("hex"), bytes: fs.statSync(target).size, schemaVersion });
154
+ parentPort.postMessage({ ok: true, sha256: hash.digest("hex"), bytes: fs.statSync(target).size, schemaVersion, marker });
146
155
  } catch (error) {
147
156
  try { fs.rmSync(partial, { force: true }); } catch {}
148
157
  parentPort.postMessage({ ok: false, problem: String((error && error.message) || error).slice(0, 300) });
149
158
  }
150
159
  })();
151
160
  `;
152
- export function copyOffThread(source, folder, tag, now) {
153
- const stamp = stampOf(now);
154
- let name = `live-${tag}-${stamp}.db`;
161
+ export function copyOffThread(source, folder, tag, now, check = "integrity") {
162
+ const stamp = stampOf(now), end = check === "quick" ? QUICK_SUFFIX : ".db";
163
+ let name = `live-${tag}-${stamp}${end}`;
155
164
  for (let n = 2; (() => { try {
156
165
  lstatSync(join(folder, name));
157
166
  return true;
@@ -159,59 +168,93 @@ export function copyOffThread(source, folder, tag, now) {
159
168
  catch {
160
169
  return false;
161
170
  } })(); n++)
162
- name = `live-${tag}-${stamp}-${n}.db`;
171
+ name = `live-${tag}-${stamp}-${n}${end}`;
163
172
  const target = join(folder, name), partial = join(folder, `.live-${tag}-${stamp}.${randomBytes(4).toString("hex")}.partial`);
164
173
  return new Promise(done => {
165
- const thread = new Worker(COPY_THREAD, { eval: true, workerData: { source, partial, target } });
174
+ const thread = new Worker(COPY_THREAD, { eval: true, workerData: { source, partial, target, check } });
166
175
  let settled = false;
167
176
  const finish = (answer) => { if (!settled) {
168
177
  settled = true;
169
178
  done(answer);
170
179
  } };
171
180
  thread.once("message", (message) => finish(message.ok
172
- ? { ok: true, copy: { file: target, sha256: String(message.sha256), bytes: Number(message.bytes), schemaVersion: Number(message.schemaVersion) } }
181
+ ? { ok: true, check, marker: typeof message.marker === "string" ? message.marker : null, copy: { file: target, sha256: String(message.sha256), bytes: Number(message.bytes), schemaVersion: Number(message.schemaVersion) } }
173
182
  : { ok: false, problem: message.problem ?? "the copy failed" }));
174
183
  thread.once("error", (error) => { rmSync(partial, { force: true }); finish({ ok: false, problem: String(error.message).slice(0, 300) }); });
175
184
  thread.once("exit", () => finish({ ok: false, problem: "the copy stopped before it finished" }));
176
185
  });
177
186
  }
178
- export function liveCopyDue(store, now) {
187
+ export function liveCopyDue(store, now, memory) {
179
188
  const state = liveBackupState(store);
180
189
  if (!state.settings.enabled)
181
190
  return false;
182
191
  const every = state.settings.everyMinutes * 60_000;
183
- const last = Math.max(state.latest === null ? 0 : Date.parse(state.latest.madeAt), state.triedAt === null ? 0 : Date.parse(state.triedAt));
192
+ const last = Math.max(state.latest === null ? 0 : Date.parse(state.latest.madeAt), state.triedAt === null ? 0 : Date.parse(state.triedAt), memory?.lookedAt ?? 0);
184
193
  return !Number.isFinite(last) || now.getTime() - last >= every;
185
194
  }
186
- export async function liveBackupPass(store, databaseFile, holder, forbidden, clock = () => new Date()) {
195
+ function stillCovers(covered, folder, tag) {
196
+ if (covered === null || liveCopies(folder, tag)[0]?.path !== covered.file)
197
+ return false;
198
+ try {
199
+ const stat = lstatSync(covered.file);
200
+ return stat.isFile() && stat.size === covered.bytes;
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ function noteQuickCopy(store, now) {
207
+ store.handle.prepare("UPDATE live_backup SET tried_at = ?, problem = NULL WHERE id = 1").run(now.toISOString());
208
+ }
209
+ export async function liveBackupPass(store, databaseFile, holder, forbidden, clock = () => new Date(), memory = newLiveCopyMemory()) {
187
210
  const now = clock();
188
- if (!liveCopyDue(store, now))
211
+ if (!liveCopyDue(store, now, memory))
189
212
  return null;
213
+ const tag = databaseTag(databaseFile), protectedRoot = dirname(defaultLiveFolder(databaseFile));
214
+ const before = liveBackupState(store);
215
+ const folder = liveFolderOf(before.settings, databaseFile);
216
+ const usable = liveFolderProblem(folder, forbidden(), protectedRoot) === null;
217
+ const lastFull = usable ? lastFullCheckAt(folder, tag) : null;
218
+ const fullAge = lastFull === null ? NaN : now.getTime() - Date.parse(lastFull);
219
+ const fullDue = !(fullAge >= 0 && fullAge < LIVE_FULL_CHECK_EVERY_MS);
220
+ if (usable && !fullDue && stillCovers(memory.covered, folder, tag)) {
221
+ const covered = memory.covered;
222
+ memory.lookedAt = now.getTime();
223
+ const seen = await markerOffThread(databaseFile);
224
+ if (seen.ok && seen.marker === covered.marker)
225
+ return { ok: true, unchanged: true, file: covered.file };
226
+ }
190
227
  if (!holdLiveBackup(store, holder, now, new Date(now.getTime() + LEASE_MS)))
191
228
  return null;
192
229
  try {
193
230
  const state = liveBackupState(store);
194
- const folder = liveFolderOf(state.settings, databaseFile);
231
+ const at = liveFolderOf(state.settings, databaseFile);
195
232
  const fail = (problem) => { recordLiveBackup(store, { ok: false, problem }, clock()); return { ok: false, problem }; };
196
- let problem = liveFolderProblem(folder, forbidden(), dirname(defaultLiveFolder(databaseFile)));
233
+ let problem = liveFolderProblem(at, forbidden(), protectedRoot);
197
234
  if (problem !== null)
198
235
  return fail(problem);
199
236
  try {
200
- mkdirSync(folder, { recursive: true, mode: 0o700 });
237
+ mkdirSync(at, { recursive: true, mode: 0o700 });
201
238
  }
202
239
  catch (error) {
203
- return fail(`${folder} couldn't be made (${error.message})`);
240
+ return fail(`${at} couldn't be made (${error.message})`);
204
241
  }
205
- problem = liveFolderProblem(folder, forbidden(), dirname(defaultLiveFolder(databaseFile)));
242
+ problem = liveFolderProblem(at, forbidden(), protectedRoot);
206
243
  if (problem !== null)
207
244
  return fail(problem);
208
- const made = await copyOffThread(databaseFile, folder, databaseTag(databaseFile), now);
245
+ const full = at !== folder || fullDue || lastFullCheckAt(at, tag) === null;
246
+ const made = await copyOffThread(databaseFile, at, tag, now, full ? "integrity" : "quick");
209
247
  if (!made.ok)
210
248
  return fail(made.problem);
211
249
  const copy = { ...made.copy, madeAt: now.toISOString() };
212
- recordLiveBackup(store, { ok: true, copy }, clock());
213
- pruneLiveCopies(folder, databaseTag(databaseFile), state.settings.keep, clock(), copy.file);
214
- return { ok: true, copy };
250
+ if (made.check === "integrity")
251
+ recordLiveBackup(store, { ok: true, copy }, clock());
252
+ else
253
+ noteQuickCopy(store, clock());
254
+ memory.covered = made.marker === null ? null : { file: copy.file, bytes: copy.bytes, marker: made.marker };
255
+ memory.lookedAt = now.getTime();
256
+ pruneLiveCopies(at, tag, state.settings.keep, clock(), [copy.file, liveBackupState(store).latest?.file ?? null]);
257
+ return { ok: true, copy, check: made.check };
215
258
  }
216
259
  finally {
217
260
  releaseLiveBackup(store, holder);
@@ -219,11 +262,12 @@ export async function liveBackupPass(store, databaseFile, holder, forbidden, clo
219
262
  }
220
263
  export function startLiveBackups(store, databaseFile, forbidden, everyMs = 60_000) {
221
264
  const holder = `${hostname()}:${process.pid}:${randomUUID().slice(0, 8)}`;
265
+ const memory = newLiveCopyMemory();
222
266
  let stopped = false, timer = null, running = Promise.resolve();
223
267
  const pass = () => {
224
268
  if (stopped)
225
269
  return;
226
- running = liveBackupPass(store, databaseFile, holder, forbidden).catch(() => null).finally(() => {
270
+ running = liveBackupPass(store, databaseFile, holder, forbidden, () => new Date(), memory).catch(() => null).finally(() => {
227
271
  if (!stopped) {
228
272
  timer = setTimeout(pass, everyMs);
229
273
  timer.unref?.();
package/dist/live-bus.js CHANGED
@@ -271,6 +271,7 @@ export function createLiveRooms(fingerprint, presence, options = {}) {
271
271
  const safetyNetMs = options.safetyNetMs ?? SAFETY_NET_MS;
272
272
  const minIntervalMs = options.minIntervalMs ?? 0;
273
273
  const readSettleMs = options.readSettleMs ?? 0;
274
+ const frameOf = options.frame ?? ((at) => ({ at }));
274
275
  const rooms = new Map();
275
276
  let unsubscribe = null;
276
277
  const announce = (key, room) => {
@@ -384,7 +385,7 @@ export function createLiveRooms(fingerprint, presence, options = {}) {
384
385
  const say = (key, room) => {
385
386
  room.saidAt = Date.now();
386
387
  for (const viewer of [...room.viewers.keys()])
387
- deliver(key, room, viewer, "change", { at: room.last, revision: room.revision }, room.lastOrder || undefined);
388
+ deliver(key, room, viewer, "change", { ...frameOf(room.last), revision: room.revision }, room.lastOrder || undefined);
388
389
  };
389
390
  const heard = (change) => {
390
391
  for (const [key, room] of [...rooms]) {
@@ -422,7 +423,7 @@ export function createLiveRooms(fingerprint, presence, options = {}) {
422
423
  const forget = viewer.connection.onClose(() => leave(key, viewer));
423
424
  const unprove = viewer.connection.onKeepAlive(() => { deliver(key, joined, viewer); });
424
425
  room.viewers.set(viewer, () => { forget(); unprove(); });
425
- if (!deliver(key, room, viewer, "change", { at: room.last, revision: bus?.revision() ?? null }, room.lastOrder || undefined) || presence === null)
426
+ if (!deliver(key, room, viewer, "change", { ...frameOf(room.last), revision: bus?.revision() ?? null }, room.lastOrder || undefined) || presence === null)
426
427
  return;
427
428
  if (deliver(key, room, viewer, "here", { people: presence([...room.viewers.keys()], viewer.name) }, room.order = liveOrderAfter(room.order)))
428
429
  announce(key, room);
@@ -264,7 +264,6 @@ function liveHost(given) {
264
264
  }
265
265
  }
266
266
  const short = (given) => (typeof given === "string" ? liveTarget(given.split(/\r?\n/)[0] ?? "", SHORT_CAP) : null);
267
- export const liveShort = short;
268
267
  const CLAUDE_KINDS = new Map([
269
268
  ["Edit", "edit"], ["Write", "edit"], ["MultiEdit", "edit"], ["NotebookEdit", "edit"],
270
269
  ["Bash", "command"], ["Read", "read"], ["LS", "read"], ["Glob", "search"], ["Grep", "search"],
@@ -1,7 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { currentActor } from "./actor.js";
3
3
  import { activeRemote } from "./remote-run.js";
4
- export const AUTHORITIES = Object.freeze(["full", "local-owner"]);
5
4
  export function authorityOf(value) {
6
5
  return value === "full" || value === "local-owner" ? value : null;
7
6
  }