dsh-taskbridge 1.7.0 → 1.8.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 (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -21
  3. package/README.md +150 -289
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -627
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +13 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +6 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +12 -5
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -53
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -0,0 +1,1046 @@
1
+ // Antigravity integration: install the self-contained DSH TaskBridge plugin bundle
2
+ // into `<ANTIGRAVITY_CONFIG_DIR>/plugins/dsh-taskbridge/` (default `~/.gemini/config`).
3
+ //
4
+ // Everything lives inside that single plugin directory so Antigravity can toggle or
5
+ // uninstall it cleanly without touching `~/.gemini/config/mcp_config.json` or
6
+ // `~/.gemini/config/config.json`:
7
+ //
8
+ // plugins/dsh-taskbridge/
9
+ // ├── plugin.json
10
+ // ├── mcp_config.json
11
+ // ├── assets/logo.svg
12
+ // ├── skills/dsh-taskbridge/SKILL.md
13
+ // └── agents/dsh-taskbridge.md
14
+ //
15
+ // Safety and ownership mirror `src/codex/installer.js`:
16
+ // * `status` is strictly read-only and never creates directories or files;
17
+ // * root symlink/junction is resolved and pinned once; links inside the plugin
18
+ // tree are refused as `conflict`;
19
+ // * ownership is proved by content digest (current template or recorded managed
20
+ // digest for this home) rather than by filename alone, so operator-edited
21
+ // skills, agents or MCP entries are preserved and never overwritten or deleted;
22
+ // * `install` manages both the plugin files and `mcp_config.json`, `repair` fixes
23
+ // MCP (plus a missing/outdated `plugin.json` manifest only) without touching
24
+ // skills or agents, and `remove` deletes only verified plugin-managed files;
25
+ // * startup refresh updates already-installed, unmodified outdated files in place
26
+ // and never performs a first install.
27
+
28
+ import { createHash } from 'node:crypto';
29
+ import { lstat, mkdir, readdir, readFile, realpath, rmdir, unlink } from 'node:fs/promises';
30
+ import { homedir } from 'node:os';
31
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
32
+ import { fileURLToPath } from 'node:url';
33
+
34
+ import { writeFileAtomic } from '../config/store.js';
35
+ import { digestLf, pluginDataDirectory } from '../codex/agent-ownership.js';
36
+ import {
37
+ DISCOVERY_ENV_VAR,
38
+ MCP_ENTRY_RELATIVE,
39
+ digest,
40
+ inspectDirectory,
41
+ isNodeExecutableName,
42
+ isOwnedEntryScript,
43
+ resolveNodeExecutable,
44
+ useDirectoryClassifier,
45
+ } from '../codex/installer.js';
46
+ import { resolveDefaultEndpointDiscoveryPath, resolveEndpointDiscoveryPath } from '../runtime/endpoint-discovery.js';
47
+
48
+ function sameFsPath(left, right) {
49
+ if (typeof left !== 'string' || typeof right !== 'string') return false;
50
+ const a = resolve(left);
51
+ const b = resolve(right);
52
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
53
+ }
54
+
55
+ export const ANTIGRAVITY_PLUGIN_NAME = 'dsh-taskbridge';
56
+ export const ANTIGRAVITY_MCP_SERVER_NAME = 'dsh-taskbridge';
57
+ export const ANTIGRAVITY_ACTIONS = Object.freeze(['status', 'install', 'repair', 'remove']);
58
+
59
+ export const ANTIGRAVITY_PLUGIN_STATES = Object.freeze({
60
+ missing: 'not-installed',
61
+ installed: 'installed',
62
+ outdated: 'outdated',
63
+ modified: 'modified',
64
+ conflict: 'conflict',
65
+ });
66
+
67
+ export const ANTIGRAVITY_MCP_STATES = Object.freeze({
68
+ missing: 'not-configured',
69
+ configured: 'configured',
70
+ outdated: 'outdated',
71
+ conflict: 'conflict',
72
+ unreadable: 'unreadable',
73
+ });
74
+
75
+ export const ANTIGRAVITY_ENV_VARS = Object.freeze(['ANTIGRAVITY_CONFIG_DIR', 'GEMINI_CONFIG_DIR']);
76
+
77
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
78
+ const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
79
+ const SKILL_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'skills', 'dsh-taskbridge', 'SKILL.md');
80
+ const AGENT_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'agents', 'dsh-taskbridge.md');
81
+ const LOGO_TEMPLATE_PATH = join(PACKAGE_ROOT, 'icon.svg');
82
+
83
+ const PLUGIN_FILE_KEYS = Object.freeze([
84
+ 'plugin.json',
85
+ 'skills/dsh-taskbridge/SKILL.md',
86
+ 'agents/dsh-taskbridge.md',
87
+ 'assets/logo.svg',
88
+ ]);
89
+
90
+ const MCP_FILE_KEY = 'mcp_config.json';
91
+ const OWNERSHIP_DIR_NAME = 'antigravity-plugin-ownership';
92
+ const OWNERSHIP_SCHEMA_VERSION = 1;
93
+ const MAX_FILE_BYTES = 1024 * 1024;
94
+ const MAX_OWNERSHIP_BYTES = 8192;
95
+ const SHA256_RE = /^[0-9a-f]{64}$/u;
96
+
97
+ const ALLOWED_MCP_ENTRY_KEYS = new Set(['command', 'args', 'env']);
98
+
99
+ export class AntigravityInstallError extends Error {
100
+ constructor(code, message, details = {}) {
101
+ super(message);
102
+ this.name = 'AntigravityInstallError';
103
+ this.code = code;
104
+ this.details = details;
105
+ }
106
+ }
107
+
108
+ export { useDirectoryClassifier };
109
+
110
+ function normalizeLf(text) {
111
+ return String(text ?? '').replace(/\r\n/gu, '\n');
112
+ }
113
+
114
+ function sameTextLf(left, right) {
115
+ if (left === right) return true;
116
+ const a = normalizeLf(left);
117
+ const b = normalizeLf(right);
118
+ if (a.includes('\r') || b.includes('\r')) return false;
119
+ return a === b;
120
+ }
121
+
122
+ export function resolveAntigravityHome({ env = process.env, homeDirectory = homedir() } = {}) {
123
+ for (const key of ANTIGRAVITY_ENV_VARS) {
124
+ const configured = typeof env?.[key] === 'string' ? env[key].trim() : '';
125
+ if (configured !== '') {
126
+ if (!isAbsolute(configured)) {
127
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', `${key} must be an absolute path`);
128
+ }
129
+ return resolve(configured);
130
+ }
131
+ }
132
+ return resolve(join(homeDirectory, '.gemini', 'config'));
133
+ }
134
+
135
+ export function requireAntigravityHome(antigravityHome) {
136
+ if (typeof antigravityHome !== 'string' || antigravityHome.trim() === '' || !isAbsolute(antigravityHome)) {
137
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', 'the Antigravity config directory must be an absolute path');
138
+ }
139
+ return resolve(antigravityHome);
140
+ }
141
+
142
+ async function readPackageVersion() {
143
+ try {
144
+ const manifest = JSON.parse(await readFile(PACKAGE_MANIFEST_PATH, 'utf8'));
145
+ return typeof manifest.version === 'string' ? manifest.version : '';
146
+ } catch {
147
+ return '';
148
+ }
149
+ }
150
+
151
+ export function renderAntigravityManifest(version) {
152
+ const manifest = {
153
+ name: ANTIGRAVITY_PLUGIN_NAME,
154
+ displayName: 'DSH TaskBridge',
155
+ version: version || '0.0.0',
156
+ description: '通过 DSH TaskBridge MCP 服务向 DeepSeek Harness 派工,支持先定方案后派工、后台静默等待、逐次权限审批与集中审查验收。',
157
+ logo: 'assets/logo.svg',
158
+ suggestedPrompts: [
159
+ '把当前仓库的功能修改交给 DSH TaskBridge 执行并在交付后审查',
160
+ '检查 DSH TaskBridge 本机调用状态和当前工作区预检结果',
161
+ '把多阶段目标拆成 TaskBridge 任务树并按顺序派给 DSH 执行',
162
+ ],
163
+ };
164
+ return `${JSON.stringify(manifest, null, 2)}\n`;
165
+ }
166
+
167
+ export async function readAntigravityTemplates(versionOverride = null) {
168
+ const version = typeof versionOverride === 'string' && versionOverride.trim() !== ''
169
+ ? versionOverride.trim()
170
+ : await readPackageVersion();
171
+ const [skill, agent, logo] = await Promise.all([
172
+ readFile(SKILL_TEMPLATE_PATH, 'utf8'),
173
+ readFile(AGENT_TEMPLATE_PATH, 'utf8'),
174
+ readFile(LOGO_TEMPLATE_PATH, 'utf8'),
175
+ ]);
176
+ return {
177
+ version,
178
+ files: {
179
+ 'plugin.json': renderAntigravityManifest(version),
180
+ 'skills/dsh-taskbridge/SKILL.md': normalizeLf(skill),
181
+ 'agents/dsh-taskbridge.md': normalizeLf(agent),
182
+ 'assets/logo.svg': normalizeLf(logo),
183
+ },
184
+ };
185
+ }
186
+
187
+ function pluginPathsFor(realHome) {
188
+ const pluginsDir = join(realHome, 'plugins');
189
+ const pluginDir = join(pluginsDir, ANTIGRAVITY_PLUGIN_NAME);
190
+ return {
191
+ pluginsDir,
192
+ pluginDir,
193
+ files: {
194
+ 'plugin.json': join(pluginDir, 'plugin.json'),
195
+ 'skills/dsh-taskbridge/SKILL.md': join(pluginDir, 'skills', 'dsh-taskbridge', 'SKILL.md'),
196
+ 'agents/dsh-taskbridge.md': join(pluginDir, 'agents', 'dsh-taskbridge.md'),
197
+ 'assets/logo.svg': join(pluginDir, 'assets', 'logo.svg'),
198
+ },
199
+ mcpPath: join(pluginDir, MCP_FILE_KEY),
200
+ dirs: [
201
+ pluginsDir,
202
+ pluginDir,
203
+ join(pluginDir, 'skills'),
204
+ join(pluginDir, 'skills', 'dsh-taskbridge'),
205
+ join(pluginDir, 'agents'),
206
+ join(pluginDir, 'assets'),
207
+ ],
208
+ };
209
+ }
210
+
211
+ function ownershipPathFor(realHome, env = process.env) {
212
+ const dataDir = pluginDataDirectory(env);
213
+ if (dataDir === null) return null;
214
+ const key = createHash('sha256').update(resolve(realHome), 'utf8').digest('hex');
215
+ return join(dataDir, OWNERSHIP_DIR_NAME, `${key}.json`);
216
+ }
217
+
218
+ async function readOwnershipRecord(realHome, env = process.env) {
219
+ const path = ownershipPathFor(realHome, env);
220
+ if (path === null) return null;
221
+ try {
222
+ const info = await lstat(path);
223
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_OWNERSHIP_BYTES) return null;
224
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
225
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
226
+ if (parsed.schemaVersion !== OWNERSHIP_SCHEMA_VERSION) return null;
227
+ if (typeof parsed.antigravityHome !== 'string' || resolve(parsed.antigravityHome) !== resolve(realHome)) return null;
228
+ if (parsed.files === null || typeof parsed.files !== 'object' || Array.isArray(parsed.files)) return null;
229
+ const files = {};
230
+ for (const [k, v] of Object.entries(parsed.files)) {
231
+ if (typeof v === 'string' && SHA256_RE.test(v)) files[k] = v;
232
+ }
233
+ return { path, files };
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+
239
+ async function writeOwnershipRecord(realHome, pluginDir, fileDigests, env = process.env) {
240
+ const path = ownershipPathFor(realHome, env);
241
+ if (path === null) return false;
242
+ try {
243
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
244
+ const record = {
245
+ schemaVersion: OWNERSHIP_SCHEMA_VERSION,
246
+ antigravityHome: resolve(realHome),
247
+ pluginDir: resolve(pluginDir),
248
+ files: fileDigests,
249
+ };
250
+ await writeFileAtomic(path, `${JSON.stringify(record, null, 2)}\n`);
251
+ return true;
252
+ } catch {
253
+ return false;
254
+ }
255
+ }
256
+
257
+ async function pinAntigravityHome(selected) {
258
+ const info = await inspectDirectory(selected).catch(() => ({ kind: 'unknown' }));
259
+ if (info.kind === 'missing' || info.kind === 'directory' || info.kind === 'unknown') {
260
+ return { selected, real: selected, linked: false, linkTarget: null, error: null };
261
+ }
262
+ if (info.kind === 'link') {
263
+ let resolved;
264
+ try {
265
+ resolved = await realpath(selected);
266
+ } catch {
267
+ return {
268
+ selected,
269
+ real: selected,
270
+ linked: true,
271
+ linkTarget: info.target ?? null,
272
+ error: {
273
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
274
+ reason: 'antigravity-home-link-unresolvable',
275
+ message: 'the Antigravity config directory link cannot be resolved to a real directory',
276
+ },
277
+ };
278
+ }
279
+ const targetInfo = await inspectDirectory(resolved).catch(() => ({ kind: 'unknown' }));
280
+ if (targetInfo.kind !== 'directory') {
281
+ return {
282
+ selected,
283
+ real: resolved,
284
+ linked: true,
285
+ linkTarget: info.target ?? null,
286
+ error: {
287
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
288
+ reason: 'antigravity-home-target-not-a-directory',
289
+ message: 'the Antigravity config directory link does not point at a real directory',
290
+ },
291
+ };
292
+ }
293
+ return { selected, real: resolved, linked: true, linkTarget: info.target ?? null, error: null };
294
+ }
295
+ return {
296
+ selected,
297
+ real: selected,
298
+ linked: false,
299
+ linkTarget: null,
300
+ error: {
301
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
302
+ reason: 'antigravity-home-not-a-directory',
303
+ message: 'the Antigravity config path exists but is not a directory',
304
+ },
305
+ };
306
+ }
307
+
308
+ async function inspectFileSafe(path) {
309
+ let info;
310
+ try {
311
+ info = await lstat(path);
312
+ } catch (error) {
313
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return { kind: 'missing' };
314
+ throw error;
315
+ }
316
+ if (info.isSymbolicLink()) return { kind: 'link' };
317
+ if (!info.isFile()) return { kind: 'other' };
318
+ if (info.size > MAX_FILE_BYTES) return { kind: 'other' };
319
+ return { kind: 'file', contents: await readFile(path, 'utf8') };
320
+ }
321
+
322
+ async function inspectBoundaries(realHome, paths) {
323
+ const rootInfo = await inspectDirectory(realHome).catch(() => ({ kind: 'unknown' }));
324
+ if (rootInfo.kind !== 'missing' && rootInfo.kind !== 'directory') {
325
+ return { ok: false, reason: rootInfo.kind === 'unknown' ? 'boundary-unverified' : 'antigravity-home-invalid', path: realHome };
326
+ }
327
+ for (const dir of paths.dirs) {
328
+ const info = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
329
+ if (info.kind === 'missing' || info.kind === 'directory') continue;
330
+ return {
331
+ ok: false,
332
+ reason: info.kind === 'link' ? 'plugin-dir-is-link' : (info.kind === 'unknown' ? 'boundary-unverified' : 'plugin-dir-not-a-directory'),
333
+ path: dir,
334
+ };
335
+ }
336
+ return { ok: true, reason: null, path: null };
337
+ }
338
+
339
+ function desiredMcpConfig(options = {}) {
340
+ const env = options.env ?? process.env;
341
+ const script = resolve(join(PACKAGE_ROOT, MCP_ENTRY_RELATIVE));
342
+ let node = null;
343
+ let nodeError = null;
344
+ try {
345
+ node = typeof options.nodeExecutable === 'string' && options.nodeExecutable.trim() !== ''
346
+ ? resolve(options.nodeExecutable)
347
+ : resolveNodeExecutable({ env, execPath: options.execPath, resourcesPath: options.resourcesPath, versions: options.versions, platform: options.platform });
348
+ } catch (error) {
349
+ nodeError = {
350
+ code: typeof error?.code === 'string' ? error.code : 'MCP_EXECUTABLE_UNRESOLVED',
351
+ message: String(error?.message ?? 'no Node.js executable could be proved'),
352
+ };
353
+ }
354
+ let discoveryFile = null;
355
+ if (typeof options.discoveryFile === 'string' && options.discoveryFile.trim() !== '') {
356
+ discoveryFile = resolve(options.discoveryFile);
357
+ } else {
358
+ const resolved = resolveEndpointDiscoveryPath(env);
359
+ const defaultPath = resolveDefaultEndpointDiscoveryPath(env);
360
+ if (resolved !== undefined && !sameFsPath(resolved, defaultPath)) {
361
+ discoveryFile = resolve(resolved);
362
+ }
363
+ }
364
+ const serverEntry = node === null ? null : {
365
+ command: node,
366
+ args: [script],
367
+ ...(discoveryFile === null ? {} : { env: { [DISCOVERY_ENV_VAR]: discoveryFile } }),
368
+ };
369
+ return { node, nodeError, script, discoveryFile, serverEntry };
370
+ }
371
+
372
+ function renderMcpDocument(existingDoc, serverEntry) {
373
+ const base = existingDoc !== null && typeof existingDoc === 'object' && !Array.isArray(existingDoc)
374
+ ? { ...existingDoc }
375
+ : {};
376
+ const servers = base.mcpServers !== null && typeof base.mcpServers === 'object' && !Array.isArray(base.mcpServers)
377
+ ? { ...base.mcpServers }
378
+ : {};
379
+ servers[ANTIGRAVITY_MCP_SERVER_NAME] = serverEntry;
380
+ base.mcpServers = servers;
381
+ return `${JSON.stringify(base, null, 2)}\n`;
382
+ }
383
+
384
+ function sameMcpEnv(actualEnv, desiredEnv) {
385
+ const a = actualEnv === undefined ? null : actualEnv;
386
+ const b = desiredEnv === undefined ? null : desiredEnv;
387
+ if (a === null && b === null) return true;
388
+ if (a === null || b === null) return false;
389
+ if (typeof a !== 'object' || Array.isArray(a)) return false;
390
+ const aKeys = Object.keys(a);
391
+ const bKeys = Object.keys(b);
392
+ if (aKeys.length !== bKeys.length) return false;
393
+ return aKeys.every((key) => typeof a[key] === 'string' && typeof b[key] === 'string' && sameFsPath(a[key], b[key]));
394
+ }
395
+
396
+ function isManagedMcpShape(entry) {
397
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false;
398
+ for (const key of Object.keys(entry)) {
399
+ if (!ALLOWED_MCP_ENTRY_KEYS.has(key)) return false;
400
+ }
401
+ if (typeof entry.command !== 'string' || !isNodeExecutableName(entry.command)) return false;
402
+ if (!Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string') return false;
403
+ if (entry.env !== undefined) {
404
+ if (entry.env === null || typeof entry.env !== 'object' || Array.isArray(entry.env)) return false;
405
+ const keys = Object.keys(entry.env);
406
+ if (keys.some((key) => key !== DISCOVERY_ENV_VAR || typeof entry.env[key] !== 'string')) return false;
407
+ }
408
+ return true;
409
+ }
410
+
411
+ async function classifyMcpFile({ mcpPath, desired, recordedDigest }) {
412
+ const file = await inspectFileSafe(mcpPath);
413
+ if (file.kind === 'missing') {
414
+ return {
415
+ path: mcpPath,
416
+ state: ANTIGRAVITY_MCP_STATES.missing,
417
+ configured: false,
418
+ managed: true,
419
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
420
+ script: desired.script,
421
+ node: desired.node,
422
+ nodeResolved: desired.node !== null,
423
+ nodeError: desired.nodeError,
424
+ reason: null,
425
+ existingDoc: null,
426
+ expectDigest: null,
427
+ };
428
+ }
429
+ if (file.kind !== 'file') {
430
+ return {
431
+ path: mcpPath,
432
+ state: ANTIGRAVITY_MCP_STATES.conflict,
433
+ configured: false,
434
+ managed: false,
435
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
436
+ script: desired.script,
437
+ node: desired.node,
438
+ nodeResolved: desired.node !== null,
439
+ nodeError: desired.nodeError,
440
+ reason: file.kind === 'link' ? 'mcp-file-is-link' : 'mcp-file-not-regular',
441
+ existingDoc: null,
442
+ expectDigest: null,
443
+ };
444
+ }
445
+ let parsed;
446
+ try {
447
+ parsed = JSON.parse(file.contents);
448
+ } catch {
449
+ return {
450
+ path: mcpPath,
451
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
452
+ configured: false,
453
+ managed: false,
454
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
455
+ script: desired.script,
456
+ node: desired.node,
457
+ nodeResolved: desired.node !== null,
458
+ nodeError: desired.nodeError,
459
+ reason: 'mcp-json-invalid',
460
+ existingDoc: null,
461
+ expectDigest: digest(file.contents),
462
+ };
463
+ }
464
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
465
+ return {
466
+ path: mcpPath,
467
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
468
+ configured: false,
469
+ managed: false,
470
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
471
+ script: desired.script,
472
+ node: desired.node,
473
+ nodeResolved: desired.node !== null,
474
+ nodeError: desired.nodeError,
475
+ reason: 'mcp-json-not-object',
476
+ existingDoc: null,
477
+ expectDigest: digest(file.contents),
478
+ };
479
+ }
480
+ const servers = parsed.mcpServers;
481
+ if (servers !== undefined && (servers === null || typeof servers !== 'object' || Array.isArray(servers))) {
482
+ return {
483
+ path: mcpPath,
484
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
485
+ configured: false,
486
+ managed: false,
487
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
488
+ script: desired.script,
489
+ node: desired.node,
490
+ nodeResolved: desired.node !== null,
491
+ nodeError: desired.nodeError,
492
+ reason: 'mcp-servers-not-object',
493
+ existingDoc: null,
494
+ expectDigest: digest(file.contents),
495
+ };
496
+ }
497
+ const entry = servers?.[ANTIGRAVITY_MCP_SERVER_NAME];
498
+ const fileDigest = digest(file.contents);
499
+ if (entry === undefined) {
500
+ return {
501
+ path: mcpPath,
502
+ state: ANTIGRAVITY_MCP_STATES.missing,
503
+ configured: false,
504
+ managed: true,
505
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
506
+ script: desired.script,
507
+ node: desired.node,
508
+ nodeResolved: desired.node !== null,
509
+ nodeError: desired.nodeError,
510
+ reason: null,
511
+ existingDoc: parsed,
512
+ expectDigest: fileDigest,
513
+ };
514
+ }
515
+ if (!isManagedMcpShape(entry)) {
516
+ return {
517
+ path: mcpPath,
518
+ state: ANTIGRAVITY_MCP_STATES.conflict,
519
+ configured: false,
520
+ managed: false,
521
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
522
+ script: desired.script,
523
+ node: desired.node,
524
+ nodeResolved: desired.node !== null,
525
+ nodeError: desired.nodeError,
526
+ reason: 'mcp-entry-customized',
527
+ existingDoc: parsed,
528
+ expectDigest: fileDigest,
529
+ };
530
+ }
531
+ const exactMatch = desired.serverEntry !== null
532
+ && sameFsPath(entry.command, desired.serverEntry.command)
533
+ && sameFsPath(entry.args[0], desired.serverEntry.args[0])
534
+ && sameMcpEnv(entry.env, desired.serverEntry.env);
535
+ if (exactMatch) {
536
+ return {
537
+ path: mcpPath,
538
+ state: ANTIGRAVITY_MCP_STATES.configured,
539
+ configured: true,
540
+ managed: true,
541
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
542
+ script: desired.script,
543
+ node: desired.node,
544
+ nodeResolved: desired.node !== null,
545
+ nodeError: desired.nodeError,
546
+ reason: null,
547
+ existingDoc: parsed,
548
+ expectDigest: fileDigest,
549
+ };
550
+ }
551
+ const recordedMatch = typeof recordedDigest === 'string' && digestLf(file.contents) === recordedDigest;
552
+ const sameScript = sameFsPath(entry.args[0], desired.script);
553
+ const ownedMovedScript = !sameScript && await isOwnedEntryScript(entry.args[0], desired.script);
554
+ if (recordedMatch || sameScript || ownedMovedScript) {
555
+ const reasons = [];
556
+ if (desired.node !== null && !sameFsPath(entry.command, desired.node)) reasons.push('node-path-changed');
557
+ if (!sameScript) reasons.push('script-path-changed');
558
+ if (desired.serverEntry !== null && !sameMcpEnv(entry.env, desired.serverEntry.env)) reasons.push('discovery-env-changed');
559
+ return {
560
+ path: mcpPath,
561
+ state: ANTIGRAVITY_MCP_STATES.outdated,
562
+ configured: false,
563
+ managed: true,
564
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
565
+ script: desired.script,
566
+ node: desired.node,
567
+ nodeResolved: desired.node !== null,
568
+ nodeError: desired.nodeError,
569
+ reason: reasons.join(',') || 'mcp-outdated',
570
+ movedScript: ownedMovedScript,
571
+ existingDoc: parsed,
572
+ expectDigest: fileDigest,
573
+ };
574
+ }
575
+ return {
576
+ path: mcpPath,
577
+ state: ANTIGRAVITY_MCP_STATES.conflict,
578
+ configured: false,
579
+ managed: false,
580
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
581
+ script: desired.script,
582
+ node: desired.node,
583
+ nodeResolved: desired.node !== null,
584
+ nodeError: desired.nodeError,
585
+ reason: 'mcp-script-unowned',
586
+ existingDoc: parsed,
587
+ expectDigest: fileDigest,
588
+ };
589
+ }
590
+
591
+ function isManagedAntigravityManifest(contents) {
592
+ try {
593
+ const parsed = JSON.parse(contents);
594
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
595
+ if (typeof parsed.version !== 'string' || parsed.version.trim() === '') return false;
596
+ return sameTextLf(contents, renderAntigravityManifest(parsed.version));
597
+ } catch {
598
+ return false;
599
+ }
600
+ }
601
+
602
+ async function classifyPluginFiles({ paths, templates, recordedFiles }) {
603
+ const details = {};
604
+ for (const key of PLUGIN_FILE_KEYS) {
605
+ const targetPath = paths.files[key];
606
+ const desiredText = templates.files[key];
607
+ const file = await inspectFileSafe(targetPath);
608
+ if (file.kind === 'missing') {
609
+ details[key] = { path: targetPath, state: 'not-installed', expectDigest: null };
610
+ continue;
611
+ }
612
+ if (file.kind !== 'file') {
613
+ details[key] = {
614
+ path: targetPath,
615
+ state: 'conflict',
616
+ reason: file.kind === 'link' ? 'file-is-link' : 'file-not-regular',
617
+ expectDigest: null,
618
+ };
619
+ continue;
620
+ }
621
+ const rawDigest = digest(file.contents);
622
+ if (sameTextLf(file.contents, desiredText)) {
623
+ details[key] = { path: targetPath, state: 'installed', expectDigest: rawDigest };
624
+ continue;
625
+ }
626
+ const recorded = recordedFiles?.[key] ?? null;
627
+ if (typeof recorded === 'string' && digestLf(file.contents) === recorded) {
628
+ details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
629
+ continue;
630
+ }
631
+ if (key === 'plugin.json' && isManagedAntigravityManifest(file.contents)) {
632
+ details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
633
+ continue;
634
+ }
635
+ details[key] = { path: targetPath, state: 'modified', expectDigest: rawDigest };
636
+ }
637
+ const states = Object.values(details).map((entry) => entry.state);
638
+ let state;
639
+ if (states.includes('conflict')) state = ANTIGRAVITY_PLUGIN_STATES.conflict;
640
+ else if (states.includes('modified')) state = ANTIGRAVITY_PLUGIN_STATES.modified;
641
+ else if (states.every((s) => s === 'not-installed')) state = ANTIGRAVITY_PLUGIN_STATES.missing;
642
+ else if (states.every((s) => s === 'installed')) state = ANTIGRAVITY_PLUGIN_STATES.installed;
643
+ else state = ANTIGRAVITY_PLUGIN_STATES.outdated;
644
+ return {
645
+ path: paths.pluginDir,
646
+ state,
647
+ installed: state === ANTIGRAVITY_PLUGIN_STATES.installed,
648
+ managed: state !== ANTIGRAVITY_PLUGIN_STATES.modified && state !== ANTIGRAVITY_PLUGIN_STATES.conflict,
649
+ files: details,
650
+ };
651
+ }
652
+
653
+ export async function readAntigravityStatus(options = {}) {
654
+ const env = options.env ?? process.env;
655
+ const selectedHome = typeof options.antigravityHome === 'string' && options.antigravityHome.trim() !== ''
656
+ ? requireAntigravityHome(options.antigravityHome)
657
+ : resolveAntigravityHome({ env, homeDirectory: options.homeDirectory });
658
+
659
+ const pinned = await pinAntigravityHome(selectedHome);
660
+ const templates = await readAntigravityTemplates(options.version ?? null);
661
+ const paths = pluginPathsFor(pinned.real);
662
+ const desiredMcp = desiredMcpConfig(options);
663
+ const notes = [];
664
+
665
+ if (pinned.error !== null) {
666
+ notes.push({ code: pinned.error.reason, text: pinned.error.message });
667
+ return {
668
+ antigravityHome: pinned.selected,
669
+ realAntigravityHome: pinned.real,
670
+ pluginDir: paths.pluginDir,
671
+ packageVersion: templates.version,
672
+ plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
673
+ mcp: {
674
+ path: paths.mcpPath,
675
+ state: ANTIGRAVITY_MCP_STATES.conflict,
676
+ configured: false,
677
+ managed: false,
678
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
679
+ script: desiredMcp.script,
680
+ node: desiredMcp.node,
681
+ nodeResolved: desiredMcp.node !== null,
682
+ nodeError: desiredMcp.nodeError,
683
+ reason: pinned.error.reason,
684
+ },
685
+ ready: false,
686
+ notes,
687
+ };
688
+ }
689
+
690
+ const boundary = await inspectBoundaries(pinned.real, paths);
691
+ if (!boundary.ok) {
692
+ notes.push({
693
+ code: boundary.reason,
694
+ text: `检测到非普通目录边界(${boundary.path}),插件不会穿过软链接或异常路径写入文件。`,
695
+ });
696
+ return {
697
+ antigravityHome: pinned.selected,
698
+ realAntigravityHome: pinned.real,
699
+ pluginDir: paths.pluginDir,
700
+ packageVersion: templates.version,
701
+ plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
702
+ mcp: {
703
+ path: paths.mcpPath,
704
+ state: ANTIGRAVITY_MCP_STATES.conflict,
705
+ configured: false,
706
+ managed: false,
707
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
708
+ script: desiredMcp.script,
709
+ node: desiredMcp.node,
710
+ nodeResolved: desiredMcp.node !== null,
711
+ nodeError: desiredMcp.nodeError,
712
+ reason: boundary.reason,
713
+ },
714
+ ready: false,
715
+ notes,
716
+ };
717
+ }
718
+
719
+ const ownership = await readOwnershipRecord(pinned.real, env);
720
+ const plugin = await classifyPluginFiles({
721
+ paths,
722
+ templates,
723
+ recordedFiles: ownership?.files ?? {},
724
+ });
725
+ const mcp = await classifyMcpFile({
726
+ mcpPath: paths.mcpPath,
727
+ desired: desiredMcp,
728
+ recordedDigest: ownership?.files?.[MCP_FILE_KEY] ?? null,
729
+ });
730
+
731
+ if (desiredMcp.nodeError !== null) {
732
+ notes.push({
733
+ code: desiredMcp.nodeError.code,
734
+ text: '未找到可用的 Node.js 运行时,无法写入 MCP 配置(不会写入桌面应用自身的 exe)。',
735
+ });
736
+ }
737
+ if (plugin.state === ANTIGRAVITY_PLUGIN_STATES.modified) {
738
+ notes.push({
739
+ code: 'PLUGIN_USER_MODIFIED',
740
+ text: '检测到插件目录内有你自定义修改过的文件,安装与卸载都会保留它们;若仅需恢复连接,可点「仅修复 MCP 配置」。',
741
+ });
742
+ }
743
+ if (mcp.state === ANTIGRAVITY_MCP_STATES.conflict || mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
744
+ notes.push({
745
+ code: 'MCP_CONFLICT',
746
+ text: 'plugins/dsh-taskbridge/mcp_config.json 存在自定义内容或格式错误,插件不会覆盖。',
747
+ });
748
+ }
749
+
750
+ return {
751
+ antigravityHome: pinned.selected,
752
+ realAntigravityHome: pinned.real,
753
+ pluginDir: paths.pluginDir,
754
+ packageVersion: templates.version,
755
+ plugin,
756
+ mcp,
757
+ ready: plugin.installed && mcp.configured,
758
+ notes,
759
+ };
760
+ }
761
+
762
+ async function ensureManagedDirs(paths) {
763
+ for (const dir of paths.dirs) {
764
+ const info = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
765
+ if (info.kind === 'directory') continue;
766
+ if (info.kind !== 'missing') {
767
+ throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `refused to traverse non-directory ${dir}`);
768
+ }
769
+ await mkdir(dir, { mode: 0o700 });
770
+ const after = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
771
+ if (after.kind !== 'directory') {
772
+ throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `created directory ${dir} could not be verified`);
773
+ }
774
+ }
775
+ }
776
+
777
+ async function ensureRootDir(realHome) {
778
+ const info = await inspectDirectory(realHome).catch(() => ({ kind: 'unknown' }));
779
+ if (info.kind === 'directory') return;
780
+ if (info.kind !== 'missing') {
781
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_UNUSABLE', `refused to use non-directory ${realHome}`);
782
+ }
783
+ await mkdir(realHome, { recursive: true, mode: 0o700 });
784
+ }
785
+
786
+ async function verifyUnchanged(filePath, expectDigest) {
787
+ const current = await inspectFileSafe(filePath);
788
+ if (expectDigest === null) return current.kind === 'missing';
789
+ return current.kind === 'file' && digest(current.contents) === expectDigest;
790
+ }
791
+
792
+ async function removeEmptyDirs(dirs) {
793
+ for (const dir of [...dirs].reverse()) {
794
+ try {
795
+ const entries = await readdir(dir);
796
+ if (entries.length === 0) await rmdir(dir);
797
+ } catch {
798
+ // ignore missing or non-empty dirs
799
+ }
800
+ }
801
+ }
802
+
803
+ export async function runAntigravityAction(action, options = {}) {
804
+ if (!ANTIGRAVITY_ACTIONS.includes(action)) {
805
+ throw new AntigravityInstallError('ANTIGRAVITY_ACTION_INVALID', `unknown action ${String(action)}`);
806
+ }
807
+ if (action === 'status') {
808
+ return { changed: [], refused: [], status: await readAntigravityStatus(options) };
809
+ }
810
+
811
+ const env = options.env ?? process.env;
812
+ const before = await readAntigravityStatus(options);
813
+ const templates = await readAntigravityTemplates(options.version ?? null);
814
+ const paths = pluginPathsFor(before.realAntigravityHome);
815
+ const desiredMcp = desiredMcpConfig(options);
816
+ const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
817
+ const nextDigests = { ...(ownership?.files ?? {}) };
818
+ const changed = [];
819
+ const refused = [];
820
+
821
+ if (before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.conflict) {
822
+ refused.push({ target: 'plugin', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
823
+ refused.push({ target: 'mcp', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
824
+ return { changed, refused, status: before };
825
+ }
826
+
827
+ if (action === 'install') {
828
+ await ensureRootDir(before.realAntigravityHome);
829
+ await ensureManagedDirs(paths);
830
+
831
+ // 1. Plugin bundle files (per-file: write missing/outdated managed files, preserve user-modified ones)
832
+ let wrotePlugin = false;
833
+ let modifiedPlugin = false;
834
+ let pluginConflict = false;
835
+ for (const key of PLUGIN_FILE_KEYS) {
836
+ const entry = before.plugin.files[key];
837
+ if (entry?.state === 'installed') {
838
+ nextDigests[key] = digestLf(templates.files[key]);
839
+ continue;
840
+ }
841
+ if (entry?.state === 'modified') {
842
+ modifiedPlugin = true;
843
+ continue;
844
+ }
845
+ if (entry?.state !== 'not-installed' && entry?.state !== 'outdated') {
846
+ pluginConflict = true;
847
+ continue;
848
+ }
849
+ if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
850
+ pluginConflict = true;
851
+ break;
852
+ }
853
+ await writeFileAtomic(paths.files[key], templates.files[key]);
854
+ nextDigests[key] = digestLf(templates.files[key]);
855
+ wrotePlugin = true;
856
+ }
857
+ if (wrotePlugin) changed.push('plugin');
858
+ if (pluginConflict) {
859
+ refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during install' });
860
+ } else if (modifiedPlugin) {
861
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
862
+ }
863
+
864
+ // 2. MCP config file
865
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
866
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
867
+ } else if (action === 'repair') {
868
+ await ensureRootDir(before.realAntigravityHome);
869
+ await ensureManagedDirs(paths);
870
+
871
+ // Repair touches mcp_config.json (and creates/updates plugin.json only if missing/outdated
872
+ // so Antigravity discovers the plugin), never touching SKILL.md or agents/dsh-taskbridge.md.
873
+ const manifestEntry = before.plugin.files['plugin.json'];
874
+ if (manifestEntry?.state === 'not-installed' || manifestEntry?.state === 'outdated') {
875
+ if (await verifyUnchanged(paths.files['plugin.json'], manifestEntry.expectDigest ?? null)) {
876
+ await writeFileAtomic(paths.files['plugin.json'], templates.files['plugin.json']);
877
+ nextDigests['plugin.json'] = digestLf(templates.files['plugin.json']);
878
+ }
879
+ }
880
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
881
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
882
+ } else if (action === 'remove') {
883
+ // 1. Remove verified managed plugin files only
884
+ let removedPlugin = false;
885
+ let refusedPlugin = false;
886
+ for (const key of PLUGIN_FILE_KEYS) {
887
+ const entry = before.plugin.files[key];
888
+ if (!entry || entry.state === 'not-installed') {
889
+ delete nextDigests[key];
890
+ continue;
891
+ }
892
+ if (entry.state !== 'installed' && entry.state !== 'outdated') {
893
+ refusedPlugin = true;
894
+ continue;
895
+ }
896
+ if (!(await verifyUnchanged(paths.files[key], entry.expectDigest))) {
897
+ refusedPlugin = true;
898
+ continue;
899
+ }
900
+ await unlink(paths.files[key]);
901
+ delete nextDigests[key];
902
+ removedPlugin = true;
903
+ }
904
+ if (removedPlugin) changed.push('plugin');
905
+ if (refusedPlugin) {
906
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
907
+ }
908
+
909
+ // 2. Remove managed MCP entry only
910
+ if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured || before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated) {
911
+ if (await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest)) {
912
+ const doc = { ...(before.mcp.existingDoc ?? {}) };
913
+ const servers = { ...(doc.mcpServers ?? {}) };
914
+ delete servers[ANTIGRAVITY_MCP_SERVER_NAME];
915
+ if (Object.keys(servers).length === 0 && Object.keys(doc).every((k) => k === 'mcpServers')) {
916
+ await unlink(paths.mcpPath);
917
+ } else {
918
+ doc.mcpServers = servers;
919
+ await writeFileAtomic(paths.mcpPath, `${JSON.stringify(doc, null, 2)}\n`);
920
+ }
921
+ delete nextDigests[MCP_FILE_KEY];
922
+ changed.push('mcp');
923
+ } else {
924
+ refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during remove' });
925
+ }
926
+ } else if (before.mcp.state === ANTIGRAVITY_MCP_STATES.conflict || before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
927
+ refused.push({ target: 'mcp', code: 'MCP_USER_MODIFIED', message: 'customized mcp_config.json was preserved' });
928
+ }
929
+
930
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
931
+ // Clean empty directories inside plugins/dsh-taskbridge only (never remove plugins/ itself).
932
+ await removeEmptyDirs(paths.dirs.slice(1));
933
+ }
934
+
935
+ return { changed, refused, status: await readAntigravityStatus(options) };
936
+ }
937
+
938
+ async function applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused }) {
939
+ if (desiredMcp.serverEntry === null) {
940
+ refused.push({
941
+ target: 'mcp',
942
+ code: desiredMcp.nodeError?.code ?? 'MCP_EXECUTABLE_UNRESOLVED',
943
+ message: desiredMcp.nodeError?.message ?? 'no Node.js executable available',
944
+ });
945
+ return;
946
+ }
947
+ if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured) {
948
+ const existing = await inspectFileSafe(paths.mcpPath);
949
+ if (existing.kind === 'file') nextDigests[MCP_FILE_KEY] = digestLf(existing.contents);
950
+ return;
951
+ }
952
+ if (before.mcp.state !== ANTIGRAVITY_MCP_STATES.missing && before.mcp.state !== ANTIGRAVITY_MCP_STATES.outdated) {
953
+ refused.push({
954
+ target: 'mcp',
955
+ code: before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable ? 'MCP_UNREADABLE' : 'MCP_CONFLICT',
956
+ message: 'mcp_config.json cannot be overwritten safely',
957
+ });
958
+ return;
959
+ }
960
+ if (!(await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest ?? null))) {
961
+ refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during write' });
962
+ return;
963
+ }
964
+ const rendered = renderMcpDocument(before.mcp.existingDoc, desiredMcp.serverEntry);
965
+ await writeFileAtomic(paths.mcpPath, rendered);
966
+ nextDigests[MCP_FILE_KEY] = digestLf(rendered);
967
+ changed.push('mcp');
968
+ }
969
+
970
+ export async function refreshManagedAntigravityPlugin(options = {}) {
971
+ const before = await readAntigravityStatus(options);
972
+ const env = options.env ?? process.env;
973
+ const templates = await readAntigravityTemplates(options.version ?? null);
974
+ const paths = pluginPathsFor(before.realAntigravityHome);
975
+ const desiredMcp = desiredMcpConfig(options);
976
+ const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
977
+ const nextDigests = { ...(ownership?.files ?? {}) };
978
+ const changed = [];
979
+ const refused = [];
980
+
981
+ // Never create a fresh installation on startup. Upgrade only provably existing
982
+ // managed plugin files (per-file when another file was customized by the user).
983
+ const pluginEntries = Object.values(before.plugin.files ?? {});
984
+ const hasOutdatedPluginFile = before.plugin.state !== ANTIGRAVITY_PLUGIN_STATES.conflict
985
+ && pluginEntries.some((entry) => entry?.state === 'outdated');
986
+ const hasExistingManagedPlugin = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated || hasOutdatedPluginFile;
987
+ const hasExistingStaleMcp = before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated && before.mcp.movedScript !== true;
988
+ if (!hasExistingManagedPlugin && !hasExistingStaleMcp) {
989
+ return { changed, refused, status: before };
990
+ }
991
+
992
+ if (hasExistingManagedPlugin) {
993
+ await ensureManagedDirs(paths);
994
+ const fillMissing = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated;
995
+ let wrotePlugin = false;
996
+ let modifiedPlugin = false;
997
+ let pluginConflict = false;
998
+ for (const key of PLUGIN_FILE_KEYS) {
999
+ const entry = before.plugin.files[key];
1000
+ if (entry?.state === 'modified') {
1001
+ modifiedPlugin = true;
1002
+ continue;
1003
+ }
1004
+ const shouldWrite = entry?.state === 'outdated' || (fillMissing && entry?.state === 'not-installed');
1005
+ if (!shouldWrite) continue;
1006
+ if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
1007
+ pluginConflict = true;
1008
+ break;
1009
+ }
1010
+ await writeFileAtomic(paths.files[key], templates.files[key]);
1011
+ nextDigests[key] = digestLf(templates.files[key]);
1012
+ wrotePlugin = true;
1013
+ }
1014
+ if (wrotePlugin) changed.push('plugin');
1015
+ if (pluginConflict) {
1016
+ refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during refresh' });
1017
+ } else if (modifiedPlugin) {
1018
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
1019
+ }
1020
+ }
1021
+
1022
+ if (hasExistingStaleMcp) {
1023
+ await ensureManagedDirs(paths);
1024
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
1025
+ }
1026
+
1027
+ if (changed.length > 0) {
1028
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
1029
+ }
1030
+ return { changed, refused, status: await readAntigravityStatus(options) };
1031
+ }
1032
+
1033
+ export function publicAntigravityStatus(status) {
1034
+ if (status === null || typeof status !== 'object') return status;
1035
+ const files = {};
1036
+ for (const [key, entry] of Object.entries(status.plugin?.files ?? {})) {
1037
+ const { expectDigest: _ignored, ...pub } = entry ?? {};
1038
+ files[key] = pub;
1039
+ }
1040
+ const { existingDoc: _doc, expectDigest: _digest, ...mcp } = status.mcp ?? {};
1041
+ return {
1042
+ ...status,
1043
+ plugin: { ...(status.plugin ?? {}), files },
1044
+ mcp,
1045
+ };
1046
+ }