clay-server 5.6.0 → 5.7.0-beta.1

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 (74) hide show
  1. package/lib/clay-product-control.js +2 -1
  2. package/lib/daemon.js +12 -0
  3. package/lib/mcp-agent-management.js +98 -0
  4. package/lib/mcp-agent-tools.js +4 -3
  5. package/lib/mcp-local-configuration.js +20 -0
  6. package/lib/mcp-management-service.js +96 -0
  7. package/lib/mcp-remote-connections.js +127 -35
  8. package/lib/mcp-settings-navigation.js +34 -0
  9. package/lib/mcp-xcode.js +43 -0
  10. package/lib/project-admin-overview.js +2 -2
  11. package/lib/project-mcp.js +28 -6
  12. package/lib/project-ownership-diagnostics.js +37 -0
  13. package/lib/project-ownership-recovery.js +59 -0
  14. package/lib/project-ownership.js +1 -34
  15. package/lib/public/app.js +3 -0
  16. package/lib/public/css/mcp-connections.css +15 -0
  17. package/lib/public/css/mcp-skills-workbench.css +6 -4
  18. package/lib/public/css/project-admin-overview.css +4 -0
  19. package/lib/public/css/project-settings-modal.css +8 -0
  20. package/lib/public/css/settings-shell.css +42 -0
  21. package/lib/public/index.html +4 -4
  22. package/lib/public/modules/clay-tool-presentation.js +7 -0
  23. package/lib/public/modules/extension-settings.js +1 -1
  24. package/lib/public/modules/mcp-connection-view.js +52 -24
  25. package/lib/public/modules/mcp-skills-workbench.js +10 -3
  26. package/lib/public/modules/mcp-ui.js +40 -11
  27. package/lib/public/modules/mcp-xcode-view.js +42 -0
  28. package/lib/public/modules/project-admin-overview.js +9 -0
  29. package/lib/public/modules/project-ownership-recovery.js +56 -0
  30. package/lib/public/modules/project-session-visibility-settings.js +1 -1
  31. package/lib/public/modules/project-settings-access.js +91 -0
  32. package/lib/public/modules/project-settings-environment.js +3 -2
  33. package/lib/public/modules/project-settings.js +39 -5
  34. package/lib/public/modules/settings-project-tree.js +74 -0
  35. package/lib/public/modules/settings-shell-view.js +3 -1
  36. package/lib/public/modules/settings-shell.js +3 -2
  37. package/lib/public/pane-assets/{app-QR6W64PK.js → app-KYK2HXZR.js} +1 -1
  38. package/lib/public/pane-assets/chunk-3CGVMON5.js +1 -0
  39. package/lib/public/pane-assets/{chunk-YDQZXMHJ.js → chunk-3WQWIQ53.js} +1 -1
  40. package/lib/public/pane-assets/{chunk-I5RM7KNO.js → chunk-42POZKMA.js} +1 -1
  41. package/lib/public/pane-assets/chunk-53PJD7FQ.js +1 -0
  42. package/lib/public/pane-assets/{chunk-HXD34AZT.js → chunk-5525OCE4.js} +1 -1
  43. package/lib/public/pane-assets/{chunk-K3AFWB4T.js → chunk-6WHHBK62.js} +100 -100
  44. package/lib/public/pane-assets/{chunk-H6RI6IG5.js → chunk-7DMFCL3J.js} +1 -1
  45. package/lib/public/pane-assets/chunk-7IDJFDUF.js +1 -0
  46. package/lib/public/pane-assets/chunk-C4BC5QKM.js +1 -0
  47. package/lib/public/pane-assets/{chunk-OHKQX2VV.js → chunk-G2OD6CYE.js} +1 -1
  48. package/lib/public/pane-assets/{chunk-TUZOISN6.js → chunk-H2Z5IANY.js} +1 -1
  49. package/lib/public/pane-assets/{chunk-4KCNVBBD.js → chunk-I74MAWWL.js} +1 -1
  50. package/lib/public/pane-assets/{chunk-UBGZO6GV.js → chunk-IPEGITRJ.js} +1 -1
  51. package/lib/public/pane-assets/{chunk-25X3V6RW.js → chunk-NTWCEBHU.js} +1 -1
  52. package/lib/public/pane-assets/{chunk-KLRVHJC5.js → chunk-NZYCUCTU.js} +1 -1
  53. package/lib/public/pane-assets/chunk-OX66WEZB.js +1 -0
  54. package/lib/public/pane-assets/{chunk-WI7YYJ5R.js → chunk-SDEVOBXA.js} +1 -1
  55. package/lib/public/pane-assets/chunk-TA6KA3QG.js +1 -0
  56. package/lib/public/pane-assets/chunk-TDKHZ2NU.js +1 -0
  57. package/lib/public/pane-assets/{chunk-H3BOT3SB.js → chunk-UEQM5YNB.js} +1 -1
  58. package/lib/public/pane-assets/{chunk-IIZZTDLB.js → chunk-WBLXJD4Q.js} +1 -1
  59. package/lib/public/pane-assets/{chunk-TKD25TLY.js → chunk-YZAEN74U.js} +1 -1
  60. package/lib/public/pane-assets/chunk-ZBCR4WTM.js +1 -0
  61. package/lib/public/pane-assets/manifest.json +416 -412
  62. package/lib/public/pane-assets/style-WRLOVB6B.css +1 -0
  63. package/lib/server-project-ownership.js +39 -0
  64. package/lib/server.js +5 -0
  65. package/package.json +1 -1
  66. package/lib/public/pane-assets/chunk-AKFJO7SA.js +0 -1
  67. package/lib/public/pane-assets/chunk-DX7R6GRL.js +0 -1
  68. package/lib/public/pane-assets/chunk-F33TBKP2.js +0 -1
  69. package/lib/public/pane-assets/chunk-PTZ2QTNA.js +0 -1
  70. package/lib/public/pane-assets/chunk-QWNMLSVA.js +0 -1
  71. package/lib/public/pane-assets/chunk-VG32EEIQ.js +0 -1
  72. package/lib/public/pane-assets/chunk-W2W4CPO7.js +0 -1
  73. package/lib/public/pane-assets/chunk-XX2GY7T5.js +0 -1
  74. package/lib/public/pane-assets/style-BCUGGAD3.css +0 -1
@@ -6,13 +6,17 @@ var StreamableHTTPClientTransport = require('@modelcontextprotocol/sdk/client/st
6
6
  var network = require('./mcp-network');
7
7
  var oauth = require('./mcp-oauth');
8
8
  var createLoginBrowser = require('./vendor-login-browser').createLoginBrowser;
9
+ var xcode = require('./mcp-xcode');
9
10
 
10
11
  function createRemoteConnections(ctx) {
11
12
  var accounts = new Map(), live = new Map(), flows = new Map(), queues = new Map();
12
13
  var remoteFetch = ctx.remoteFetch || network.createRemoteFetch();
13
14
  var closed = false;
15
+ var xcodeSupport = xcode.createXcodeSupport(ctx.xcodeOptions), xcodeChecks = new Map(), xcodeGenerations = new Map();
16
+ function xcodeIdentity(owner) { return ctx.ownerIdentity ? ctx.ownerIdentity(owner) : null; }
17
+ function xcodeState(owner) { records(owner); return xcodeChecks.get(owner) || null; }
14
18
  function sameRuntimeConfig(left, right) {
15
- return left && right && left.url === right.url && left.enabled === right.enabled && left.authMode === right.authMode && left.token === right.token && JSON.stringify(left.auth || null) === JSON.stringify(right.auth || null) && JSON.stringify([left.transport, left.command, left.args, left.env, left.cwd, left.headers, left.envHeaders, left.references, left.disabledTools, left.enabledTools, left.toolPatterns, left.toolPrefix]) === JSON.stringify([right.transport, right.command, right.args, right.env, right.cwd, right.headers, right.envHeaders, right.references, right.disabledTools, right.enabledTools, right.toolPatterns, right.toolPrefix]);
19
+ return left && right && left.integration === right.integration && left.url === right.url && left.enabled === right.enabled && left.authMode === right.authMode && left.token === right.token && JSON.stringify(left.auth || null) === JSON.stringify(right.auth || null) && JSON.stringify([left.transport, left.command, left.args, left.env, left.cwd, left.headers, left.envHeaders, left.references, left.disabledTools, left.enabledTools, left.toolPatterns, left.toolPrefix]) === JSON.stringify([right.transport, right.command, right.args, right.env, right.cwd, right.headers, right.envHeaders, right.references, right.disabledTools, right.enabledTools, right.toolPatterns, right.toolPrefix]);
16
20
  }
17
21
  function invalidate(owner, previous, current) {
18
22
  var byId = new Map(current.filter(function (row) { return row.source !== 'computer'; }).map(function (row) { return [row.id, row]; }));
@@ -47,12 +51,17 @@ function createRemoteConnections(ctx) {
47
51
  function check(owner, row) {
48
52
  if (closed || find(owner, row.id) !== row) throw new Error('Connection changed.');
49
53
  if (row.source === 'local' && ctx.ownerIdentity) ctx.ownerIdentity(owner);
54
+ if (xcode.isXcode(row)) {
55
+ xcode.validate(row); var identity = xcodeIdentity(owner); xcodeSupport.checkIdentity(identity);
56
+ var entry = live.get(key(owner, row.id));
57
+ if (entry && entry.identityKey !== xcodeSupport.identityKey(identity)) throw new Error('Xcode OS user identity changed. Reconnect from Local MCP → Xcode.');
58
+ }
50
59
  }
51
60
  function changed(owner) { if (!closed) ctx.changed(owner); }
52
61
  function view(owner) {
53
62
  return records(owner).filter(function (row) { return row.source !== 'computer'; }).map(function (row) {
54
63
  var entry = live.get(key(owner, row.id));
55
- return { id: row.id, name: row.id, label: row.label, source: row.source, transport: row.transport || 'http', url: row.url ? new URL(row.url).origin + new URL(row.url).pathname : null, provenance: row.provenance, references: require('./mcp-import-credentials').requiredNames(row),
64
+ return { id: row.id, name: row.id, label: row.label, source: row.source, integration: row.integration, transport: row.transport || 'http', url: row.url ? new URL(row.url).origin + new URL(row.url).pathname : null, provenance: row.provenance, references: require('./mcp-import-credentials').requiredNames(row),
56
65
  projectEnabled: !!row.enabled, extensionEnabled: true, tools: row.tools || [], toolCount: (row.tools || []).length,
57
66
  status: entry ? entry.status : (row.provenance || row.tools ? 'idle' : 'unavailable'), error: entry ? entry.error : '', authMode: row.authMode || 'auto' };
58
67
  });
@@ -62,62 +71,73 @@ function createRemoteConnections(ctx) {
62
71
  live.delete(key(owner, id));
63
72
  if (entry && entry.client) await entry.client.close().catch(function () {});
64
73
  }
65
- function provider(owner, row, flow) {
66
- return oauth.createOAuthProvider(row, function () { check(owner, row); persist(owner); }, flow, function () { check(owner, row); });
74
+ function provider(owner, row, flow, control) {
75
+ function authorize() { if (control) control.authorize(); check(owner, row); }
76
+ return oauth.createOAuthProvider(row, function () { authorize(); persist(owner); }, flow, authorize);
67
77
  }
68
- async function connect(owner, row, flow) {
69
- check(owner, row);
78
+ async function connect(owner, row, flow, control) {
79
+ function validateSetup() { if (control) control.authorize(); check(owner, row); }
80
+ function stopped() { disconnect(owner, row.id); }
81
+ validateSetup();
82
+ if (xcode.isXcode(row)) { xcode.validate(row); xcodeSupport.checkIdentity(xcodeIdentity(owner)); }
70
83
  await disconnect(owner, row.id);
71
- check(owner, row);
84
+ validateSetup();
72
85
  if (flow && flow.cancelled) throw new Error('Sign-in expired.');
73
86
  var client = new Client({ name: 'clay', version: '1.0.0' }, { capabilities: {} });
74
87
  if (row.source !== 'local' && ((row.references || []).length || Object.keys(row.envHeaders || {}).length)) throw new Error('Configure required credentials in Clay before connecting.');
75
- var options = { fetch: async function (input, init) { check(owner, row); var response = await remoteFetch.fetch(input, init); check(owner, row); return response; }, requestInit: { headers: row.headers || {} } };
88
+ var options = { fetch: async function (input, init) { validateSetup(); var response = await remoteFetch.fetch(input, init); validateSetup(); return response; }, requestInit: { headers: row.headers || {} } };
76
89
  if (row.authMode === 'token' && row.token) options.requestInit = { headers: Object.assign({}, row.headers || {}, { Authorization: 'Bearer ' + row.token }) };
77
- else if (flow || (row.auth && row.auth.tokens)) options.authProvider = provider(owner, row, flow);
78
- var transport = row.source === 'local' ? localTransport(row, ctx.ownerIdentity ? ctx.ownerIdentity(owner) : null) : (row.transport === 'sse' ? new SSEClientTransport(new URL(row.url), options) : new StreamableHTTPClientTransport(new URL(row.url), options));
79
- var entry = { client: client, transport: transport, status: 'connecting', error: '' };
90
+ else if (flow || (row.auth && row.auth.tokens)) options.authProvider = provider(owner, row, flow, flow ? control : null);
91
+ var transport = row.source === 'local' ? (ctx.localTransport || localTransport)(row, ctx.ownerIdentity ? ctx.ownerIdentity(owner) : null) : (row.transport === 'sse' ? new SSEClientTransport(new URL(row.url), options) : new StreamableHTTPClientTransport(new URL(row.url), options));
92
+ var entry = { client: client, transport: transport, status: 'connecting', error: '', identityKey: xcode.isXcode(row) ? xcodeSupport.identityKey(xcodeIdentity(owner)) : null };
93
+ if (xcode.isXcode(row)) client.onclose = function () {
94
+ if (live.get(key(owner, row.id)) !== entry || entry.status !== 'ready') return;
95
+ entry.status = 'unavailable'; entry.error = 'Xcode disconnected. Open your project in Xcode and reconnect from Local MCP → Xcode.'; changed(owner);
96
+ };
80
97
  live.set(key(owner, row.id), entry); changed(owner);
98
+ if (control && control.signal) control.signal.addEventListener('abort', stopped, { once: true });
81
99
  try {
82
100
  await client.connect(transport, { timeout: 30000 });
83
- check(owner, row);
101
+ validateSetup();
84
102
  var tools = [], cursor, seen = new Set();
85
103
  do {
86
104
  var page = await client.listTools(cursor ? { cursor: cursor } : {}, { timeout: 30000 });
87
- check(owner, row);
105
+ validateSetup();
88
106
  tools = tools.concat(page.tools);
89
107
  if (tools.length > 1000 || seen.size >= 100 || (page.nextCursor && seen.has(page.nextCursor))) throw new Error('Tool catalog exceeds the supported limit.');
90
108
  cursor = page.nextCursor; seen.add(cursor);
91
109
  } while (cursor);
92
110
  if (JSON.stringify(tools).length > 2 * 1024 * 1024) throw new Error('Tool catalog exceeds the supported limit.');
93
- check(owner, row);
111
+ validateSetup();
94
112
  if (live.get(key(owner, row.id)) !== entry || (flow && flow.cancelled)) throw new Error('Connection changed.');
95
113
  tools = tools.filter(function (tool) {
96
114
  return require('./mcp-tool-policy').permits(row, tool.name);
97
115
  });
116
+ if (xcode.isXcode(row) && !tools.length) throw new Error('Xcode did not expose any tools.');
98
117
  require('./mcp-proxy').validateDefinitions(tools);
99
118
  row.tools = tools; entry.status = 'ready'; persist(owner);
100
119
  return entry;
101
120
  } catch (error) {
102
121
  var requiresAuth = error.code === 401 || error.code === 403 || error.name === 'UnauthorizedError' || (flow && flow.authorizationUrl);
103
122
  entry.status = requiresAuth ? 'auth_required' : 'unavailable';
104
- entry.error = requiresAuth ? 'Sign in or provide an access token to connect.' : row.source === 'local' ? 'Could not start the command. Check its dependency and working directory.' : 'Could not connect. Check the address and try again.';
123
+ entry.error = xcode.isXcode(row) ? 'Could not connect to Xcode. Open your project, turn on “Allow external agents to use Xcode tools” in Xcode Settings → Intelligence, and approve Clay’s connection in Xcode if asked. Then try again.' : requiresAuth ? 'Sign in or provide an access token to connect.' : row.source === 'local' ? 'Could not start the command. Check its dependency and working directory.' : 'Could not connect. Check the address and try again.';
105
124
  if (!flow) await client.close().catch(function () {});
106
125
  return entry;
107
- } finally { changed(owner); }
126
+ } finally { if (control && control.signal) control.signal.removeEventListener('abort', stopped); control = null; changed(owner); }
108
127
  }
109
128
  function cancelLogin(owner, id) {
110
129
  var idKey = key(owner, id), flow = flows.get(idKey);
111
130
  if (!flow) return;
112
131
  flow.cancelled = true; flows.delete(idKey); clearTimeout(flow.timer);
132
+ if (flow.controlCleanup) flow.controlCleanup();
113
133
  if (flow.browser) { flow.browser.close(); ctx.sendOwner(owner, { type: 'mcp_login_closed', browserId: flow.browser.id }); }
114
134
  flow.close();
115
135
  }
116
- async function signIn(owner, row, ws) {
136
+ async function signIn(owner, row, ws, control) {
117
137
  cancelLogin(owner, row.id);
118
138
  var identity = ctx.identity(ws);
119
139
  var flow = await oauth.createCallback(async function (code, issuer) {
120
- check(owner, row);
140
+ if (control) control.authorize(); check(owner, row);
121
141
  if (flows.get(key(owner, row.id)) !== flow) throw new Error('Sign-in expired.');
122
142
  var metadata = row.auth && row.auth.discovery;
123
143
  var expected = metadata && metadata.authorizationServerMetadata && metadata.authorizationServerMetadata.issuer;
@@ -125,21 +145,26 @@ function createRemoteConnections(ctx) {
125
145
  var entry = live.get(key(owner, row.id));
126
146
  if (!entry || !entry.transport) throw new Error('Sign in again.');
127
147
  await entry.transport.finishAuth(code);
128
- check(owner, row);
148
+ if (control) control.authorize(); check(owner, row);
129
149
  if (flows.get(key(owner, row.id)) !== flow) throw new Error('Sign-in expired.');
130
- var ready = await connect(owner, row);
150
+ var ready = await connect(owner, row, null, control);
131
151
  if (ready.status !== 'ready') throw new Error('Connection failed after sign-in.');
132
152
  setTimeout(function () { if (flows.get(key(owner, row.id)) === flow) { cancelLogin(owner, row.id); changed(owner); } }, 500);
133
153
  });
134
- try { check(owner, row); } catch (error) { flow.close(); throw error; }
154
+ try { if (control) control.authorize(); check(owner, row); } catch (error) { flow.close(); throw error; }
155
+ if (control && control.signal) {
156
+ var abortLogin = function () { cancelLogin(owner, row.id); };
157
+ control.signal.addEventListener('abort', abortLogin, { once: true });
158
+ flow.controlCleanup = function () { control.signal.removeEventListener('abort', abortLogin); };
159
+ }
135
160
  flows.set(key(owner, row.id), flow);
136
161
  flow.timer = setTimeout(function () { cancelLogin(owner, row.id); }, 10 * 60 * 1000); flow.timer.unref();
137
162
  row.authMode = 'auto'; delete row.token;
138
163
  // A fresh loopback redirect requires a matching client registration.
139
164
  row.auth = { redirectUrl: flow.redirectUrl }; persist(owner);
140
- var entry = await connect(owner, row, flow);
165
+ var entry = await connect(owner, row, flow, control);
141
166
  if (!flow.authorizationUrl) { cancelLogin(owner, row.id); if (entry.status !== 'ready') throw new Error('This server could not start browser sign-in. Use an access token if supported.'); return; }
142
- check(owner, row);
167
+ if (control) control.authorize(); check(owner, row);
143
168
  if (flow.cancelled) throw new Error('Sign-in expired.');
144
169
  try { flow.browser = (ctx.createLoginBrowser || createLoginBrowser)({ ws: ws, vendor: 'mcp', initialUrl: flow.authorizationUrl,
145
170
  osUserInfo: identity, restrictedNetwork: true,
@@ -168,31 +193,97 @@ function createRemoteConnections(ctx) {
168
193
  function importConnection(owner, select, authorize) {
169
194
  return serial(owner, function () { var row = commitImport(owner, select, authorize); changed(owner); return row.id; });
170
195
  }
171
- function command(owner, msg, ws) {
196
+ async function inspectXcode(owner, authorize) {
197
+ records(owner); authorize();
198
+ var inspected = await xcodeSupport.inspect(xcodeIdentity(owner), authorize);
199
+ authorize(); xcodeChecks.set(owner, inspected); changed(owner); return inspected;
200
+ }
201
+ function managementVersion(owner) {
202
+ var rows = records(owner);
203
+ return crypto.createHash('sha256').update(JSON.stringify([accounts.get(owner).revision, rows])).digest('hex');
204
+ }
205
+ function command(owner, msg, ws, control) {
206
+ var expected = control && control.version;
207
+ function admitted() {
208
+ if (!control) return;
209
+ control.authorize();
210
+ if (expected !== managementVersion(owner)) throw new Error('MCP connections changed. Inspect the change again.');
211
+ }
212
+ try { admitted(); } catch (error) { return Promise.reject(error); }
213
+ var requestedXcodeGeneration = xcodeGenerations.get(owner) || 0;
214
+ if (msg.action === 'xcode_disconnect') {
215
+ try {
216
+ records(owner);
217
+ if (!ctx.canAccess(ws, owner)) throw new Error('Xcode access changed.');
218
+ if (control && control.started) control.started();
219
+ xcodeGenerations.set(owner, (xcodeGenerations.get(owner) || 0) + 1);
220
+ var stopped = records(owner).find(xcode.isXcode);
221
+ if (stopped) { stopped.enabled = false; persist(owner); disconnect(owner, stopped.id); }
222
+ changed(owner); return Promise.resolve(stopped ? stopped.id : null);
223
+ } catch (error) { return Promise.reject(error); }
224
+ }
172
225
  // Revocation takes effect before any queued network work completes.
173
226
  if (msg.action === 'remove' || (msg.action === 'enable' && msg.enabled !== true)) {
174
227
  try {
175
228
  var revoked = find(owner, msg.id);
176
229
  if (revoked.source === 'computer') throw new Error('Not a remote connection.');
230
+ if (xcode.isXcode(revoked)) xcodeGenerations.set(owner, (xcodeGenerations.get(owner) || 0) + 1);
231
+ if (control && control.started) control.started();
177
232
  revoked.enabled = false; cancelLogin(owner, revoked.id); persist(owner);
178
233
  disconnect(owner, revoked.id); changed(owner);
234
+ if (control) expected = managementVersion(owner);
179
235
  } catch (error) { return Promise.reject(error); }
180
236
  }
181
237
  return serial(owner, async function () {
238
+ admitted();
239
+ if (control && control.started) control.started();
182
240
  var row;
183
- if (msg.action === 'import') {
241
+ if (msg.action === 'xcode_check' || msg.action === 'xcode_connect') {
242
+ var identity = xcodeIdentity(owner), identityKey = xcodeSupport.identityKey(identity);
243
+ var generation = requestedXcodeGeneration;
244
+ function authorizeXcode() {
245
+ records(owner);
246
+ if (control) control.authorize();
247
+ if (closed || !ctx.canAccess(ws, owner) || (xcodeGenerations.get(owner) || 0) !== generation || xcodeSupport.identityKey(xcodeIdentity(owner)) !== identityKey) throw new Error('Xcode access changed or connection was cancelled. Check the connection again.');
248
+ }
249
+ authorizeXcode();
250
+ var inspected = await inspectXcode(owner, authorizeXcode);
251
+ authorizeXcode();
252
+ if (msg.action === 'xcode_check') return null;
253
+ if (!inspected.ready) throw new Error(inspected.message);
254
+ row = records(owner).find(xcode.isXcode);
255
+ if (!row) {
256
+ if (records(owner).filter(function (item) { return item.source !== 'computer'; }).length >= 30) throw new Error('Remove an unused MCP connection before adding Xcode.');
257
+ row = Object.assign(xcode.configuration(), { id: 'remote-' + crypto.randomBytes(8).toString('hex') }); records(owner).push(row);
258
+ }
259
+ xcode.validate(row); row.enabled = false; persist(owner);
260
+ var connected = await connect(owner, row, null, control);
261
+ authorizeXcode(); check(owner, row);
262
+ if (connected.status !== 'ready') throw new Error(connected.error);
263
+ row.enabled = true; persist(owner);
264
+ } else if (msg.action === 'import') {
184
265
  row = commitImport(owner, function () { return ctx.selectImport(owner, ws, msg); }, function () { if (!ctx.canAccess(ws, owner)) throw new Error('MCP account is unavailable.'); });
266
+ } else if (msg.action === 'add_local') {
267
+ records(owner);
268
+ if (!ctx.canAccess(ws, owner) || typeof ctx.ownerIdentity !== 'function') throw new Error('Local MCP requires your authorized OS account.');
269
+ var localConfig = require('./mcp-local-configuration').configuration(msg, ctx.ownerIdentity(owner));
270
+ if (records(owner).filter(function (item) { return item.source !== 'computer'; }).length >= 30) throw new Error('Remove an unused MCP connection before adding another.');
271
+ if (records(owner).some(function (item) { return item.source === 'local' && item.command === localConfig.command && JSON.stringify(item.args || []) === JSON.stringify(localConfig.args) && item.cwd === localConfig.cwd; })) throw new Error('This local MCP server is already saved. Open it from your connections.');
272
+ if (!ctx.canAccess(ws, owner)) throw new Error('MCP account is unavailable.');
273
+ row = Object.assign({}, localConfig, { id: 'remote-' + crypto.randomBytes(8).toString('hex') });
274
+ records(owner).push(row); persist(owner);
185
275
  } else if (msg.action === 'add') {
186
276
  var url = network.remoteUrl(msg.url).href;
187
277
  if (records(owner).filter(function (item) { return item.source !== 'computer'; }).length >= 30) throw new Error('You can add up to 30 remote connections per project.');
188
278
  if (records(owner).some(function (item) { return item.url === url; })) throw new Error('This server is already connected. Open it from your connections.');
189
279
  row = { id: 'remote-' + crypto.randomBytes(8).toString('hex'), source: 'url', url: url, label: new URL(url).hostname, enabled: false };
190
280
  records(owner).push(row); persist(owner);
191
- await connect(owner, row);
281
+ await connect(owner, row, null, control);
192
282
  } else {
193
283
  row = find(owner, msg.id);
194
- if (row.source === 'computer') throw new Error('Not a remote connection.');
195
- if (msg.action === 'enable') { row.enabled = msg.enabled === true; persist(owner); if (row.enabled && row.provenance) { try { await connect(owner, row); } catch (error) { row.enabled = false; persist(owner); throw error; } } }
284
+ if (row.source === 'computer') throw new Error('Not a managed connection.');
285
+ if (row.source === 'local' && !row.provenance && !xcode.isXcode(row) && !ctx.canAccess(ws, owner)) throw new Error('Local MCP access changed.');
286
+ if (msg.action === 'enable') { if (xcode.isXcode(row) && msg.enabled === true) throw new Error('Connect Xcode from Local MCP → Xcode.'); row.enabled = msg.enabled === true; persist(owner); if (row.enabled && (row.provenance || row.source === 'local')) { try { await connect(owner, row, null, control); } catch (error) { row.enabled = false; persist(owner); throw error; } } }
196
287
  else if (msg.action === 'rename') {
197
288
  if (typeof msg.label !== 'string' || !msg.label.trim() || msg.label.length > 100) throw new Error('Use a name between 1 and 100 characters.');
198
289
  row.label = msg.label.trim(); persist(owner);
@@ -200,17 +291,18 @@ function createRemoteConnections(ctx) {
200
291
  cancelLogin(owner, row.id); await disconnect(owner, row.id);
201
292
  var account = accounts.get(owner);
202
293
  accounts.set(owner, { records: records(owner).filter(function (item) { return item !== row; }), revision: account && account.revision }); persist(owner);
203
- } else if (msg.action === 'test') { cancelLogin(owner, row.id); await connect(owner, row); }
294
+ } else if (msg.action === 'test') { cancelLogin(owner, row.id); await connect(owner, row, null, control); }
204
295
  else if (msg.action === 'credentials') {
205
296
  if (!msg.values || typeof msg.values !== 'object' || Array.isArray(msg.values)) throw new Error('Enter required credential values.');
206
297
  var next = require('./mcp-import-credentials').applyCredentials(row, msg.values);
207
298
  cancelLogin(owner, row.id); Object.assign(row, next); persist(owner); await disconnect(owner, row.id);
208
299
  } else if (msg.action === 'token') {
209
300
  if (typeof msg.token !== 'string' || !msg.token.trim() || msg.token.length > 8192 || /[\r\n]/.test(msg.token)) throw new Error('Enter a valid access token.');
210
- cancelLogin(owner, row.id); row.token = msg.token.trim(); row.authMode = 'token'; delete row.auth; persist(owner); await connect(owner, row);
211
- } else if (msg.action === 'signin') { if (row.source === 'local') throw new Error('This server uses process environment credentials.'); await signIn(owner, row, ws); }
301
+ cancelLogin(owner, row.id); row.token = msg.token.trim(); row.authMode = 'token'; delete row.auth; persist(owner); await connect(owner, row, null, control);
302
+ } else if (msg.action === 'signin') { if (row.source === 'local') throw new Error('This server uses process environment credentials.'); await signIn(owner, row, ws, control); }
212
303
  else throw new Error('Unsupported connection action.');
213
304
  }
305
+ if (control) control.authorize();
214
306
  changed(owner);
215
307
  return row.id;
216
308
  });
@@ -230,11 +322,11 @@ function createRemoteConnections(ctx) {
230
322
  var entry = live.get(key(owner, id));
231
323
  if (!entry || entry.status !== 'ready') entry = await connect(owner, row);
232
324
  authorize(); check(owner, row);
233
- if (!row.enabled || entry.status !== 'ready') throw new Error('MCP connection is not ready. Open MCP Servers to reconnect.');
325
+ if (!row.enabled || entry.status !== 'ready') throw new Error('MCP connection is not ready. Open MCP / Skills to reconnect.');
234
326
  if (!(row.tools || []).some(function (tool) { return tool.name === name; })) throw new Error('Tool is unavailable.');
235
327
  // Never replay a tools/call after an ambiguous transport failure.
236
328
  var result;
237
- try { result = await entry.client.callTool({ name: name, arguments: args || {} }, undefined, { timeout: 60000 }); }
329
+ try { result = await entry.client.callTool({ name: name, arguments: args || {} }, undefined, { timeout: xcode.isXcode(row) ? 300000 : 60000 }); }
238
330
  catch (error) {
239
331
  authorize(); check(owner, row);
240
332
  if (live.get(key(owner, id)) === entry) {
@@ -242,7 +334,7 @@ function createRemoteConnections(ctx) {
242
334
  entry.error = entry.status === 'auth_required' ? 'Sign in again to reconnect.' : 'The tool call could not complete. Check the service before retrying.';
243
335
  changed(owner);
244
336
  }
245
- throw new Error('MCP tool call failed. Open MCP Servers to check the connection.');
337
+ throw new Error('MCP tool call failed. Open MCP / Skills to check the connection.');
246
338
  }
247
339
  authorize(); check(owner, row);
248
340
  if (!row.enabled || live.get(key(owner, id)) !== entry) throw new Error('Connection was disabled or changed.');
@@ -263,7 +355,7 @@ function createRemoteConnections(ctx) {
263
355
  closed = true; live.forEach(function (entry) { entry.client.close().catch(function () {}); }); live.clear();
264
356
  remoteFetch.close();
265
357
  }
266
- return { view: view, command: command, importConnection: importConnection, call: call, handleBrowser: handleBrowser, destroy: destroy,
358
+ return { view: view, managementVersion: managementVersion, inspectXcode: inspectXcode, command: command, importConnection: importConnection, call: call, handleBrowser: handleBrowser, destroy: destroy, xcodeState: xcodeState,
267
359
  computerEnabled: computerEnabled, toggleComputer: toggleComputer };
268
360
  }
269
361
  module.exports = { createRemoteConnections: createRemoteConnections };
@@ -0,0 +1,34 @@
1
+ var crypto = require('crypto');
2
+ function createSettingsNavigation(ctx) {
3
+ var pending = new Map(), closed = false;
4
+ function open(owner, ws, screen, id, session, authorize, signal) {
5
+ authorize();
6
+ if (closed || pending.size >= 100) throw new Error('MCP settings navigation is unavailable.');
7
+ return new Promise(function (resolve, reject) {
8
+ var requestId = 'mcp-settings-' + crypto.randomUUID(), timer;
9
+ function finish(error, value) {
10
+ if (!pending.has(requestId)) return;
11
+ pending.delete(requestId); clearTimeout(timer); signal.removeEventListener('abort', stopped);
12
+ if (error) reject(error); else resolve(value);
13
+ }
14
+ function stopped() { finish(new Error('MCP settings request stopped. It may already have reached the interface; inspect before retrying.')); }
15
+ pending.set(requestId, { ws: ws, owner: owner, session: session, authorize: authorize, finish: finish });
16
+ timer = setTimeout(function () { finish(null, { status: 'delivered', acknowledged: false, message: 'Request sent to the owner interface; client acceptance and visible rendering are unconfirmed. Open MCP / Skills in the source project to continue.' }); }, 5000);
17
+ signal.addEventListener('abort', stopped, { once: true });
18
+ try {
19
+ authorize(); if (signal.aborted) return stopped();
20
+ ctx.sendTo(ws, { type: 'mcp_settings_request', requestId: requestId, slug: ctx.slug, sessionId: session.localId, screen: screen, connectionId: id || null });
21
+ } catch (error) { finish(error); }
22
+ });
23
+ }
24
+ function handle(ws, msg) {
25
+ if (msg.type !== 'mcp_settings_result') return false;
26
+ var entry = pending.get(msg.requestId);
27
+ if (!entry || entry.ws !== ws || msg.slug !== ctx.slug || msg.sessionId !== entry.session.localId) return true;
28
+ try { entry.authorize(); entry.finish(null, { status: msg.accepted === true ? 'client_accepted' : 'client_refused', acknowledged: true, rendered: 'unconfirmed', message: msg.accepted === true ? 'Client accepted the settings request. Secret entry and saving remain human actions.' : 'The interface context changed or the connection is not loaded. Open MCP / Skills in the source conversation.' }); }
29
+ catch (error) { entry.finish(error); }
30
+ return true;
31
+ }
32
+ return { open: open, handle: handle, destroy: function () { closed = true; pending.forEach(function (entry) { entry.finish(new Error('MCP settings navigation closed.')); }); pending.clear(); } };
33
+ }
34
+ module.exports = { createSettingsNavigation: createSettingsNavigation };
@@ -0,0 +1,43 @@
1
+ var childProcess = require('child_process');
2
+ var os = require('os');
3
+
4
+ var COMMAND = '/usr/bin/xcrun';
5
+ function isXcode(row) { return row && row.integration === 'xcode'; }
6
+ function validate(row) {
7
+ if (row.source !== 'local' || row.transport !== 'stdio' || row.command !== COMMAND || JSON.stringify(row.args) !== '["mcpbridge"]' || Object.keys(row.env || {}).length || row.cwd || row.url || (row.references || []).length) throw new Error('Xcode connection configuration changed. Remove it and connect again from the Xcode tab.');
8
+ }
9
+ function configuration() {
10
+ return { integration: 'xcode', source: 'local', transport: 'stdio', command: COMMAND, args: ['mcpbridge'], env: {}, label: 'Xcode', enabled: false };
11
+ }
12
+ function createXcodeSupport(options) {
13
+ options = options || {};
14
+ var platform = options.platform || process.platform;
15
+ var uid = options.uid || process.getuid;
16
+ var execFile = options.execFile || childProcess.execFile;
17
+ function identityKey(identity) { return JSON.stringify(identity ? [identity.uid, identity.gid, identity.home, identity.user] : null); }
18
+ function checkIdentity(identity) {
19
+ if (platform !== 'darwin') throw new Error('Xcode requires Clay Studio to run on the same Mac as Xcode.');
20
+ if (identity && (!uid || identity.uid !== uid())) throw new Error('Run Clay Studio as the macOS user who runs Xcode. Other OS users are not supported.');
21
+ }
22
+ function run(command, args, identity) {
23
+ return new Promise(function (resolve) {
24
+ execFile(command, args, { timeout: 8000, maxBuffer: 16384, env: { HOME: identity ? identity.home : os.homedir(), PATH: '/usr/bin:/bin:/usr/sbin:/sbin' } }, function (error, stdout, stderr) { resolve({ error: error, output: String(stdout || '') + String(stderr || '') }); });
25
+ });
26
+ }
27
+ async function inspect(identity, authorize) {
28
+ authorize();
29
+ try { checkIdentity(identity); } catch (error) { return { supported: false, ready: false, message: error.message }; }
30
+ var selected = await run(COMMAND, ['--find', 'mcpbridge'], identity);
31
+ authorize();
32
+ if (selected.error) {
33
+ var message = /licen[cs]e/i.test(selected.output) ? 'Open Xcode and accept its license on this Mac, then check again.' : /command line tools|active developer/i.test(selected.output) ? 'Select a full Xcode installation in Xcode Settings → Locations → Command Line Tools, then check again.' : 'Xcode MCP bridge was not found. Install or update Xcode with MCP support and finish its first-launch setup.';
34
+ return { supported: true, ready: false, message: message };
35
+ }
36
+ var running = await run('/usr/bin/pgrep', ['-u', String(uid()), '-x', 'Xcode'], identity);
37
+ authorize();
38
+ if (running.error) return { supported: true, ready: false, message: 'Open Xcode and your project on the Mac running Clay Studio, then check again.' };
39
+ return { supported: true, ready: true, message: 'Xcode is running and its MCP bridge is available. Open your project and allow external agents before connecting.' };
40
+ }
41
+ return { inspect: inspect, checkIdentity: checkIdentity, identityKey: identityKey };
42
+ }
43
+ module.exports = { createXcodeSupport: createXcodeSupport, configuration: configuration, isXcode: isXcode, validate: validate };
@@ -35,10 +35,10 @@ function escape(value) {
35
35
 
36
36
  function page(metadata, projects) {
37
37
  var privacyText = metadata.ownershipRecovery
38
- ? "Content remains restricted because no verified owner is available. Ask the server operator to verify the account’s OS UID and real home/project mapping, then run the documented ownership repair."
38
+ ? "Content remains restricted because no verified owner is available. Ask the server operator to verify the account’s OS UID and real home/project mapping, then use the Access recovery check."
39
39
  : "Conversations, files and terminals are private. Ask the owner to share project access.";
40
40
  var accessText = metadata.ownershipRecovery
41
- ? "Ownership needs recovery. The server operator must independently verify or repair the authoritative account-to-OS mapping before ownership repair can succeed. Ambiguous records stay restricted; administrator status cannot claim this project. See the Project ownership and administrator access guide."
41
+ ? "Ownership needs recovery. The server operator must independently verify or repair the authoritative account-to-OS mapping before ownership repair can succeed. Use the recovery checks below; ambiguous records stay restricted."
42
42
  : "Only the project owner can change ownership, visibility and sharing. Administrator status does not grant access to private content.";
43
43
  var navigation = projects.filter(function (project) { return !project.isMate; }).map(function (project) {
44
44
  return { slug: project.slug, title: project.title || project.project || project.slug, icon: typeof project.icon === 'string' ? project.icon : null,
@@ -33,15 +33,36 @@ function attachMcp(ctx) {
33
33
  authorizeOwner(owner);
34
34
  }, snapshot: function (owner) { return storage.snapshot(owner); } });
35
35
  var remote = createRemoteConnections({
36
- remoteFetch: ctx.remoteFetch, createLoginBrowser: ctx.createLoginBrowser,
36
+ remoteFetch: ctx.remoteFetch, createLoginBrowser: ctx.createLoginBrowser, xcodeOptions: ctx.xcodeOptions, localTransport: ctx.localTransport,
37
37
  storage: storage, authorize: authorizeOwner,
38
38
  changed: function (owner) { announce(owner); }, sendOwner: sendOwner, sendTo: function (ws, msg) { ctx.sendTo(ws, Object.assign({ slug: ctx.slug }, msg)); },
39
39
  ownerIdentity: ctx.ownerIdentity, selectImport: discovery.selected,
40
40
  identity: ctx.identity,
41
- canAccess: function (ws, owner) { try { return ownerFor(ws) === owner; } catch (error) { return false; } },
41
+ canAccess: function (ws, owner) { try { return (ctx.clients.has(ws) || agentTools && agentTools.canViewOwner(ws, owner)) && ws.readyState === 1 && ownerFor(ws) === owner; } catch (error) { return false; } },
42
+ });
43
+ var settingsNavigation = require('./mcp-settings-navigation').createSettingsNavigation({ slug: ctx.slug, sendTo: ctx.sendTo });
44
+ var deviceIds = new WeakMap();
45
+ function clientVersion(owner) {
46
+ var device = deviceFor(owner);
47
+ if (!device) return null;
48
+ if (!deviceIds.has(device)) deviceIds.set(device, crypto.randomUUID());
49
+ return [deviceIds.get(device), device.hostConnected, device.servers];
50
+ }
51
+ function toggleClient(owner, name, value, authorize) {
52
+ if (authorize) authorize();
53
+ var device = deviceFor(owner);
54
+ if (!device || !device.servers.some(function (server) { return server.name === name; })) throw new Error('Client MCP device or server is unavailable.');
55
+ remote.toggleComputer(owner, name, value);
56
+ }
57
+ var management = require('./mcp-management-service').createManagementService({ remote: remote,
58
+ state: function (owner) { var state = buildState(owner); state.servers = state.servers.map(function (row) { return row.source === 'computer' ? Object.assign({}, row, { id: 'client:' + row.id }) : row; }); return state; },
59
+ clientVersion: clientVersion, identity: ctx.ownerIdentity,
60
+ identityKey: function (owner) { try { return JSON.stringify(ctx.ownerIdentity(owner)); } catch (error) { return 'unavailable:' + error.message; } },
61
+ canRespond: function (ws, session, owner) { return agentTools.canRespond(ws, session, owner); },
62
+ toggleClient: toggleClient, openSettings: settingsNavigation.open,
42
63
  });
43
64
  var agentTools = require('./mcp-agent-tools').attachMcpAgentTools({
44
- available: function (session) { return typeof ctx.canDiscoverSession === "function" && typeof ctx.runtimeEnvForSession === "function" && ctx.canDiscoverSession(session); },
65
+ available: function () { return true; }, management: management,
45
66
  clients: ctx.clients, isMultiUser: ctx.isMultiUser, ownerFor: ownerFor, canUseSession: ctx.canUseSession,
46
67
  authorizeOwner: authorizeOwner, discovery: discovery, importConnection: remote.importConnection,
47
68
  userInput: ctx.userInput, consentTimeout: ctx.consentTimeout,
@@ -64,7 +85,7 @@ function attachMcp(ctx) {
64
85
  extensionEnabled: server.enabled, status: active && server.enabled && device.hostConnected ? 'ready' : 'unavailable',
65
86
  error: active && device.hostConnected ? '' : 'Reconnect the local bridge on your computer.' });
66
87
  });
67
- return { type: 'mcp_servers_state', slug: ctx.slug, servers: servers,
88
+ return { type: 'mcp_servers_state', slug: ctx.slug, servers: servers, xcode: remote.xcodeState(owner),
68
89
  hostConnected: !!(active && device.hostConnected), extensionConnected: !!active,
69
90
  extensionId: device ? device.extensionId : null };
70
91
  }
@@ -87,6 +108,7 @@ function attachMcp(ctx) {
87
108
  });
88
109
  }
89
110
  function handleMcpMessage(ws, msg) {
111
+ if (msg && settingsNavigation.handle(ws, msg)) return true;
90
112
  if (!msg || typeof msg.type !== 'string' || (msg.type.indexOf('mcp_') !== 0 && msg.type !== 'mcp_toggle_server')) return false;
91
113
  var owner;
92
114
  try { owner = ownerFor(ws); } catch (error) { return true; }
@@ -122,7 +144,7 @@ function attachMcp(ctx) {
122
144
  if (msg.type === 'mcp_toggle_server') {
123
145
  var device = deviceFor(owner);
124
146
  if (device && device.servers.some(function (server) { return server.name === msg.name; })) {
125
- try { remote.toggleComputer(owner, msg.name, msg.enabled); } catch (error) { ctx.sendTo(ws, { type: 'mcp_action_result', ok: false, error: error.message }); }
147
+ try { toggleClient(owner, msg.name, msg.enabled); } catch (error) { ctx.sendTo(ws, { type: 'mcp_action_result', ok: false, error: error.message }); }
126
148
  }
127
149
  return true;
128
150
  }
@@ -176,7 +198,7 @@ function attachMcp(ctx) {
176
198
  pending.forEach(function (call, id) {
177
199
  if (call.manager === manager || removedSockets.indexOf(call.ws) >= 0) { clearTimeout(call.timer); call.reject(new Error('MCP closed.')); pending.delete(id); }
178
200
  });
179
- agentTools.destroy(); remote.destroy(); discovery.destroy();
201
+ settingsNavigation.destroy(); agentTools.destroy(); remote.destroy(); discovery.destroy();
180
202
  registry.managers.delete(manager);
181
203
  if (!registry.managers.size) SHARED_REGISTRIES.delete(namespace);
182
204
  }
@@ -0,0 +1,37 @@
1
+ // Shared read-only OS evidence for startup repair and reviewed live recovery.
2
+ var fs = require('fs');
3
+ var path = require('path');
4
+ function inspectPrivateOwner(project, accounts, resolveIdentity) {
5
+ var evidence = [], identities = [], root, stat;
6
+ function result(code, ownerId) { return { code: code, ownerId: ownerId || null, evidence: evidence }; }
7
+ try {
8
+ root = fs.realpathSync(project.path); stat = fs.statSync(root);
9
+ evidence.push([root, stat.dev, stat.ino, stat.uid, stat.mode]);
10
+ if (!stat.isDirectory() || root !== path.resolve(project.path)) return result('project_path_unverified');
11
+ } catch (error) { return result('project_unavailable'); }
12
+ for (var account of accounts) {
13
+ if (!account.linuxUser) continue;
14
+ try {
15
+ var identity = resolveIdentity(account.linuxUser);
16
+ var home = fs.realpathSync(identity.home), homeStat = fs.statSync(home);
17
+ evidence.push([account.id, account.linuxUser, identity.uid, home, homeStat.dev, homeStat.ino, homeStat.uid]);
18
+ if (!Number.isInteger(identity.uid) || identity.uid < 0 || homeStat.uid !== identity.uid || home !== path.resolve(identity.home) || home === path.parse(home).root) continue;
19
+ identities.push({ account: account, uid: identity.uid, home: home });
20
+ } catch (error) { evidence.push([account.id, 'unresolved']); return result('identity_unresolved'); }
21
+ }
22
+ if (!identities.length) return result('mapping_unavailable');
23
+ var matches = identities.filter(function (candidate) {
24
+ var relative = path.relative(candidate.home, root);
25
+ return candidate.uid === stat.uid && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
26
+ });
27
+ if (!matches.length) return result('owner_not_verified');
28
+ var unique = matches.filter(function (candidate) {
29
+ return !identities.some(function (other) {
30
+ if (other === candidate) return false;
31
+ var relative = path.relative(other.home, root);
32
+ return other.uid === candidate.uid || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep));
33
+ });
34
+ });
35
+ return unique.length === 1 ? result('verified', unique[0].account.id) : result('ambiguous_mapping');
36
+ }
37
+ module.exports = { inspectPrivateOwner: inspectPrivateOwner };
@@ -0,0 +1,59 @@
1
+ var crypto = require('crypto');
2
+ var fs = require('fs');
3
+ var ownership = require('./project-ownership');
4
+ var inspectPrivateOwner = require('./project-ownership-diagnostics').inspectPrivateOwner;
5
+ var REASONS = {
6
+ project_path_unverified: 'The project directory is not a verified real directory. The server operator must check its canonical path.',
7
+ project_unavailable: 'The server cannot inspect the project directory. The server operator must restore the directory or its filesystem access.',
8
+ identity_unresolved: 'A configured system account cannot be resolved. The server operator must repair verified account provisioning.',
9
+ mapping_unavailable: 'No verified account-to-system-user mapping is available. The server operator must verify or restore the original account mapping.',
10
+ owner_not_verified: 'No mapped account matches both the directory owner and its real home. The server operator must verify the original ownership and mapping.',
11
+ ambiguous_mapping: 'More than one account shares a system identity or overlapping home. The server operator must resolve the ambiguity.',
12
+ no_administrator: 'No existing administrator is available for the public project recovery policy.',
13
+ verified: 'The ownership checks identify one recovery owner.',
14
+ healthy: 'This project already has a valid owner.'
15
+ };
16
+ function createRecoveryService(ctx) {
17
+ var publicationFailures = new Map();
18
+ function inspect(slug) {
19
+ var config = ctx.getConfig(), accounts = ctx.getAccounts();
20
+ var project = (config.projects || []).find(function (entry) { return entry.slug === slug; });
21
+ if (!project || ownership.isPersonal(project) || slug.includes('--')) throw new Error('Choose an ordinary parent project for ownership recovery.');
22
+ var owner = accounts.find(function (account) { return account.id === project.ownerId; });
23
+ var healthy = owner && project.ownershipRecovery !== 'required';
24
+ var evidence = { code: healthy ? 'healthy' : 'verified', ownerId: owner && owner.id, evidence: [] };
25
+ if (!owner) {
26
+ if ((project.visibility || (config.osUsers ? 'private' : 'public')) === 'public') {
27
+ var admins = accounts.filter(function (account) { return account.role === 'admin'; }).sort(function (a, b) { return a.id.localeCompare(b.id); });
28
+ var preferred = config.ownershipRecoveryAdminId || config.singleUserMigratedUserId;
29
+ var designated = admins.find(function (account) { return account.id === preferred; }) || admins[0];
30
+ evidence = { code: designated ? 'verified' : 'no_administrator', ownerId: designated && designated.id, evidence: [] };
31
+ } else evidence = inspectPrivateOwner(project, accounts, ctx.resolveIdentity);
32
+ }
33
+ var directoryStamp;
34
+ try { var stat = fs.lstatSync(project.path); directoryStamp = [stat.dev, stat.ino, stat.uid, stat.mode]; } catch (error) { directoryStamp = 'unavailable'; }
35
+ var candidate = accounts.find(function (account) { return account.id === evidence.ownerId; });
36
+ var revision = crypto.createHash('sha256').update(JSON.stringify([project, directoryStamp, config.osUsers, config.ownershipRecoveryAdminId, config.singleUserMigratedUserId,
37
+ accounts.map(function (account) { return [account.id, account.role, account.linuxUser, account.displayName, account.username]; }), evidence])).digest('hex');
38
+ var failed = publicationFailures.get(slug) === revision;
39
+ return { slug: slug, status: failed ? 'publication_failed' : healthy ? 'healthy' : candidate ? 'ready' : 'blocked', code: failed ? 'publication_failed' : evidence.code, message: failed ? 'Ownership was saved but runtime publication failed. The server operator must reload the saved configuration before further recovery.' : REASONS[evidence.code], revision: revision,
40
+ owner: candidate ? { id: candidate.id, name: candidate.displayName || candidate.username } : null,
41
+ checkedAt: Date.now(), sessionOwnersChanged: false };
42
+ }
43
+ function apply(slug, revision, authorize) {
44
+ authorize();
45
+ var check = inspect(slug);
46
+ if (check.status !== 'ready' || check.revision !== revision) throw new Error('Ownership evidence changed or recovery is unavailable. Check again and review the current result.');
47
+ authorize();
48
+ var next = JSON.parse(JSON.stringify(ctx.getConfig()));
49
+ var project = next.projects.find(function (entry) { return entry.slug === slug; });
50
+ project.ownerId = check.owner.id; delete project.ownershipRecovery;
51
+ // Persistence must complete before any runtime or account can see repaired ownership.
52
+ ctx.persist(next);
53
+ try { ctx.publish(next, slug, check.owner.id); }
54
+ catch (error) { publicationFailures.set(slug, revision); return { ok: false, status: 'publication_failed', persisted: true, error: 'Ownership was saved, but runtime publication failed. Ask the server operator to reload the saved configuration; do not repeat recovery.' }; }
55
+ return { ok: true, status: 'recovered', persisted: true, owner: check.owner, sessionOwnersChanged: false };
56
+ }
57
+ return { inspect: inspect, apply: apply };
58
+ }
59
+ module.exports = { createRecoveryService: createRecoveryService };