borgmcp 5.4.1 → 5.6.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 (101) hide show
  1. package/README.md +15 -0
  2. package/dist/assimilate-cmd.d.ts +8 -1
  3. package/dist/assimilate-cmd.d.ts.map +1 -1
  4. package/dist/assimilate-cmd.js +54 -21
  5. package/dist/assimilate-cmd.js.map +1 -1
  6. package/dist/claude.d.ts.map +1 -1
  7. package/dist/claude.js +30 -0
  8. package/dist/claude.js.map +1 -1
  9. package/dist/cli-help.d.ts +1 -0
  10. package/dist/cli-help.d.ts.map +1 -1
  11. package/dist/cli-help.js +45 -0
  12. package/dist/cli-help.js.map +1 -1
  13. package/dist/docs-sections.d.ts.map +1 -1
  14. package/dist/docs-sections.js +8 -0
  15. package/dist/docs-sections.js.map +1 -1
  16. package/dist/local-server-cursor.d.ts +10 -1
  17. package/dist/local-server-cursor.d.ts.map +1 -1
  18. package/dist/local-server-cursor.js +64 -5
  19. package/dist/local-server-cursor.js.map +1 -1
  20. package/dist/log-stream.d.ts +13 -0
  21. package/dist/log-stream.d.ts.map +1 -1
  22. package/dist/log-stream.js +45 -13
  23. package/dist/log-stream.js.map +1 -1
  24. package/dist/remote-client.d.ts +17 -0
  25. package/dist/remote-client.d.ts.map +1 -1
  26. package/dist/remote-client.js +37 -15
  27. package/dist/remote-client.js.map +1 -1
  28. package/dist/representative-cmd.d.ts +94 -0
  29. package/dist/representative-cmd.d.ts.map +1 -0
  30. package/dist/representative-cmd.js +290 -0
  31. package/dist/representative-cmd.js.map +1 -0
  32. package/dist/representative-core.d.ts +243 -0
  33. package/dist/representative-core.d.ts.map +1 -0
  34. package/dist/representative-core.js +679 -0
  35. package/dist/representative-core.js.map +1 -0
  36. package/dist/representative-delivery-store.d.ts +79 -0
  37. package/dist/representative-delivery-store.d.ts.map +1 -0
  38. package/dist/representative-delivery-store.js +233 -0
  39. package/dist/representative-delivery-store.js.map +1 -0
  40. package/dist/representative-listener-store.d.ts +46 -0
  41. package/dist/representative-listener-store.d.ts.map +1 -0
  42. package/dist/representative-listener-store.js +119 -0
  43. package/dist/representative-listener-store.js.map +1 -0
  44. package/dist/representative-listener.d.ts +32 -0
  45. package/dist/representative-listener.d.ts.map +1 -0
  46. package/dist/representative-listener.js +293 -0
  47. package/dist/representative-listener.js.map +1 -0
  48. package/dist/representative-mcp.d.ts +37 -0
  49. package/dist/representative-mcp.d.ts.map +1 -0
  50. package/dist/representative-mcp.js +211 -0
  51. package/dist/representative-mcp.js.map +1 -0
  52. package/dist/representative-owner.d.ts +10 -0
  53. package/dist/representative-owner.d.ts.map +1 -0
  54. package/dist/representative-owner.js +107 -0
  55. package/dist/representative-owner.js.map +1 -0
  56. package/dist/representative-store.d.ts +68 -0
  57. package/dist/representative-store.d.ts.map +1 -0
  58. package/dist/representative-store.js +173 -0
  59. package/dist/representative-store.js.map +1 -0
  60. package/dist/seat-probe.d.ts +1 -0
  61. package/dist/seat-probe.d.ts.map +1 -1
  62. package/dist/seat-probe.js +1 -1
  63. package/dist/seat-probe.js.map +1 -1
  64. package/dist/seat-store.d.ts +13 -0
  65. package/dist/seat-store.d.ts.map +1 -1
  66. package/dist/seat-store.js +55 -10
  67. package/dist/seat-store.js.map +1 -1
  68. package/dist/server-trust.d.ts +10 -0
  69. package/dist/server-trust.d.ts.map +1 -1
  70. package/dist/server-trust.js +23 -6
  71. package/dist/server-trust.js.map +1 -1
  72. package/dist/stream-owner.d.ts +10 -0
  73. package/dist/stream-owner.d.ts.map +1 -1
  74. package/dist/stream-owner.js +129 -21
  75. package/dist/stream-owner.js.map +1 -1
  76. package/dist/unknown-subcommand.d.ts +1 -1
  77. package/dist/unknown-subcommand.d.ts.map +1 -1
  78. package/dist/unknown-subcommand.js +1 -0
  79. package/dist/unknown-subcommand.js.map +1 -1
  80. package/docs/HUMAN_REPRESENTATIVE.md +434 -0
  81. package/package.json +1 -1
  82. package/src/assimilate-cmd.ts +73 -22
  83. package/src/claude.ts +30 -0
  84. package/src/cli-help.ts +48 -0
  85. package/src/docs-sections.ts +8 -0
  86. package/src/local-server-cursor.ts +56 -4
  87. package/src/log-stream.ts +47 -14
  88. package/src/remote-client.ts +54 -13
  89. package/src/representative-cmd.ts +369 -0
  90. package/src/representative-core.ts +908 -0
  91. package/src/representative-delivery-store.ts +235 -0
  92. package/src/representative-listener-store.ts +115 -0
  93. package/src/representative-listener.ts +215 -0
  94. package/src/representative-mcp.ts +250 -0
  95. package/src/representative-owner.ts +105 -0
  96. package/src/representative-store.ts +224 -0
  97. package/src/seat-probe.ts +1 -1
  98. package/src/seat-store.ts +61 -10
  99. package/src/server-trust.ts +25 -6
  100. package/src/stream-owner.ts +129 -20
  101. package/src/unknown-subcommand.ts +1 -0
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Restricted stdio MCP facade for the human representative.
3
+ *
4
+ * A Borg server speaks pinned-TLS HTTPS, not MCP, so a generic MCP host reaches
5
+ * it through this local stdio process. The surface is five tools: status, send
6
+ * (to the ONE bound Coordinator), read (that Coordinator's replies), deliver
7
+ * (the host's durable delivery checkpoint) and ack.
8
+ * There is deliberately no log/broadcast/dispatch, roster-management, grant,
9
+ * evict, release, regen or server-lifecycle tool, and no dispatcher escape hatch.
10
+ *
11
+ * The connection context is resolved per call and injected, so the same facade
12
+ * runs over the real seat-scoped backend or a controlled test backend.
13
+ */
14
+
15
+ import { ErrorCode } from 'borgmcp-shared/protocol';
16
+ import type { Readable, Writable } from 'node:stream';
17
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
18
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
19
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
20
+ import {
21
+ REPRESENTATIVE_DELIVERY_NOTE,
22
+ REPRESENTATIVE_MESSAGE_LIMIT_BYTES,
23
+ RepresentativeError,
24
+ ackRepresentativeReply,
25
+ deliverRepresentativeReplies,
26
+ readRepresentativeReplies,
27
+ serializeRepresentativeResult,
28
+ representativeStatus,
29
+ sendRepresentativeMessage,
30
+ type RepresentativeContext,
31
+ } from './representative-core.js';
32
+ import { RepresentativeStoreError, bindingFingerprint } from './representative-store.js';
33
+ import { createDeliveryStore } from './representative-delivery-store.js';
34
+ import { createRepresentativeOwner } from './representative-owner.js';
35
+
36
+ export const REPRESENTATIVE_TOOL_NAMES = [
37
+ 'borg_representative-status',
38
+ 'borg_representative-send',
39
+ 'borg_representative-read',
40
+ 'borg_representative-deliver',
41
+ 'borg_representative-ack',
42
+ ] as const;
43
+
44
+ export const REPRESENTATIVE_INSTRUCTIONS =
45
+ 'You are connected as the human representative of one Borg cube: an automated delegate that relays the ' +
46
+ 'human\'s requests, questions and decisions to ONE bound Coordinator drone and reads its replies. You are not the ' +
47
+ 'Coordinator and not the human: never plan or dispatch work for other drones — the Coordinator does that. ' +
48
+ 'Mark content user_authorized ONLY when the human explicitly said it; everything you originate is model_advice. ' +
49
+ 'A relayed decision authorizes only its own text, never broader approval. ' +
50
+ REPRESENTATIVE_DELIVERY_NOTE;
51
+
52
+ const TOOLS = [
53
+ {
54
+ name: 'borg_representative-status',
55
+ description:
56
+ 'Show which cube, representative drone and Coordinator this connection is bound to, whether the live cube still matches, ' +
57
+ 'any unresolved (ambiguous) sends, process ownership and the delivery limits. Read-only; never takes ownership.',
58
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
59
+ },
60
+ {
61
+ name: 'borg_representative-send',
62
+ description:
63
+ 'Relay ONE human request, question or decision to the bound Coordinator. The recipient is fixed; workers and broadcast ' +
64
+ 'are not addressable. Returns a request_id. If the outcome is "ambiguous" (the result names the cause), retry only ' +
65
+ 'with the SAME request_id and identical content (server-deduplicated); never re-send under a new id. A ' +
66
+ 'SEND_REJECTED error names the refusal and its recovery. Do not issue overlapping sends of the same content.',
67
+ inputSchema: {
68
+ type: 'object',
69
+ properties: {
70
+ kind: { type: 'string', enum: ['request', 'question', 'decision'] },
71
+ authorization: {
72
+ type: 'string',
73
+ enum: ['user_authorized', 'model_advice'],
74
+ description:
75
+ 'user_authorized: the human explicitly said/approved this exact content. model_advice: your own suggestion. ' +
76
+ 'A decision must be user_authorized.',
77
+ },
78
+ message: { type: 'string', description: `Plain text, at most ${REPRESENTATIVE_MESSAGE_LIMIT_BYTES} bytes.` },
79
+ request_id: {
80
+ type: 'string',
81
+ description: 'Omit for a new request. To retry, pass the request_id returned earlier with identical content.',
82
+ },
83
+ },
84
+ required: ['kind', 'authorization', 'message'],
85
+ additionalProperties: false,
86
+ },
87
+ },
88
+ {
89
+ name: 'borg_representative-read',
90
+ description:
91
+ 'Read the bound Coordinator\'s replies addressed to this representative that come after your delivered checkpoint, ' +
92
+ 'oldest first. Reading changes nothing: the same replies return on every call until you call ' +
93
+ 'borg_representative-deliver. Persist each reply durably, route it by in_reply_to or hold it for the human, then ' +
94
+ 'deliver through the last one you persisted. At most `limit` replies and `max_bytes` of serialized result; a reply ' +
95
+ 'larger than max_bytes is returned whole and alone with oversize:true, and the result never exceeds ' +
96
+ 'max(max_bytes, 16384) bytes (oversize citations reduced to ids, documents_reduced:true). has_more means more ' +
97
+ 'replies follow the window; an empty page never has has_more. ' +
98
+ 'Stop routing if binding_fingerprint differs from the value you persisted at binding time.',
99
+ inputSchema: {
100
+ type: 'object',
101
+ properties: {
102
+ include_broadcast: { type: 'boolean', description: 'Also return the Coordinator\'s cube-wide broadcasts (marked as such).' },
103
+ limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Hard cap on returned replies. Default 10.' },
104
+ max_bytes: {
105
+ type: 'integer', minimum: 4096, maximum: 60000,
106
+ description: 'Hard cap on the serialized result size in bytes. Default 32768.',
107
+ },
108
+ },
109
+ additionalProperties: false,
110
+ },
111
+ },
112
+ {
113
+ name: 'borg_representative-deliver',
114
+ description:
115
+ 'Record that every reply up to and including `through` is durably persisted by the host. Only this call moves the ' +
116
+ 'read window. `through` must be a reply borg_representative-read returned; the same or an older id is a no-op ' +
117
+ '(advanced:false). Call it only after durable persistence: a delivered reply is not returned again. It does not ' +
118
+ 'notify the Coordinator; that is borg_representative-ack.',
119
+ inputSchema: {
120
+ type: 'object',
121
+ properties: { through: { type: 'string', description: 'entry_id of the last reply you persisted.' } },
122
+ required: ['through'],
123
+ additionalProperties: false,
124
+ },
125
+ },
126
+ {
127
+ name: 'borg_representative-ack',
128
+ description:
129
+ 'Signal to the Coordinator that one of its direct replies (entry_id from borg_representative-read) was received. ' +
130
+ 'It is only that signal: it is not delivery, does not move the read window (that is borg_representative-deliver), ' +
131
+ 'and is not needed for reading.',
132
+ inputSchema: {
133
+ type: 'object',
134
+ properties: { entry_id: { type: 'string' } },
135
+ required: ['entry_id'],
136
+ additionalProperties: false,
137
+ },
138
+ },
139
+ ] as const;
140
+
141
+ function errorBody(error: unknown): { error: { code: string; message: string; details?: unknown } } {
142
+ if (error instanceof RepresentativeError || error instanceof RepresentativeStoreError) {
143
+ const details = error instanceof RepresentativeError ? error.details : undefined;
144
+ return { error: { code: error.code, message: error.message, ...(details ? { details } : {}) } };
145
+ }
146
+ const code = (error as { code?: unknown } | null)?.code;
147
+ return {
148
+ error: {
149
+ code: typeof code === 'string' ? code : 'BACKEND_ERROR',
150
+ message: error instanceof Error ? error.message : 'Unknown error',
151
+ },
152
+ };
153
+ }
154
+
155
+ const toolResult = (body: unknown, isError = false) => ({
156
+ content: [{ type: 'text' as const, text: serializeRepresentativeResult(body) }],
157
+ ...(isError ? { isError: true } : {}),
158
+ });
159
+
160
+ export interface ServeRepresentativeOptions {
161
+ /** Resolved on every call; a throw fails that call closed. */
162
+ context: () => Promise<RepresentativeContext>;
163
+ /**
164
+ * The binding generation this process started with. Every call except status
165
+ * refuses with BINDING_MISMATCH, before any lease, ledger, checkpoint, cursor
166
+ * or network activity, once the saved binding's fingerprint differs.
167
+ */
168
+ pinnedFingerprint?: string;
169
+ version: string;
170
+ stdin?: Readable;
171
+ stdout?: Writable;
172
+ /** Internal timing seam for heartbeat controls; production uses 20 seconds. */
173
+ heartbeatIntervalMs?: number;
174
+ }
175
+
176
+ export async function serveRepresentativeMcp(
177
+ options: ServeRepresentativeOptions,
178
+ ): Promise<{ close: () => Promise<void>; closed: Promise<void> }> {
179
+ const owner = createRepresentativeOwner(options.heartbeatIntervalMs);
180
+ const server = new Server(
181
+ { name: 'borg-human-representative', version: options.version },
182
+ { capabilities: { tools: {} }, instructions: REPRESENTATIVE_INSTRUCTIONS },
183
+ );
184
+
185
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS.map((tool) => ({ ...tool })) }));
186
+
187
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
188
+ const name = request.params.name;
189
+ const args = request.params.arguments ?? {};
190
+ try {
191
+ if (!(REPRESENTATIVE_TOOL_NAMES as readonly string[]).includes(name)) {
192
+ throw new RepresentativeError(ErrorCode.INVALID_INPUT, `Unknown tool ${JSON.stringify(name)}; this connection exposes only the representative tools.`);
193
+ }
194
+ const ctx = await options.context();
195
+ const pinned = options.pinnedFingerprint ? { pinned_binding_fingerprint: options.pinnedFingerprint } : {};
196
+ if (name === 'borg_representative-status') {
197
+ return toolResult({ ...await representativeStatus(ctx), ...pinned, ownership: await owner.snapshot(ctx.binding) });
198
+ }
199
+ if (options.pinnedFingerprint && bindingFingerprint(ctx.binding) !== options.pinnedFingerprint) {
200
+ throw new RepresentativeError(
201
+ 'BINDING_MISMATCH',
202
+ 'The operator rebound this connection (a new binding generation) while it was running. Restart the MCP server to use the new binding.',
203
+ );
204
+ }
205
+ // An untrustworthy delivery checkpoint stops every effect, not only read
206
+ // and deliver, so the refusal reaches the human. Read-only; status stays.
207
+ await createDeliveryStore(ctx.binding).load();
208
+ await owner.ensure(ctx.binding);
209
+ // Recheck at each network boundary, not just at tool dispatch: a process
210
+ // may have paused or lost its lease while awaiting live verification.
211
+ const backend = ctx.backend;
212
+ const guarded = { ...ctx, guard: () => owner.ensure(ctx.binding), backend: Object.fromEntries(['whoami', 'roster', 'append', 'readAfter', 'unreadCursor', 'readEntry', 'ack'].map((key) => [key, async (...args: unknown[]) => {
213
+ await owner.ensure(ctx.binding);
214
+ if (key === 'readAfter') args[2] = () => owner.ensure(ctx.binding);
215
+ const result = await (backend[key as keyof typeof backend] as (...args: unknown[]) => Promise<unknown>).apply(backend, args);
216
+ await owner.ensure(ctx.binding);
217
+ return result;
218
+ }])) as unknown as typeof backend };
219
+ switch (name) {
220
+ case 'borg_representative-send': {
221
+ const sent = await sendRepresentativeMessage(guarded, args);
222
+ return toolResult(sent, sent.outcome === 'ambiguous');
223
+ }
224
+ case 'borg_representative-read':
225
+ return toolResult(await readRepresentativeReplies(guarded, args));
226
+ case 'borg_representative-deliver':
227
+ return toolResult(await deliverRepresentativeReplies(guarded, args));
228
+ default:
229
+ return toolResult(await ackRepresentativeReply(guarded, args));
230
+ }
231
+ } catch (error) {
232
+ return toolResult(errorBody(error), true);
233
+ }
234
+ });
235
+
236
+ const transport = new StdioServerTransport(options.stdin, options.stdout);
237
+ let finish!: () => void;
238
+ const closed = new Promise<void>((resolve) => { finish = resolve; });
239
+ const shutdown = async () => {
240
+ process.removeListener('SIGTERM', signalClose);
241
+ process.removeListener('SIGINT', signalClose);
242
+ try { await owner.close(); } finally { finish(); }
243
+ };
244
+ const signalClose = () => { void server.close(); };
245
+ server.onclose = () => { void shutdown().catch(() => {}); };
246
+ process.once('SIGTERM', signalClose);
247
+ process.once('SIGINT', signalClose);
248
+ try { await server.connect(transport); } catch (error) { await shutdown(); throw error; }
249
+ return { close: async () => { await server.close(); await closed; }, closed };
250
+ }
@@ -0,0 +1,105 @@
1
+ /** Lifecycle adapter for the existing stream lease; no separate lock protocol. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { borgConfigRoot, borgHomeRoot } from './private-root.js';
5
+ import {
6
+ acquireStreamLease, readOwnershipSnapshot, STREAM_OWNER_STALE_MS,
7
+ type StreamLease, type StreamOwnerDeps, type StreamOwnershipSnapshot,
8
+ } from './stream-owner.js';
9
+ import { RepresentativeError } from './representative-core.js';
10
+ import type { RepresentativeBinding } from './representative-store.js';
11
+
12
+ export function representativeOwnerDeps(binding: RepresentativeBinding): StreamOwnerDeps {
13
+ const authority = createHash('sha256').update(JSON.stringify([binding.origin, binding.trustIdentity])).digest('hex');
14
+ return {
15
+ // Separate from stream-locks, which borg_stream-status inspects. One lease
16
+ // across all worktrees using this authority/cube/drone, never one per host.
17
+ locksDir: join(borgConfigRoot(), 'representative-host-locks', authority),
18
+ privateRoot: { root: borgConfigRoot(), boundary: borgHomeRoot() },
19
+ worktree: binding.worktree, droneLabel: binding.representativeLabel, cubeName: binding.cubeName,
20
+ };
21
+ }
22
+
23
+ export function representativeOwnership(binding: RepresentativeBinding): Promise<StreamOwnershipSnapshot> {
24
+ return privateStorage(() => readOwnershipSnapshot(binding.cubeId, binding.representativeDroneId, representativeOwnerDeps(binding)));
25
+ }
26
+
27
+ async function privateStorage<T>(operation: () => Promise<T>): Promise<T> {
28
+ try { return await operation(); }
29
+ catch (error) {
30
+ if (error instanceof RepresentativeError) throw error;
31
+ const message = error instanceof Error ? error.message : 'invalid private state';
32
+ // Only this exact directory-mode refusal permits manual permission recovery.
33
+ // Symlink, ownership and other failures must not suggest chmod through a path.
34
+ const looseDirectory = /^Borg credential store root (.+) has insecure permissions; expected 0700$/s.exec(message);
35
+ const detail = looseDirectory
36
+ ? `directory ${looseDirectory[1]} has insecure permissions; expected 0700. ` +
37
+ 'Check that the named path is a real directory you own and not a symlink, then set it to 0700 and retry. ' +
38
+ 'Restart a process that had already lost ownership.'
39
+ : message.replace(/^Borg credential store /, '');
40
+ throw new RepresentativeError('REPRESENTATIVE_OWNERSHIP_REQUIRED',
41
+ 'Representative lease storage refused: ' + detail);
42
+ }
43
+ }
44
+
45
+ export function createRepresentativeOwner(heartbeatIntervalMs = 20_000) {
46
+ let lease: StreamLease | null = null;
47
+ let selected: RepresentativeBinding | undefined;
48
+ let deps: StreamOwnerDeps;
49
+ let lost = false, closed = false;
50
+ let timer: ReturnType<typeof setInterval> | undefined;
51
+ let tail: Promise<unknown> = Promise.resolve();
52
+ const processNonce = randomUUID();
53
+ // Serialize lease mutations, including heartbeats, but NOT tool execution:
54
+ // overlapping sends still use the existing atomic request reservation.
55
+ const serial = <T>(op: () => Promise<T>): Promise<T> => {
56
+ const result = tail.then(op);
57
+ tail = result.catch(() => {});
58
+ return result;
59
+ };
60
+ const snapshot = (binding: RepresentativeBinding) => privateStorage(() => readOwnershipSnapshot(
61
+ binding.cubeId, binding.representativeDroneId,
62
+ { ...representativeOwnerDeps(binding), processNonce },
63
+ ));
64
+ const refuse = async (binding: RepresentativeBinding): Promise<never> => {
65
+ const owner = await snapshot(binding);
66
+ throw new RepresentativeError(
67
+ 'REPRESENTATIVE_OWNERSHIP_REQUIRED',
68
+ `This representative is owned by another MCP process (pid ${owner.pid ?? 'unknown'}, started ${owner.startedAt ?? 'unknown'}), ` +
69
+ 'or this process lost its lease. Use the owning host; after it exits or its lease expires, retry from the intended host. ' +
70
+ 'Restart a process that lost ownership before using it again. Status remains available.',
71
+ { owner },
72
+ );
73
+ };
74
+ const refresh = async () => {
75
+ try {
76
+ if (!lease || !await lease.refresh()) lost = true;
77
+ } catch { lost = true; }
78
+ if (lost && timer) { clearInterval(timer); timer = undefined; }
79
+ };
80
+ return {
81
+ snapshot,
82
+ ensure: (binding: RepresentativeBinding) => serial(async () => {
83
+ if (selected && (selected.origin !== binding.origin || selected.trustIdentity !== binding.trustIdentity ||
84
+ selected.cubeId !== binding.cubeId || selected.representativeDroneId !== binding.representativeDroneId)) lost = true;
85
+ if (closed || lost) return refuse(binding);
86
+ if (lease) {
87
+ await refresh();
88
+ if (lost) return refuse(binding);
89
+ return;
90
+ }
91
+ deps = { ...representativeOwnerDeps(binding), processNonce };
92
+ lease = await privateStorage(() => acquireStreamLease(binding.cubeId, binding.representativeDroneId, STREAM_OWNER_STALE_MS, deps));
93
+ if (!lease) return refuse(binding);
94
+ selected = binding;
95
+ timer = setInterval(() => { void serial(refresh); }, heartbeatIntervalMs);
96
+ timer.unref();
97
+ }),
98
+ close: () => serial(async () => {
99
+ closed = true;
100
+ if (timer) { clearInterval(timer); timer = undefined; }
101
+ await lease?.release();
102
+ lease = null;
103
+ }),
104
+ };
105
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Private on-disk state for the human representative connection.
3
+ *
4
+ * One 0600 file under the Borg config root holds, per representative worktree:
5
+ * - the BINDING: the one explicit cube + Coordinator drone this worktree's
6
+ * dedicated seat may talk to. Changing it requires an explicit operator rebind.
7
+ * - the REQUEST LEDGER: one record per sent request id, so a retry never becomes
8
+ * a second message and an ambiguous send survives a reconnect.
9
+ *
10
+ * The file never holds a bearer (the seat store owns credentials) and never
11
+ * holds message text (only a payload digest).
12
+ */
13
+
14
+ import { decodeUuid } from 'borgmcp-shared/protocol';
15
+ import { createHash } from 'node:crypto';
16
+ import { join } from 'node:path';
17
+ import { borgConfigRoot } from './private-root.js';
18
+ import { shellEscape } from './shell-escape.js';
19
+ import { readStoreFile, withStore } from './seat-store.js';
20
+
21
+ export function isRepresentativeUuid(value: unknown): value is string {
22
+ try { decodeUuid(value); return true; } catch { return false; }
23
+ }
24
+ const SETTLED_REQUEST_LIMIT = 200;
25
+
26
+ /**
27
+ * Host fence for one binding generation: hex SHA-256 of the canonical JSON array
28
+ * [origin, trustIdentity, cubeId, representativeDroneId, coordinatorDroneId,
29
+ * boundAt]. It changes on every rebind (boundAt) and trust change, and carries
30
+ * no path or credential.
31
+ */
32
+ export function bindingFingerprint(binding: RepresentativeBinding): string {
33
+ return createHash('sha256').update(JSON.stringify([
34
+ binding.origin, binding.trustIdentity, binding.cubeId,
35
+ binding.representativeDroneId, binding.coordinatorDroneId, binding.boundAt,
36
+ ])).digest('hex');
37
+ }
38
+
39
+ export interface RepresentativeBinding {
40
+ /** Canonical worktree holding the dedicated representative seat. */
41
+ worktree: string;
42
+ origin: string;
43
+ trustIdentity: string;
44
+ cubeId: string;
45
+ cubeName: string;
46
+ representativeDroneId: string;
47
+ representativeLabel: string;
48
+ representativeRoleName: string;
49
+ coordinatorDroneId: string;
50
+ coordinatorLabel: string;
51
+ coordinatorRoleName: string;
52
+ repositoryOrigin?: string;
53
+ boundAt: string;
54
+ }
55
+
56
+ export function representativeRecoveryCommand(binding: RepresentativeBinding): string {
57
+ return `cd ${shellEscape(binding.worktree)} && borg representative prepare --coordinator ${shellEscape(binding.coordinatorLabel)} --role ${shellEscape(binding.representativeRoleName)} --rebind`;
58
+ }
59
+
60
+ export type RepresentativeRequestState = 'pending' | 'ambiguous' | 'sent' | 'rejected';
61
+
62
+ export interface RepresentativeRequestRecord {
63
+ /** Stable request identity; also the protocol `post_id` idempotency key. */
64
+ requestId: string;
65
+ /** sha256 of kind, authorization, message, cube and Coordinator — never the text. */
66
+ payloadDigest: string;
67
+ kind: string;
68
+ authorization: string;
69
+ state: RepresentativeRequestState;
70
+ entryId?: string;
71
+ /** An attempt under this id may have reached the log; a later refusal must not clear that. */
72
+ maybeStored?: boolean;
73
+ createdAt: string;
74
+ updatedAt: string;
75
+ }
76
+
77
+ interface RepresentativeFile {
78
+ version: 1;
79
+ bindings: Record<string, RepresentativeBinding>;
80
+ requests: Record<string, RepresentativeRequestRecord[]>;
81
+ }
82
+
83
+ export class RepresentativeStoreError extends Error {
84
+ constructor(readonly code: 'BINDING_CONFLICT', message: string) {
85
+ super(message);
86
+ this.name = 'RepresentativeStoreError';
87
+ }
88
+ }
89
+
90
+ export interface RepresentativeStore {
91
+ getBinding(worktree: string): Promise<RepresentativeBinding | null>;
92
+ readRequests(worktree: string): Promise<RepresentativeRequestRecord[]>;
93
+ saveBinding(
94
+ binding: RepresentativeBinding,
95
+ options: { rebind: boolean },
96
+ ): Promise<'created' | 'unchanged' | 'rebound'>;
97
+ /** Read-compare-write over one worktree's ledger under the store lock. */
98
+ transactRequests<T>(
99
+ worktree: string,
100
+ op: (records: RepresentativeRequestRecord[]) => T,
101
+ ): Promise<T>;
102
+ }
103
+
104
+ const BINDING_STRING_FIELDS = [
105
+ 'worktree', 'origin', 'trustIdentity', 'cubeId', 'cubeName',
106
+ 'representativeDroneId', 'representativeLabel', 'representativeRoleName',
107
+ 'coordinatorDroneId', 'coordinatorLabel', 'coordinatorRoleName', 'boundAt',
108
+ ] as const;
109
+
110
+ function validBinding(value: unknown, key: string): value is RepresentativeBinding {
111
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
112
+ const binding = value as Record<string, unknown>;
113
+ return BINDING_STRING_FIELDS.every((field) => typeof binding[field] === 'string' && binding[field] !== '') &&
114
+ binding.worktree === key &&
115
+ isRepresentativeUuid(binding.cubeId as string) &&
116
+ isRepresentativeUuid(binding.representativeDroneId as string) &&
117
+ isRepresentativeUuid(binding.coordinatorDroneId as string) &&
118
+ binding.representativeDroneId !== binding.coordinatorDroneId &&
119
+ (binding.repositoryOrigin === undefined || typeof binding.repositoryOrigin === 'string');
120
+ }
121
+
122
+ function validRequest(value: unknown): value is RepresentativeRequestRecord {
123
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
124
+ const record = value as Record<string, unknown>;
125
+ return isRepresentativeUuid(String(record.requestId ?? '')) &&
126
+ typeof record.payloadDigest === 'string' &&
127
+ typeof record.kind === 'string' &&
128
+ typeof record.authorization === 'string' &&
129
+ ['pending', 'ambiguous', 'sent', 'rejected'].includes(record.state as string) &&
130
+ (record.entryId === undefined || typeof record.entryId === 'string') &&
131
+ (record.maybeStored === undefined || typeof record.maybeStored === 'boolean') &&
132
+ typeof record.createdAt === 'string' &&
133
+ typeof record.updatedAt === 'string';
134
+ }
135
+
136
+ function parseFile(raw: string): RepresentativeFile | null {
137
+ const parsed = JSON.parse(raw) as Partial<RepresentativeFile> | null;
138
+ if (
139
+ parsed === null || typeof parsed !== 'object' || parsed.version !== 1 ||
140
+ parsed.bindings === null || typeof parsed.bindings !== 'object' || Array.isArray(parsed.bindings) ||
141
+ parsed.requests === null || typeof parsed.requests !== 'object' || Array.isArray(parsed.requests)
142
+ ) return null;
143
+ for (const [key, binding] of Object.entries(parsed.bindings)) {
144
+ if (!validBinding(binding, key)) return null;
145
+ }
146
+ for (const records of Object.values(parsed.requests)) {
147
+ if (!Array.isArray(records) || !records.every(validRequest)) return null;
148
+ }
149
+ return parsed as RepresentativeFile;
150
+ }
151
+
152
+ const emptyFile = (): RepresentativeFile => ({ version: 1, bindings: {}, requests: {} });
153
+
154
+ function sameSelection(a: RepresentativeBinding, b: RepresentativeBinding): boolean {
155
+ return a.origin === b.origin &&
156
+ a.trustIdentity === b.trustIdentity &&
157
+ a.cubeId === b.cubeId &&
158
+ a.representativeDroneId === b.representativeDroneId &&
159
+ a.coordinatorDroneId === b.coordinatorDroneId;
160
+ }
161
+
162
+ /** Settled history is bounded; unresolved (pending/ambiguous) records are never dropped. */
163
+ function pruneSettled(records: RepresentativeRequestRecord[]): RepresentativeRequestRecord[] {
164
+ const settled = records.filter((record) => record.state === 'sent' || record.state === 'rejected');
165
+ if (settled.length <= SETTLED_REQUEST_LIMIT) return records;
166
+ const drop = new Set(settled.slice(0, settled.length - SETTLED_REQUEST_LIMIT).map((record) => record.requestId));
167
+ return records.filter((record) => !drop.has(record.requestId));
168
+ }
169
+
170
+ export function representativeStorePath(): string {
171
+ return join(borgConfigRoot(), 'representative.json');
172
+ }
173
+
174
+ export function createRepresentativeStore(storePath: string = representativeStorePath()): RepresentativeStore {
175
+ // Atomic writer renames make a single read a complete snapshot, without a
176
+ // store-lock write or pruning settled history during read-only status.
177
+ const read = async () => {
178
+ const raw = await readStoreFile(storePath);
179
+ if (raw === null) return emptyFile();
180
+ let data: RepresentativeFile | null;
181
+ try { data = parseFile(raw); } catch { data = null; }
182
+ if (!data) throw new Error('Borg representative store is malformed or unsupported; refusing to read it');
183
+ return data;
184
+ };
185
+ return {
186
+ getBinding: async (worktree) => (await read()).bindings[worktree] ?? null,
187
+ readRequests: async (worktree) => (await read()).requests[worktree] ?? [],
188
+
189
+ saveBinding: (binding, options) => withStore(storePath, emptyFile, parseFile, async (txn) => {
190
+ if (!validBinding(binding, binding.worktree)) {
191
+ throw new Error('Refusing to save an invalid representative binding');
192
+ }
193
+ const existing = txn.data.bindings[binding.worktree];
194
+ // An explicit rebind always starts a new generation (new boundAt, so a new
195
+ // binding_fingerprint), even for the same selection.
196
+ if (existing && sameSelection(existing, binding) && !options.rebind) return 'unchanged' as const;
197
+ if (existing && !options.rebind) {
198
+ throw new RepresentativeStoreError(
199
+ 'BINDING_CONFLICT',
200
+ `This worktree is already bound to Coordinator ${existing.coordinatorLabel} in cube ${existing.cubeName}. ` +
201
+ `To confirm the new selection, run \`${representativeRecoveryCommand(binding)}\`.`,
202
+ );
203
+ }
204
+ txn.data.bindings[binding.worktree] = binding;
205
+ // A different selection invalidates the old ledger: its post ids belong to
206
+ // another cube/Coordinator conversation.
207
+ if (existing && !sameSelection(existing, binding)) delete txn.data.requests[binding.worktree];
208
+ await txn.commit();
209
+ return existing ? 'rebound' as const : 'created' as const;
210
+ }),
211
+
212
+ transactRequests: (worktree, op) => withStore(storePath, emptyFile, parseFile, async (txn) => {
213
+ const records = txn.data.requests[worktree] ?? [];
214
+ const before = JSON.stringify(records);
215
+ const result = op(records);
216
+ const next = pruneSettled(records);
217
+ if (JSON.stringify(next) !== before) {
218
+ txn.data.requests[worktree] = next;
219
+ await txn.commit();
220
+ }
221
+ return result;
222
+ }),
223
+ };
224
+ }
package/src/seat-probe.ts CHANGED
@@ -68,7 +68,7 @@ const TRANSPORT_ERRNOS = new Set([
68
68
  'ABORT_ERR',
69
69
  ]);
70
70
 
71
- function isTransportFailure(err: unknown): boolean {
71
+ export function isTransportFailure(err: unknown): boolean {
72
72
  if (err instanceof BorgServerUnreachableError) return true;
73
73
  const e = err as { name?: string; code?: string; cause?: { code?: string } };
74
74
  if (e?.name === 'AbortError') return true;