maka-agent 0.2.0-dev.27.20260910 → 0.2.0-dev.28.20260911

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 (76) hide show
  1. package/LICENSE +106 -0
  2. package/dist/cli-core.js +7 -0
  3. package/dist/runtime-host-run-command.js +15 -7
  4. package/dist/session-import-command.js +69 -0
  5. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  6. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  7. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  8. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +9 -4
  11. package/node_modules/@maka/core/dist/diagnostic-log.js +18 -7
  12. package/node_modules/@maka/core/dist/text-sanitize.js +8 -2
  13. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +8 -8
  14. package/node_modules/@maka/runtime/dist/archive-read-tool.js +3 -1
  15. package/node_modules/@maka/runtime/dist/bots/bot-test.js +2 -1
  16. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +24 -20
  17. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +5 -3
  18. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +87 -29
  19. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +40 -36
  20. package/node_modules/@maka/runtime/dist/computer-use-tools.js +4 -1
  21. package/node_modules/@maka/runtime/dist/deep-research-tools.js +11 -5
  22. package/node_modules/@maka/runtime/dist/edit-replace.js +2 -2
  23. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +5 -6
  24. package/node_modules/@maka/runtime/dist/memory-extraction-evidence.js +7 -1
  25. package/node_modules/@maka/runtime/dist/memory-extraction.js +12 -7
  26. package/node_modules/@maka/runtime/dist/openai-responses-websocket.js +2 -5
  27. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +11 -2
  28. package/node_modules/@maka/runtime/dist/request-customization-fetch.js +14 -7
  29. package/node_modules/@maka/runtime/dist/session-export.js +1 -0
  30. package/node_modules/@maka/runtime/dist/session-import.js +100 -0
  31. package/node_modules/@maka/runtime/dist/session-manager.js +6 -1
  32. package/node_modules/@maka/runtime/dist/shell-run-manager.js +9 -6
  33. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +13 -6
  34. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +43 -10
  35. package/node_modules/@maka/runtime/dist/stream-graph-handoff.js +6 -1
  36. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +1 -4
  37. package/node_modules/@maka/runtime/dist/system-prompt/workspace-instructions.js +11 -6
  38. package/node_modules/@maka/runtime/dist/tavily-search.js +8 -2
  39. package/node_modules/@maka/runtime/dist/text-line-window.js +49 -0
  40. package/node_modules/@maka/runtime/dist/tool-output.js +35 -12
  41. package/node_modules/@maka/runtime/dist/unified-diff.js +40 -10
  42. package/node_modules/@maka/runtime/dist/web-fetch-tool.js +4 -2
  43. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +82 -33
  44. package/node_modules/@maka/runtime/dist/workspace-executor.js +2 -6
  45. package/node_modules/@maka/runtime/package.json +2 -1
  46. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +6 -6
  47. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +7 -4
  48. package/node_modules/@maka/runtime-host/dist/protocol/artifact.js +2 -2
  49. package/node_modules/@maka/runtime-host/dist/protocol/index.js +2 -1
  50. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +3 -2
  51. package/node_modules/@maka/runtime-host/dist/protocol/skill-catalog.js +2 -1
  52. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -0
  53. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +29 -4
  54. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +6 -1
  55. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +35 -4
  56. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +24 -8
  57. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +17 -8
  58. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-projection.js +3 -9
  59. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +20 -21
  60. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +24 -2
  61. package/node_modules/@maka/runtime-host/dist/server/skill-catalog-coordinator.js +18 -2
  62. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +4 -1
  63. package/node_modules/@maka/runtime-host/dist/transport/local-ipc-framing.js +4 -2
  64. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +9 -8
  65. package/node_modules/@maka/runtime-host/dist/transport/resumable-peer-stream.js +14 -9
  66. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +19 -4
  67. package/node_modules/@maka/storage/dist/context-value-mutation-gate.js +59 -0
  68. package/node_modules/@maka/storage/dist/session-bundle-policy.js +579 -7
  69. package/node_modules/@maka/storage/dist/session-message-projection.js +8 -4
  70. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +18 -4
  71. package/node_modules/@maka/storage/dist/stable-storage.js +2 -1
  72. package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs +22 -5
  73. package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs +22 -5
  74. package/node_modules/zod/v4/core/memoizer.cjs +12 -16
  75. package/node_modules/zod/v4/core/memoizer.js +12 -16
  76. package/package.json +1 -1
@@ -131,13 +131,11 @@ export class SessionContinuityCoordinator {
131
131
  if (this.#connections.has(connectionId)) {
132
132
  throw new Error(`Duplicate Runtime Host connection: ${connectionId}`);
133
133
  }
134
- const closed = signal();
135
134
  this.#connections.set(connectionId, {
136
135
  sink,
137
136
  subscriptionIds: new Set(),
138
137
  pendingOpenCount: 0,
139
- closed: closed.promise,
140
- resolveClosed: closed.resolve,
138
+ closed: new AbortController(),
141
139
  });
142
140
  let attached = true;
143
141
  return {
@@ -639,12 +637,7 @@ export class SessionContinuityCoordinator {
639
637
  const throughSequence = await this.#transcriptReader.readDurableHighWater(sessionId);
640
638
  cachedTranscriptOverlay = this.#prepareTranscriptOverlay(committed.state, sessionId, throughSequence, preparationPermit);
641
639
  cachedTranscriptOverlay.pendingConsumers += 1;
642
- retainedTranscriptOverlay = await Promise.race([
643
- cachedTranscriptOverlay.prepared,
644
- connection.closed.then(() => {
645
- throw new Error('Runtime Host connection closed during subscription open');
646
- }),
647
- ]);
640
+ retainedTranscriptOverlay = await waitForConnectionOpen(cachedTranscriptOverlay.prepared, connection.closed.signal);
648
641
  const snapshot = projectSessionSnapshot(committed.value, identity.principalKind);
649
642
  const created = await createSessionTranscriptBootstrap({
650
643
  reader: this.#transcriptReader,
@@ -918,12 +911,7 @@ export class SessionContinuityCoordinator {
918
911
  const ticket = this.#queueTranscriptOverlayPreparation();
919
912
  let release;
920
913
  try {
921
- release = await Promise.race([
922
- ticket.ready,
923
- connection.closed.then(() => {
924
- throw new Error('Runtime Host connection closed during subscription open');
925
- }),
926
- ]);
914
+ release = await waitForConnectionOpen(ticket.ready, connection.closed.signal);
927
915
  }
928
916
  catch (error) {
929
917
  this.#cancelTranscriptOverlayPreparation(ticket.waiter);
@@ -1118,7 +1106,7 @@ export class SessionContinuityCoordinator {
1118
1106
  const connection = this.#connections.get(connectionId);
1119
1107
  if (!connection)
1120
1108
  return;
1121
- connection.resolveClosed();
1109
+ connection.closed.abort(new Error('Runtime Host connection closed during subscription open'));
1122
1110
  for (const subscriptionId of [...connection.subscriptionIds]) {
1123
1111
  const subscriber = this.#ownedSubscriber(connectionId, subscriptionId);
1124
1112
  if (subscriber)
@@ -1794,10 +1782,21 @@ function toolStartShellRunRef(event) {
1794
1782
  return undefined;
1795
1783
  }
1796
1784
  }
1797
- function signal() {
1798
- let resolve;
1799
- const promise = new Promise((settle) => {
1800
- resolve = settle;
1785
+ function waitForConnectionOpen(task, closed) {
1786
+ // A race against a connection-lifetime Promise retains every winning overlay
1787
+ // until disconnect. Remove the close listener as soon as this wait finishes.
1788
+ return new Promise((resolve, reject) => {
1789
+ const onClose = () => reject(closed.reason);
1790
+ if (closed.aborted)
1791
+ onClose();
1792
+ else
1793
+ closed.addEventListener('abort', onClose, { once: true });
1794
+ void task.then((value) => {
1795
+ closed.removeEventListener('abort', onClose);
1796
+ resolve(value);
1797
+ }, (error) => {
1798
+ closed.removeEventListener('abort', onClose);
1799
+ reject(error);
1800
+ });
1801
1801
  });
1802
- return { promise, resolve };
1803
1802
  }
@@ -126,7 +126,7 @@ export async function readSessionTranscriptPage(input) {
126
126
  const storage = state.projection === 'shared'
127
127
  ? await readSharedDurablePage(input.reader, state.sessionId, durableRequest, position.rangeBoundarySequence)
128
128
  : await input.reader.readDurablePage(state.sessionId, durableRequest);
129
- const selected = storageSelection(storage);
129
+ const selected = selectionThroughRangeBoundary(storageSelection(storage), request.direction, position.rangeBoundarySequence);
130
130
  const rangeEdges = await readRangeEdges({
131
131
  reader: input.reader,
132
132
  state,
@@ -275,7 +275,7 @@ async function readRangeEdges(input) {
275
275
  const fragments = input.selected.fragments.filter((fragment) => fragment.kind === 'durable' && retainedSequences.has(fragment.sequence));
276
276
  return {
277
277
  fragments,
278
- rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.from(fragment.data, 'base64').byteLength, 0),
278
+ rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.byteLength(fragment.data, 'base64'), 0),
279
279
  next: { position: rangeRecords[retainedEnd].sequence, byteOffset: null },
280
280
  };
281
281
  })();
@@ -440,6 +440,28 @@ function storageSelection(storage) {
440
440
  next: storage.next,
441
441
  };
442
442
  }
443
+ function selectionThroughRangeBoundary(selected, direction, rangeBoundarySequence) {
444
+ if (rangeBoundarySequence === null)
445
+ return selected;
446
+ // RuntimeEvent-backed message sequences are sparse, so a continuation's
447
+ // message limit cannot infer how many records remain from sequence distance.
448
+ const firstOmittedIndex = selected.fragments.findIndex((fragment) => fragment.kind === 'durable' &&
449
+ (direction === 'older'
450
+ ? fragment.sequence < rangeBoundarySequence
451
+ : fragment.sequence > rangeBoundarySequence));
452
+ if (firstOmittedIndex === -1)
453
+ return selected;
454
+ const firstOmitted = selected.fragments[firstOmittedIndex];
455
+ if (firstOmitted.kind !== 'durable') {
456
+ throw new Error('Session transcript durable range contained an overlay fragment');
457
+ }
458
+ const fragments = selected.fragments.slice(0, firstOmittedIndex);
459
+ return {
460
+ fragments,
461
+ rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.from(fragment.data, 'base64').byteLength, 0),
462
+ next: { position: firstOmitted.sequence, byteOffset: null },
463
+ };
464
+ }
443
465
  function selectOverlay(messages, direction, position, byteOffset, maxBytes, maxMessages = SESSION_TRANSCRIPT_PAGE_MAX_MESSAGES) {
444
466
  const fragments = [];
445
467
  let rawBytes = 0;
@@ -18,6 +18,14 @@
18
18
  */
19
19
  import { SkillCatalogRepositoryError, } from './skill-catalog-repository.js';
20
20
  import { WorkspaceResolutionError, } from './workspace-resolver.js';
21
+ export class SkillCatalogInvocableContextError extends Error {
22
+ code;
23
+ name = 'SkillCatalogInvocableContextError';
24
+ constructor(code, message) {
25
+ super(message);
26
+ this.code = code;
27
+ }
28
+ }
21
29
  /** Serialized single authority lane for catalog recovery, reads, and mutations. */
22
30
  export class HostSkillCatalogCoordinator {
23
31
  handlers = {
@@ -58,6 +66,14 @@ export class HostSkillCatalogCoordinator {
58
66
  return this.#admitProtocolOperation('skill.catalog.invocable.query', async () => {
59
67
  const resolved = await this.#resolveInvocableContext(input, context);
60
68
  return this.#repository.queryInvocable(repositoryInvocableQueryInput(input), { projectRoot: resolved.projectRoot }, resolved.host);
69
+ }, (error) => {
70
+ if (error instanceof SkillCatalogInvocableContextError) {
71
+ return {
72
+ ok: false,
73
+ error: { code: error.code, message: error.message },
74
+ };
75
+ }
76
+ return repositoryFailure('skill.catalog.invocable.query', error);
61
77
  });
62
78
  }
63
79
  mutate(input) {
@@ -83,7 +99,7 @@ export class HostSkillCatalogCoordinator {
83
99
  this.#closePromise = this.#tail;
84
100
  return this.#closePromise;
85
101
  }
86
- #admitProtocolOperation(operation, run) {
102
+ #admitProtocolOperation(operation, run, onFailure = (error) => repositoryFailure(operation, error)) {
87
103
  if (!this.#accepting) {
88
104
  return Promise.resolve({
89
105
  ok: false,
@@ -95,7 +111,7 @@ export class HostSkillCatalogCoordinator {
95
111
  return { ok: true, result: await run() };
96
112
  }
97
113
  catch (error) {
98
- return repositoryFailure(operation, error);
114
+ return onFailure(error);
99
115
  }
100
116
  });
101
117
  }
@@ -137,7 +137,10 @@ export class FramedByteStreamTransport {
137
137
  break;
138
138
  }
139
139
  const encoded = this.#buffered.subarray(0, encodedBytes);
140
- this.#buffered = this.#buffered.subarray(encodedBytes);
140
+ this.#buffered =
141
+ encodedBytes === this.#buffered.byteLength
142
+ ? Buffer.alloc(0)
143
+ : this.#buffered.subarray(encodedBytes);
141
144
  const frames = this.#decoder.push(encoded);
142
145
  if (frames.length !== 1) {
143
146
  throw new Error('Runtime Host decoder did not produce one complete frame');
@@ -35,8 +35,10 @@ export class LocalIpcProtocolFrameDecoder {
35
35
  if (this.#pending.byteLength + segment.byteLength > RUNTIME_HOST_MAX_MESSAGE_BYTES) {
36
36
  throw new RuntimeHostProtocolError('frame_too_large', 'Runtime Host message exceeds the byte limit');
37
37
  }
38
- if (segment.byteLength > 0)
39
- this.#pending = Buffer.concat([this.#pending, segment]);
38
+ if (segment.byteLength > 0) {
39
+ this.#pending =
40
+ this.#pending.byteLength === 0 ? segment : Buffer.concat([this.#pending, segment]);
41
+ }
40
42
  if (newline === -1)
41
43
  break;
42
44
  frames.push(this.#decodePending());
@@ -157,7 +157,7 @@ async function readBoundedJsonLine(stream, maxBytes, label) {
157
157
  const encoded = buffered.subarray(0, newline);
158
158
  return {
159
159
  value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(encoded)),
160
- remainder: buffered.subarray(newline + 1),
160
+ remainder: newline + 1 === buffered.length ? Buffer.alloc(0) : buffered.subarray(newline + 1),
161
161
  };
162
162
  }
163
163
  if (buffered.byteLength >= maxBytes) {
@@ -176,18 +176,16 @@ export class RuntimeHostPeerByteStream {
176
176
  #endListeners = new Set();
177
177
  #errorListeners = new Set();
178
178
  #stream;
179
- #initialData;
180
179
  #resolveClosed;
181
180
  #resume;
182
181
  #paused = false;
183
182
  #closed = false;
184
183
  constructor(stream, initialData = Buffer.alloc(0)) {
185
184
  this.#stream = stream;
186
- this.#initialData = initialData;
187
185
  this.closed = new Promise((resolve) => {
188
186
  this.#resolveClosed = resolve;
189
187
  });
190
- queueMicrotask(() => void this.#pump());
188
+ queueMicrotask(() => void this.#pump(initialData));
191
189
  }
192
190
  onData(listener) {
193
191
  this.#dataListeners.add(listener);
@@ -221,10 +219,11 @@ export class RuntimeHostPeerByteStream {
221
219
  this.#resume?.();
222
220
  this.#resume = undefined;
223
221
  }
224
- async #pump() {
222
+ async #pump(initialData) {
225
223
  try {
226
- if (this.#initialData.byteLength > 0)
227
- this.#emitData(this.#initialData);
224
+ if (initialData.byteLength > 0)
225
+ this.#emitData(initialData);
226
+ initialData = Buffer.alloc(0);
228
227
  while (!this.#closed) {
229
228
  if (this.#paused) {
230
229
  await new Promise((resolve) => {
@@ -233,13 +232,15 @@ export class RuntimeHostPeerByteStream {
233
232
  if (this.#closed)
234
233
  return;
235
234
  }
236
- const chunk = await this.#stream.read();
235
+ let chunk = await this.#stream.read();
237
236
  if (!chunk) {
238
237
  for (const listener of this.#endListeners)
239
238
  listener();
240
239
  return;
241
240
  }
242
241
  this.#emitData(chunk);
242
+ // Listeners own any data they retain; the read loop no longer needs it.
243
+ chunk = null;
243
244
  }
244
245
  }
245
246
  catch (error) {
@@ -111,7 +111,8 @@ export class ResumablePeerStream {
111
111
  }
112
112
  const old = this.#path;
113
113
  const path = {
114
- ...attachment,
114
+ stream: attachment.stream,
115
+ received: attachment.received,
115
116
  sent: this.#acknowledged,
116
117
  acknowledged: -1,
117
118
  pong: undefined,
@@ -123,7 +124,7 @@ export class ResumablePeerStream {
123
124
  this.#recoveryStarted = undefined;
124
125
  old?.stream.abort();
125
126
  this.#notify();
126
- void this.#pumpRead(path).catch((error) => this.#pathFailed(path, error));
127
+ void this.#pumpRead(path, attachment.remainder).catch((error) => this.#pathFailed(path, error));
127
128
  void this.#pumpWrite(path).catch((error) => this.#pathFailed(path, error));
128
129
  }
129
130
  async read() {
@@ -223,16 +224,17 @@ export class ResumablePeerStream {
223
224
  this.#outgoing.shift();
224
225
  this.#notify();
225
226
  }
226
- async #pumpRead(path) {
227
- let buffered = path.remainder;
227
+ async #pumpRead(path, buffered) {
228
+ // Suspended reads retain locals: drop consumed chunks and backing-buffer views before awaiting.
228
229
  while (this.#path === path && !this.#ended) {
229
230
  if (buffered.length < HEADER_BYTES) {
230
- const chunk = await path.stream.read();
231
+ let chunk = await path.stream.read();
231
232
  if (!chunk)
232
233
  throw new Error('Peer path ended');
233
234
  if (this.#path !== path)
234
235
  return;
235
236
  buffered = Buffer.concat([buffered, chunk]);
237
+ chunk = null;
236
238
  continue;
237
239
  }
238
240
  const type = buffered[0];
@@ -244,17 +246,16 @@ export class ResumablePeerStream {
244
246
  throw new PeerResumeRejectedError('Invalid peer stream frame');
245
247
  }
246
248
  if (buffered.length < HEADER_BYTES + size) {
247
- const chunk = await path.stream.read();
249
+ let chunk = await path.stream.read();
248
250
  if (!chunk)
249
251
  throw new Error('Peer path ended inside frame');
250
252
  if (this.#path !== path)
251
253
  return;
252
254
  buffered = Buffer.concat([buffered, chunk]);
255
+ chunk = null;
253
256
  continue;
254
257
  }
255
258
  const offset = Number(wideOffset);
256
- const bytes = buffered.subarray(HEADER_BYTES, HEADER_BYTES + size);
257
- buffered = buffered.subarray(HEADER_BYTES + size);
258
259
  switch (type) {
259
260
  case DATA:
260
261
  if (size === 0 || this.#remoteFin)
@@ -263,7 +264,7 @@ export class ResumablePeerStream {
263
264
  break; // Lost ACK: already retained/delivered.
264
265
  if (offset !== this.#received || this.#received - this.#consumed + size > WINDOW_BYTES)
265
266
  throw new PeerResumeRejectedError('Peer stream receive window violated');
266
- this.#incoming.push(Buffer.from(bytes));
267
+ this.#incoming.push(Buffer.from(buffered.subarray(HEADER_BYTES, HEADER_BYTES + size)));
267
268
  this.#received += size;
268
269
  break;
269
270
  case ACK:
@@ -289,6 +290,10 @@ export class ResumablePeerStream {
289
290
  default:
290
291
  throw new PeerResumeRejectedError('Unknown peer stream frame');
291
292
  }
293
+ buffered =
294
+ buffered.length === HEADER_BYTES + size
295
+ ? Buffer.alloc(0)
296
+ : buffered.subarray(HEADER_BYTES + size);
292
297
  this.#notify();
293
298
  }
294
299
  }
@@ -22,7 +22,7 @@ import { chmod, copyFile, lstat, mkdir, realpath } from 'node:fs/promises';
22
22
  import { dirname, join, resolve } from 'node:path';
23
23
  import { backup, DatabaseSync } from 'node:sqlite';
24
24
  import { isCanonicalStorageRef } from '@maka/core/events';
25
- import { discoverMarkedStorageRoot, runWithStorageRootLease, tryAcquireInteractiveRootOwner, } from './root-authority.js';
25
+ import { discoverMarkedStorageRoot, resolveStorageRoot, runWithStorageRootLease, tryAcquireInteractiveRootOwner, } from './root-authority.js';
26
26
  import { migrateSqliteContextOffloadDatabase, SQLITE_CONTEXT_OFFLOAD_SCHEMA_VERSION, } from './sqlite-context-offload-schema.js';
27
27
  import { CONTEXT_OFFLOAD_DATABASE_NAME, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, } from './sqlite-context-offload-store.js';
28
28
  import { syncDirectoryChain, syncFile } from './stable-storage.js';
@@ -32,10 +32,25 @@ import { SQLITE_SESSION_MESSAGE_CHUNK_MARKER } from './sqlite-session-metadata-s
32
32
  * snapshots require the root owner: a Session gate does not fence global GC.
33
33
  * The callback must recheck absence before publishing an artifact-only snapshot.
34
34
  */
35
- export async function withOfflineContextSnapshot(root, operation) {
36
- if (!(await exists(join(root, CONTEXT_OFFLOAD_DATABASE_NAME))))
35
+ export async function withOfflineContextSnapshot(root, operation, options = {}) {
36
+ if (options.requireAuthority !== true &&
37
+ !(await exists(join(root, CONTEXT_OFFLOAD_DATABASE_NAME)))) {
37
38
  return operation(false);
38
- const capability = await discoverMarkedStorageRoot({ path: root });
39
+ }
40
+ const lease = options.lease;
41
+ if (lease) {
42
+ if ((await realpath(root).catch(() => resolve(root))) !== lease.canonicalPath) {
43
+ throw new Error('Context snapshot lease does not name this Storage Root');
44
+ }
45
+ return runWithStorageRootLease(lease, 'interactive', 'write', () => operation(true));
46
+ }
47
+ // Discovery finds a marked root; it does not make one. A workspace that has
48
+ // never been opened is exactly the target an import writes to first, so when
49
+ // the caller says it is about to write, the root is resolved -- which
50
+ // initialises it -- rather than merely looked for.
51
+ const capability = options.requireAuthority === true
52
+ ? await resolveStorageRoot({ path: root, kind: 'interactive' })
53
+ : await discoverMarkedStorageRoot({ path: root });
39
54
  const owner = await tryAcquireInteractiveRootOwner(capability);
40
55
  if (!owner)
41
56
  throw new Error('Context snapshot requires an offline Storage Root; stop the Runtime Host first');
@@ -0,0 +1,59 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ /**
20
+ * Serialises every mutation of a Storage Root's managed context values.
21
+ *
22
+ * The Context Store's own operations read database state, await, and then act
23
+ * on files -- garbage collection decides a payload is unreferenced, awaits, and
24
+ * unlinks it. A second writer that commits a reference to that payload inside
25
+ * the await leaves a reference pointing at a file that is about to disappear.
26
+ * The re-check garbage collection performs cannot see it, because the check and
27
+ * the unlink straddle the await.
28
+ *
29
+ * The Store used to serialise those operations against each other through a
30
+ * private promise tail, which fenced nothing outside the instance. This is the
31
+ * same queue, keyed by Storage Root, so that an importer publishing payloads
32
+ * into a live workspace takes its turn alongside the Store's own publication
33
+ * and collection rather than interleaving with them.
34
+ *
35
+ * In-process is the whole boundary: the interactive write authority is an
36
+ * exclusive election, so one process at a time can mutate a root's context.
37
+ *
38
+ * `root` must already be canonical -- the same string the Store derives with
39
+ * `realpath`. Two spellings of one directory would be two queues and fence
40
+ * nothing.
41
+ */
42
+ const gates = new Map();
43
+ export async function runWithContextValueMutation(root, operation) {
44
+ const previous = gates.get(root);
45
+ let release;
46
+ const current = new Promise((resolve) => {
47
+ release = resolve;
48
+ });
49
+ gates.set(root, current);
50
+ await previous?.catch(() => { });
51
+ try {
52
+ return await operation();
53
+ }
54
+ finally {
55
+ release();
56
+ if (gates.get(root) === current)
57
+ gates.delete(root);
58
+ }
59
+ }