joinweave 0.0.0-stage → 0.1.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.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 L1fe AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # joinweave
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The web wasn't built for agents. Weave was.
4
+
5
+ ```sh
6
+ npx joinweave@0.1.0
7
+ ```
8
+
9
+ Installs the prebuilt `weave` executable, creates `~/.weave` and `~/Weave`,
10
+ initializes a local identity, runs a user-level background node, and checks live
11
+ connectivity with `weave doctor`. No Rust toolchain or compilation is required.
12
+ macOS and Linux arm64/x64 are supported; Windows is not supported in 0.1.0.
13
+ Private keys stay in your local workspace.
14
+
15
+ The installer asks before adding a shell PATH line or editing any agent client
16
+ configuration. Existing unrelated entries are retained. Conflicting files,
17
+ modified installer entries and symbolic links are refused. Config edits use
18
+ atomic replacements and private backup files beside the config.
19
+
20
+ For agents and unattended installs:
21
+
22
+ ```sh
23
+ npx joinweave@0.1.0 --yes --json
24
+ ```
25
+
26
+ `--json` prints exactly one JSON result to stdout. Errors return `ok: false` and
27
+ a nonzero exit status. A doctor failure is an install failure; a build or healthy
28
+ process alone cannot substitute for peer discovery and an announce/find round
29
+ trip. The node and recoverable installation receipt remain available for a rerun.
30
+
31
+ Options:
32
+
33
+ - `--yes`: headless installation; skips PATH and MCP questions.
34
+ - `--path`: explicitly consent to adding the managed shell PATH entry.
35
+ - `--mcp-client cursor`: explicitly consent to configuring a named MCP client;
36
+ repeat or use a comma-separated list. Clients are `claude-desktop`,
37
+ `claude-code`, `cursor`, and `codex`. `one` and `bridge` print a manual setup
38
+ definition; their configuration files are not edited because no verified
39
+ writable MCP schema is available. These clients are detected when their
40
+ `.one`/`.bridge` directories or macOS application bundles are present.
41
+ - `--no-mcp`: skip agent configuration.
42
+ - `--no-service`: run a detached node with `weave node start` instead of
43
+ installing launchd or systemd. A live node is still required for doctor.
44
+ - `--json`: machine-readable output, with no prompts.
45
+
46
+ For example, consent to Cursor and Codex configuration headlessly:
47
+
48
+ ```sh
49
+ npx joinweave@0.1.0 --yes --path --mcp-client cursor,codex --json
50
+ ```
51
+
52
+ The MCP configuration starts `npx --yes @useweave/mcp@0.1.0` with the persistent
53
+ binary and workspace paths. The installed binary remains at `~/.weave/bin/weave`
54
+ after npm's execution cache is cleaned. Restart configured agent clients after
55
+ installation. Start a fresh shell after adding PATH, or use the absolute binary
56
+ path printed in the JSON result.
57
+
58
+ Manage the node with `weave node start`, `weave node stop`, `weave node status`,
59
+ and `weave node logs`. Linux service installation requires an available
60
+ `systemd --user` session. On a box without one, use `--no-service`.
61
+ `WEAVE_HOME` can select a dedicated absolute workspace directory.
62
+
63
+ ```sh
64
+ npx joinweave@0.1.0 uninstall --yes
65
+ npx joinweave@0.1.0 uninstall --yes --purge
66
+ ```
67
+
68
+ Uninstall stops the node and removes only owned service, executable, PATH and
69
+ MCP entries. It retains workspace data by default. `--purge` also deletes the
70
+ dedicated workspace, including local identity keys; `~/Weave` is always
71
+ preserved because it may contain unrelated user files. Modified installer
72
+ entries are retained and reported instead of being overwritten or deleted.
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { Installer, VERSION, parseArgs } from '../src/installer.js';
4
+
5
+ const jsonRequested = process.argv.slice(2).includes('--json');
6
+ let prompt;
7
+ try {
8
+ const options = parseArgs(process.argv.slice(2));
9
+ if (options.help) {
10
+ const usage = 'joinweave [uninstall] [--yes] [--json] [--no-service] [--no-mcp] [--path] [--mcp-client CLIENT] [--purge]\n\n--yes installs headlessly; PATH and MCP edits require --path and --mcp-client.\nClients: claude-desktop, claude-code, cursor, codex; one and bridge provide manual setup.\n--no-service starts a detached node. Uninstall keeps your data; --purge removes ~/.weave data.\n';
11
+ console.log(options.json ? JSON.stringify({ ok: true, version: VERSION, usage }) : usage);
12
+ } else if (options.version) console.log(options.json ? JSON.stringify({ ok: true, version: VERSION }) : VERSION);
13
+ else {
14
+ if (!options.yes && !options.json && !process.stdin.isTTY && options.action === 'install') throw Object.assign(new Error('For unattended installation use --yes. MCP and PATH edits still need explicit flags.'), { code: 'INTERACTION_REQUIRED' });
15
+ if (!options.yes && !options.json && process.stdin.isTTY) prompt = createInterface({ input: process.stdin, output: process.stderr });
16
+ const installer = new Installer({
17
+ resolveNative: options.action === 'install' ? (await import('@useweave/cli')).resolveBinary : undefined,
18
+ confirm: async (question) => prompt ? /^y(?:es)?$/i.test((await prompt.question(`${question} [y/N] `)).trim()) : false,
19
+ progress: (message) => { if (!options.json) console.error(`✓ ${message}`); },
20
+ });
21
+ const result = await installer[options.action](options);
22
+ if (options.json) console.log(JSON.stringify(result));
23
+ else if (options.action === 'install') {
24
+ console.log(`\nWeave is ready.\nWorkspace: ${result.shared}\nTry: ${result.pathAdded ? 'weave doctor' : `${result.binary} doctor`}\n`);
25
+ for (const manual of result.manualMcpClients) console.log(`${manual.client}: add this MCP server in the client's settings:\n${JSON.stringify({ weave: manual.server }, null, 2)}\n`);
26
+ }
27
+ else {
28
+ console.log(result.ok ? `Weave uninstalled. ${result.dataRetained ? 'Your data is preserved.' : 'Workspace data removed.'} Your ~/Weave folder is preserved.` : 'Uninstall preserved modified files.');
29
+ for (const warning of result.warnings) console.error(warning);
30
+ }
31
+ if (!result.ok) process.exitCode = 1;
32
+ }
33
+ } catch (error) {
34
+ const result = { ok: false, error: { code: error.code || 'INSTALL_FAILED', message: error.message } };
35
+ if (jsonRequested) console.log(JSON.stringify(result));
36
+ else console.error(`joinweave: ${error.message}`);
37
+ process.exitCode = 1;
38
+ } finally { prompt?.close(); }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "joinweave",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "One command to join the Weave agent-native web.",
6
+ "license": "MIT OR Apache-2.0",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "bin": {
11
+ "joinweave": "bin/joinweave.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@useweave/cli": "0.1.0"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/l1felabs/useweave.git",
24
+ "directory": "npm/joinweave"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test test/*.test.mjs"
31
+ }
32
+ }
@@ -0,0 +1,503 @@
1
+ import * as fs from 'node:fs';
2
+ import { homedir, hostname } from 'node:os';
3
+ import { resolve, join, dirname, isAbsolute, parse } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+
7
+ export const VERSION = '0.1.0';
8
+ const PATH_BEGIN = '# >>> joinweave managed PATH >>>';
9
+ const PATH_END = '# <<< joinweave managed PATH <<<' ;
10
+ const MCP_BEGIN = '# >>> joinweave managed MCP >>>';
11
+ const MCP_END = '# <<< joinweave managed MCP <<<';
12
+ const serviceName = 'com.useweave.node';
13
+ const clients = new Set(['claude-desktop', 'claude-code', 'cursor', 'codex']);
14
+ const manualClients = new Set(['one', 'bridge']);
15
+
16
+ export class InstallError extends Error {
17
+ constructor(code, message) { super(message); this.code = code; }
18
+ }
19
+ function fail(code, message) { throw new InstallError(code, message); }
20
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
21
+ const regular = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
22
+
23
+ export function parseArgs(args) {
24
+ const options = { action: 'install', yes: false, json: false, noService: false, noMcp: false, path: false, purge: false, mcpClients: [] };
25
+ for (let i = 0; i < args.length; i++) {
26
+ const arg = args[i];
27
+ if (arg === 'uninstall' && i === 0) options.action = 'uninstall';
28
+ else if (arg === '--yes' || arg === '-y') options.yes = true;
29
+ else if (arg === '--json') options.json = true;
30
+ else if (arg === '--no-service') options.noService = true;
31
+ else if (arg === '--no-mcp') options.noMcp = true;
32
+ else if (arg === '--path') options.path = true;
33
+ else if (arg === '--purge') options.purge = true;
34
+ else if (arg === '--help' || arg === '-h') options.help = true;
35
+ else if (arg === '--version' || arg === '-v') options.version = true;
36
+ else if (arg === '--mcp-client' || arg.startsWith('--mcp-client=')) {
37
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
38
+ if (!value) fail('INVALID_ARGUMENT', '--mcp-client requires a client name.');
39
+ for (const client of value.split(',')) {
40
+ if (!clients.has(client) && !manualClients.has(client)) fail('INVALID_ARGUMENT', `Unknown MCP client ${client}. Choose claude-desktop, claude-code, cursor or codex; one and bridge provide manual setup.`);
41
+ if (!options.mcpClients.includes(client)) options.mcpClients.push(client);
42
+ }
43
+ } else fail('INVALID_ARGUMENT', `Unknown argument: ${arg}`);
44
+ }
45
+ if (options.purge && options.action !== 'uninstall') fail('INVALID_ARGUMENT', '--purge is only valid with uninstall.');
46
+ if (options.noMcp && options.mcpClients.length) fail('INVALID_ARGUMENT', '--no-mcp conflicts with --mcp-client.');
47
+ return options;
48
+ }
49
+
50
+ /** Reject symlinks at every existing path component, including broken links. */
51
+ export function assertSafePath(path) {
52
+ if (!isAbsolute(path)) fail('UNSAFE_PATH', 'Installer paths must be absolute.');
53
+ const absolute = resolve(path), root = parse(absolute).root;
54
+ let cursor = root;
55
+ for (const part of absolute.slice(root.length).split('/').filter(Boolean)) {
56
+ cursor = join(cursor, part);
57
+ let stat;
58
+ try { stat = fs.lstatSync(cursor); }
59
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
60
+ if (stat.isSymbolicLink()) fail('UNSAFE_SYMLINK', `Refusing symbolic link at ${cursor}.`);
61
+ if (cursor !== absolute && !stat.isDirectory()) fail('UNSAFE_PATH', `Parent path is not a directory: ${cursor}.`);
62
+ }
63
+ }
64
+
65
+ function ensureDirectory(path, mode = 0o700) {
66
+ assertSafePath(path);
67
+ if (fs.existsSync(path)) {
68
+ if (!fs.lstatSync(path).isDirectory()) fail('UNSAFE_PATH', `Expected a directory at ${path}.`);
69
+ return;
70
+ }
71
+ const parent = dirname(path);
72
+ if (parent !== path) ensureDirectory(parent);
73
+ fs.mkdirSync(path, { mode });
74
+ }
75
+
76
+ function readFile(path) {
77
+ assertSafePath(path);
78
+ try {
79
+ const stat = fs.lstatSync(path);
80
+ if (!stat.isFile()) fail('UNSAFE_PATH', `Expected a regular file at ${path}.`);
81
+ return fs.readFileSync(path);
82
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
83
+ }
84
+
85
+ /** Atomic, compare-before-replace edit. Backups stay beside edited app files. */
86
+ function atomicWrite(path, bytes, { previous = null, mode = 0o600, backup = false } = {}) {
87
+ assertSafePath(path);
88
+ ensureDirectory(dirname(path));
89
+ const current = readFile(path);
90
+ if ((current === null) !== (previous === null) || (current && !current.equals(previous))) fail('CONCURRENT_EDIT', `The file changed while preparing an edit: ${path}. Rerun after the other editor finishes.`);
91
+ if (backup && current !== null) {
92
+ fs.writeFileSync(`${path}.joinweave-backup-${randomUUID()}`, current, { flag: 'wx', mode: 0o600 });
93
+ }
94
+ const temporary = join(dirname(path), `.joinweave-${randomUUID()}.new`);
95
+ try {
96
+ const fd = fs.openSync(temporary, 'wx', mode);
97
+ try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
98
+ assertSafePath(path);
99
+ const latest = readFile(path);
100
+ if ((latest === null) !== (previous === null) || (latest && !latest.equals(previous))) fail('CONCURRENT_EDIT', `Refusing to replace a concurrently edited file: ${path}.`);
101
+ fs.renameSync(temporary, path);
102
+ } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
103
+ }
104
+
105
+ function unlinkIfUnchanged(path, expectedHash) {
106
+ const current = readFile(path);
107
+ if (!current) return true;
108
+ if (digest(current) !== expectedHash) return false;
109
+ assertSafePath(path);
110
+ fs.unlinkSync(path);
111
+ return true;
112
+ }
113
+
114
+ export function runCommand(command, args, { env = process.env, timeout = 60_000 } = {}) {
115
+ return new Promise((done) => execFile(command, args, { env, timeout, maxBuffer: 2 * 1024 * 1024, encoding: 'utf8', shell: false }, (error, stdout, stderr) => {
116
+ done({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr });
117
+ }));
118
+ }
119
+
120
+ const xml = (value) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;');
121
+ const systemdQuote = (value, exec = false) => `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%').replaceAll('$', exec ? '$$' : '$')}"`;
122
+ // Scalar path directives do not use ExecStart/Environment's token parser.
123
+ const systemdPath = (value) => value.replaceAll('%', '%%');
124
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
125
+
126
+ export class Installer {
127
+ constructor({ home = homedir(), weaveHome = process.env.WEAVE_HOME || join(home, '.weave'), platform = process.platform, uid = process.getuid?.(), env = process.env, run = runCommand, resolveNative, confirm = async () => false, progress = () => {}, sleep = (ms) => new Promise((done) => setTimeout(done, ms)) } = {}) {
128
+ this.home = resolve(home);
129
+ this.weaveHome = resolve(weaveHome);
130
+ if ([this.home, this.weaveHome].some((path) => /[\x00-\x1f\x7f]/.test(path))) fail('UNSAFE_PATH', 'Workspace and home paths cannot contain control characters.');
131
+ if (!isAbsolute(weaveHome) || this.weaveHome === this.home || this.weaveHome === '/' || this.home.startsWith(`${this.weaveHome}/`)) fail('UNSAFE_HOME', 'WEAVE_HOME must be a dedicated absolute workspace directory.');
132
+ this.shared = join(this.home, 'Weave');
133
+ if (this.weaveHome === this.shared || this.shared.startsWith(`${this.weaveHome}/`)) fail('UNSAFE_HOME', 'WEAVE_HOME must be separate from the visible Weave folder.');
134
+ this.platform = platform;
135
+ this.uid = uid;
136
+ this.env = { ...env, WEAVE_HOME: this.weaveHome };
137
+ this.run = run;
138
+ this.resolveNative = resolveNative;
139
+ this.confirm = confirm;
140
+ this.progress = progress;
141
+ this.sleep = sleep;
142
+ this.binary = join(this.weaveHome, 'bin', 'weave');
143
+ this.manifestPath = join(this.weaveHome, '.joinweave-install.json');
144
+ this.lockPath = join(this.weaveHome, '.joinweave-install.lock');
145
+ this.manifest = { schema: 1, installer: 'joinweave', version: VERSION, binary: null, service: null, path: null, mcp: {} };
146
+ this.warnings = [];
147
+ this.manualMcp = [];
148
+ }
149
+
150
+ validatePlatform() {
151
+ if (!['darwin', 'linux'].includes(this.platform)) fail('UNSUPPORTED_PLATFORM', 'joinweave 0.1.0 supports macOS and Linux. Windows service installation is not supported yet.');
152
+ }
153
+
154
+ loadManifest() {
155
+ const bytes = readFile(this.manifestPath);
156
+ if (!bytes) return;
157
+ let value;
158
+ try { value = JSON.parse(bytes); } catch { fail('INVALID_MANIFEST', 'The installation receipt is invalid. It will not be overwritten.'); }
159
+ if (!regular(value) || value.schema !== 1 || value.installer !== 'joinweave' || !regular(value.mcp) || (value.binary && !/^[a-f0-9]{64}$/.test(value.binary.sha256))) fail('INVALID_MANIFEST', 'The installation receipt is not recognized. It will not be overwritten.');
160
+ this.manifest = value;
161
+ }
162
+
163
+ saveManifest() {
164
+ this.manifest.version = VERSION;
165
+ atomicWrite(this.manifestPath, Buffer.from(`${JSON.stringify(this.manifest, null, 2)}\n`), { previous: readFile(this.manifestPath) });
166
+ }
167
+
168
+ lock() {
169
+ assertSafePath(this.lockPath);
170
+ const old = readFile(this.lockPath);
171
+ if (old) {
172
+ let owner;
173
+ try { owner = JSON.parse(old); } catch { fail('INSTALL_LOCKED', 'An unrecognized installer lock exists. It will not be removed automatically.'); }
174
+ if (owner.host !== hostname() || !Number.isInteger(owner.pid) || owner.pid < 1) fail('INSTALL_LOCKED', 'Another installer owns this workspace.');
175
+ let alive = true;
176
+ try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
177
+ if (alive) fail('INSTALL_LOCKED', 'Another installer is running in this workspace.');
178
+ if (!unlinkIfUnchanged(this.lockPath, digest(old))) fail('INSTALL_LOCKED', 'Installer lock changed; rerun after the other installer finishes.');
179
+ }
180
+ this.lockBytes = Buffer.from(JSON.stringify({ pid: process.pid, host: hostname(), id: randomUUID() }));
181
+ fs.writeFileSync(this.lockPath, this.lockBytes, { flag: 'wx', mode: 0o600 });
182
+ }
183
+
184
+ unlock() {
185
+ if (this.lockBytes) unlinkIfUnchanged(this.lockPath, digest(this.lockBytes));
186
+ }
187
+
188
+ async native(args, label, timeout = 60_000) {
189
+ const result = await this.run(this.binary, args, { env: this.env, timeout });
190
+ if (result.code !== 0) fail('NATIVE_COMMAND_FAILED', `${label} failed (exit ${result.code}). Run ${this.binary} ${args.join(' ')} to inspect the runtime result.`);
191
+ let data;
192
+ try { data = JSON.parse(result.stdout); } catch { fail('INVALID_NATIVE_RESULT', `${label} did not return valid JSON.`); }
193
+ if (!regular(data) || data.ok !== true) fail('NATIVE_CHECK_FAILED', `${label} did not report success. Run weave doctor --json or weave node logs to diagnose connectivity.`);
194
+ return data;
195
+ }
196
+
197
+ async readyDoctor() {
198
+ const deadline = Date.now() + 30_000;
199
+ for (let attempt = 0; ; attempt++) {
200
+ try { return await this.native(['doctor', '--json'], 'Weave doctor', 90_000); }
201
+ catch (error) {
202
+ if (!['NATIVE_COMMAND_FAILED', 'NATIVE_CHECK_FAILED'].includes(error.code) || attempt >= 9 || Date.now() >= deadline) throw error;
203
+ await this.sleep(1_000);
204
+ }
205
+ }
206
+ }
207
+
208
+ installBinary() {
209
+ const source = this.resolveNative();
210
+ const stat = fs.lstatSync(source);
211
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('INVALID_BINARY', 'Native package executable must be a regular file.');
212
+ const bytes = fs.readFileSync(source), sha256 = digest(bytes), old = readFile(this.binary);
213
+ if (old && (!this.manifest.binary || digest(old) !== this.manifest.binary.sha256)) fail('UNMANAGED_BINARY', `An unrelated or modified executable exists at ${this.binary}. It will not be replaced.`);
214
+ if (!old || digest(old) !== sha256) atomicWrite(this.binary, bytes, { previous: old, mode: 0o755 });
215
+ fs.chmodSync(this.binary, 0o755);
216
+ this.manifest.binary = { sha256, version: VERSION };
217
+ this.saveManifest();
218
+ this.progress('Installed Weave');
219
+ }
220
+
221
+ serviceDefinition() {
222
+ const logs = join(this.weaveHome, 'logs');
223
+ const environment = { WEAVE_HOME: this.weaveHome };
224
+ for (const key of ['WEAVE_DHT_BOOTSTRAP', 'WEAVE_DHT_PORT', 'WEAVE_REPLICATION_ADVERTISE_ADDR', 'WEAVE_DHT_DISABLE_QUIC']) {
225
+ if (this.env[key] === undefined) continue;
226
+ const value = key === 'WEAVE_DHT_BOOTSTRAP' ? this.env[key].trim().split(/[\s,]+/).join(',') : this.env[key];
227
+ if (/[\x00-\x1f\x7f]/.test(value)) fail('INVALID_SERVICE_ENV', `${key} cannot contain control characters.`);
228
+ environment[key] = value;
229
+ }
230
+ const logPath = join(logs, 'node.log');
231
+ if (this.platform === 'darwin') {
232
+ const entries = Object.entries(environment).map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join('');
233
+ return { path: join(this.home, 'Library', 'LaunchAgents', `${serviceName}.plist`), bytes: Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${serviceName}</string>\n<key>ProgramArguments</key><array><string>${xml(this.binary)}</string><string>node</string><string>run</string></array>\n<key>EnvironmentVariables</key><dict>${entries}</dict>\n<key>WorkingDirectory</key><string>${xml(this.weaveHome)}</string>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>5</integer>\n<key>StandardOutPath</key><string>${xml(logPath)}</string>\n<key>StandardErrorPath</key><string>${xml(logPath)}</string>\n</dict></plist>\n`) };
234
+ }
235
+ const entries = Object.entries(environment).map(([key, value]) => `Environment=${systemdQuote(`${key}=${value}`)}\n`).join('');
236
+ return { path: join(this.home, '.config', 'systemd', 'user', 'weave-node.service'), bytes: Buffer.from(`[Unit]\nDescription=Weave peer node\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=${systemdQuote(this.binary, true)} node run\n${entries}WorkingDirectory=${systemdPath(this.weaveHome)}\nRestart=on-failure\nRestartSec=5\nStandardOutput=append:${systemdPath(logPath)}\nStandardError=append:${systemdPath(logPath)}\n\n[Install]\nWantedBy=default.target\n`) };
237
+ }
238
+
239
+ async serviceCommand(args, required = true) {
240
+ const command = this.platform === 'darwin' ? 'launchctl' : 'systemctl';
241
+ const result = await this.run(command, args, { env: this.env, timeout: 30_000 });
242
+ if (required && result.code !== 0) fail('SERVICE_COMMAND_FAILED', `${command} ${args.join(' ')} failed. Confirm a logged-in user service session is available; use --no-service for a detached node.`);
243
+ return result;
244
+ }
245
+
246
+ async stopService() {
247
+ if (this.platform === 'darwin') {
248
+ await this.serviceCommand(['bootout', `gui/${this.uid}/${serviceName}`], false);
249
+ const status = await this.serviceCommand(['print', `gui/${this.uid}/${serviceName}`], false);
250
+ if (status.code === 0) fail('SERVICE_STOP_FAILED', 'The launchd node remains registered. Its binary and configuration were preserved.');
251
+ const missing = `Could not find service "${serviceName}" in domain for user gui: ${this.uid}`;
252
+ if (status.code !== 113 || !status.stderr.includes(missing)) fail('SERVICE_STOP_UNKNOWN', 'Could not verify launchd shutdown. Its binary and configuration were preserved.');
253
+ } else {
254
+ await this.serviceCommand(['--user', 'disable', '--now', 'weave-node.service'], false);
255
+ const status = await this.serviceCommand(['--user', 'is-active', '--quiet', 'weave-node.service'], false);
256
+ if (status.code === 0) fail('SERVICE_STOP_FAILED', 'The systemd node remains active. Its binary and configuration were preserved.');
257
+ if (status.code !== 3 || status.stderr.trim()) fail('SERVICE_STOP_UNKNOWN', 'Could not verify systemd shutdown. Its binary and configuration were preserved.');
258
+ }
259
+ }
260
+
261
+ async installService() {
262
+ const service = this.serviceDefinition(), existing = readFile(service.path);
263
+ if (existing && (!this.manifest.service || this.manifest.service.path !== service.path || digest(existing) !== this.manifest.service.sha256)) fail('UNMANAGED_SERVICE', `An unrelated or modified service exists at ${service.path}. It will not be replaced.`);
264
+ ensureDirectory(join(this.weaveHome, 'logs'));
265
+ // Native logs and service log redirections must not follow a pre-existing symlink.
266
+ const logPath = join(this.weaveHome, 'logs', 'node.log');
267
+ if (readFile(logPath) === null) fs.writeFileSync(logPath, '', { flag: 'wx', mode: 0o600 });
268
+ fs.chmodSync(logPath, 0o600);
269
+ if (existing) await this.stopService();
270
+ atomicWrite(service.path, service.bytes, { previous: existing, mode: 0o600, backup: Boolean(existing) });
271
+ this.manifest.service = { platform: this.platform, path: service.path, sha256: digest(service.bytes) };
272
+ this.saveManifest();
273
+ if (this.platform === 'darwin') {
274
+ if (!Number.isInteger(this.uid)) fail('SERVICE_UNAVAILABLE', 'Cannot determine the user launchd session.');
275
+ await this.serviceCommand(['bootstrap', `gui/${this.uid}`, service.path]);
276
+ } else {
277
+ await this.serviceCommand(['--user', 'daemon-reload']);
278
+ await this.serviceCommand(['--user', 'enable', '--now', 'weave-node.service']);
279
+ }
280
+ this.progress('Started the background node');
281
+ }
282
+
283
+ pathDefinition() {
284
+ const shell = this.env.SHELL || '/bin/sh', name = shell.split('/').pop();
285
+ if (name === 'fish') return { path: join(this.home, '.config', 'fish', 'config.fish'), block: `${PATH_BEGIN}\nfish_add_path --path --prepend ${shellQuote(dirname(this.binary))}\n${PATH_END}\n` };
286
+ const path = join(this.home, name === 'zsh' ? '.zshrc' : name === 'bash' ? (this.platform === 'darwin' ? '.bash_profile' : '.bashrc') : '.profile');
287
+ return { path, block: `${PATH_BEGIN}\nexport PATH=${shellQuote(dirname(this.binary))}:"$PATH"\n${PATH_END}\n` };
288
+ }
289
+
290
+ installPath() {
291
+ const { path, block } = this.pathDefinition(), old = readFile(path), text = old?.toString('utf8') || '';
292
+ if (text.includes(PATH_BEGIN) || text.includes(PATH_END)) {
293
+ if (this.manifest.path?.path === path && this.manifest.path.block === block && text.includes(block)) return;
294
+ fail('UNMANAGED_PATH_ENTRY', `An unrecognized joinweave PATH block exists in ${path}. It will not be changed.`);
295
+ }
296
+ const prefix = text && !text.endsWith('\n') ? '\n' : '';
297
+ atomicWrite(path, Buffer.from(`${text}${prefix}${block}`), { previous: old, backup: Boolean(old) });
298
+ this.manifest.path = { path, block };
299
+ this.saveManifest();
300
+ this.progress('Added Weave to your shell PATH');
301
+ }
302
+
303
+ clientDefinition(client) {
304
+ const paths = {
305
+ 'claude-desktop': this.platform === 'darwin' ? join(this.home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json') : join(this.home, '.config', 'Claude', 'claude_desktop_config.json'),
306
+ 'claude-code': join(this.home, '.claude.json'),
307
+ cursor: join(this.home, '.cursor', 'mcp.json'),
308
+ codex: join(this.home, '.codex', 'config.toml'),
309
+ };
310
+ return { path: paths[client], format: client === 'codex' ? 'toml' : 'json' };
311
+ }
312
+
313
+ detectClients() {
314
+ const detected = [];
315
+ const hints = { 'claude-code': join(this.home, '.claude'), cursor: join(this.home, '.cursor'), codex: join(this.home, '.codex') };
316
+ for (const client of clients) {
317
+ const { path } = this.clientDefinition(client);
318
+ // Only test existence here; safety checks happen before a requested edit.
319
+ if (fs.existsSync(path) || fs.existsSync(hints[client] || dirname(path))) detected.push(client);
320
+ }
321
+ for (const client of manualClients) {
322
+ const appName = client === 'one' ? 'One.app' : 'Bridge.app';
323
+ if ([join(this.home, `.${client}`), join(this.home, 'Applications', appName), join('/Applications', appName)].some((path) => fs.existsSync(path))) detected.push(client);
324
+ }
325
+ return detected;
326
+ }
327
+
328
+ mcpDefinition() {
329
+ return { command: 'npx', args: ['--yes', '@useweave/mcp@0.1.0'], env: { WEAVE_HOME: this.weaveHome, WEAVE_BINARY: this.binary } };
330
+ }
331
+
332
+ mcpTomlBlock() {
333
+ return `${MCP_BEGIN}\n[mcp_servers.weave]\ncommand = "npx"\nargs = ["--yes", "@useweave/mcp@0.1.0"]\n\n[mcp_servers.weave.env]\nWEAVE_HOME = ${JSON.stringify(this.weaveHome)}\nWEAVE_BINARY = ${JSON.stringify(this.binary)}\n${MCP_END}\n`;
334
+ }
335
+
336
+ installMcp(client) {
337
+ if (manualClients.has(client)) {
338
+ this.manualMcp.push({ client, status: 'manual-setup-required', reason: 'No verified writable MCP configuration schema is available for this client.', server: this.mcpDefinition() });
339
+ this.progress(`${client} needs manual MCP setup`);
340
+ return;
341
+ }
342
+ const { path, format } = this.clientDefinition(client), old = readFile(path), previous = this.manifest.mcp[client], spec = this.mcpDefinition();
343
+ let bytes, ownership;
344
+ if (format === 'json') {
345
+ let config;
346
+ try { config = old ? JSON.parse(old.toString('utf8')) : {}; } catch { fail('INVALID_CLIENT_CONFIG', `${client} config is not valid JSON. It will not be changed.`); }
347
+ if (!regular(config) || (config.mcpServers !== undefined && !regular(config.mcpServers))) fail('INVALID_CLIENT_CONFIG', `${client} config has an unsupported MCP structure. It will not be changed.`);
348
+ config.mcpServers ||= {};
349
+ if (Object.hasOwn(config.mcpServers, 'weave')) {
350
+ if (!previous || previous.path !== path || JSON.stringify(previous.spec) !== JSON.stringify(spec) || JSON.stringify(config.mcpServers.weave) !== JSON.stringify(previous.spec)) fail('MCP_ENTRY_CONFLICT', `${client} already has an unrelated or modified weave MCP entry. It will not be changed.`);
351
+ }
352
+ config.mcpServers.weave = spec;
353
+ bytes = Buffer.from(`${JSON.stringify(config, null, 2)}\n`);
354
+ ownership = { path, format, spec };
355
+ } else {
356
+ const text = old?.toString('utf8') || '';
357
+ const block = this.mcpTomlBlock();
358
+ let next = text;
359
+ if (previous?.path === path && previous.block !== block) fail('INVALID_MANIFEST', 'The Codex MCP receipt is not a recognized Weave server definition.');
360
+ if (previous?.path === path && text.includes(block)) next = text.replace(block, '');
361
+ // Do not guess at inline/quoted TOML tables or overwrite foreign definitions.
362
+ if (/^\s*\[\[?\s*(?:mcp_servers|["']mcp_servers["'])\s*\./m.test(next) && /^\s*\[\[?\s*(?:mcp_servers|["']mcp_servers["'])\s*\.\s*(?:weave|["']weave["'])\s*(?:\.|\])/m.test(next)) fail('MCP_ENTRY_CONFLICT', 'Codex already has a weave MCP table. It will not be changed.');
363
+ if (next.includes(MCP_BEGIN) || next.includes(MCP_END) || /^\s*(?:mcp_servers|["']mcp_servers["'])\s*=/m.test(next) || /^\s*\[\s*(?:mcp_servers|["']mcp_servers["'])\s*\]\s*$/m.test(next)) fail('INVALID_CLIENT_CONFIG', 'Codex config uses a structure that cannot be merged safely. Add the Weave MCP entry manually.');
364
+ bytes = Buffer.from(`${next}${next && !next.endsWith('\n') ? '\n' : ''}\n${block}`);
365
+ ownership = { path, format, block };
366
+ }
367
+ atomicWrite(path, bytes, { previous: old, backup: Boolean(old) });
368
+ this.manifest.mcp[client] = ownership;
369
+ this.saveManifest();
370
+ this.progress(`Connected ${client}`);
371
+ }
372
+
373
+ async install(options) {
374
+ this.validatePlatform();
375
+ ensureDirectory(this.weaveHome);
376
+ this.lock();
377
+ try {
378
+ this.loadManifest();
379
+ this.installBinary();
380
+ ensureDirectory(this.shared, 0o755);
381
+ await this.native(['init', '--json'], 'Workspace initialization');
382
+ this.progress('Created your workspace and identity');
383
+ if (options.noService) {
384
+ // A rerun switching off service management must not leave two runtime owners.
385
+ if (this.manifest.service) await this.removeService();
386
+ if (this.manifest.service) fail('MODIFIED_SERVICE', 'The modified service was preserved. Stop and remove it before starting a detached node.');
387
+ await this.native(['node', 'start', '--json'], 'Detached node startup');
388
+ } else {
389
+ // Stop an earlier detached runtime before the service takes ownership.
390
+ await this.native(['node', 'stop', '--json'], 'Node shutdown before service startup');
391
+ await this.installService();
392
+ }
393
+ const detected = this.detectClients();
394
+ if (options.path || (!options.yes && !options.json && await this.confirm('Add Weave to your shell PATH?'))) this.installPath();
395
+ const selected = [...options.mcpClients];
396
+ if (!options.noMcp && !options.yes && !options.json) {
397
+ for (const client of detected) if (!selected.includes(client) && await this.confirm(manualClients.has(client) ? `Show manual Weave MCP setup for ${client}?` : `Add the Weave MCP server to ${client}?`)) selected.push(client);
398
+ }
399
+ for (const client of selected) this.installMcp(client);
400
+ // Doctor owns connectivity, peer and announce/find validation. Never turn a failed doctor into success.
401
+ const doctor = await this.readyDoctor();
402
+ this.progress('Verified Weave connectivity');
403
+ return { ok: true, action: 'install', version: VERSION, binary: this.binary, workspace: this.weaveHome, shared: this.shared, service: { managed: !options.noService, running: true }, pathAdded: Boolean(this.manifest.path), mcpClients: Object.keys(this.manifest.mcp), detectedMcpClients: detected, manualMcpClients: this.manualMcp, doctor, next: this.manifest.path ? 'weave doctor' : `${this.binary} doctor` };
404
+ } finally { this.unlock(); }
405
+ }
406
+
407
+ async removeService() {
408
+ const receipt = this.manifest.service;
409
+ if (!receipt) return;
410
+ const expected = this.serviceDefinition().path;
411
+ if (receipt.path !== expected || receipt.platform !== this.platform || !/^[a-f0-9]{64}$/.test(receipt.sha256 || '')) fail('INVALID_MANIFEST', 'Service receipt is not valid for this user and platform.');
412
+ const bytes = readFile(expected);
413
+ if (bytes && digest(bytes) !== receipt.sha256) { this.warnings.push('Preserved modified service configuration.'); return; }
414
+ await this.stopService();
415
+ unlinkIfUnchanged(expected, receipt.sha256);
416
+ if (this.platform === 'linux') await this.serviceCommand(['--user', 'daemon-reload'], false);
417
+ this.manifest.service = null;
418
+ this.saveManifest();
419
+ }
420
+
421
+ removePath() {
422
+ const receipt = this.manifest.path;
423
+ if (!receipt) return;
424
+ const allowed = [join(this.home, '.zshrc'), join(this.home, '.bashrc'), join(this.home, '.bash_profile'), join(this.home, '.profile'), join(this.home, '.config', 'fish', 'config.fish')];
425
+ const expectedBlock = receipt.path === allowed.at(-1) ? `${PATH_BEGIN}\nfish_add_path --path --prepend ${shellQuote(dirname(this.binary))}\n${PATH_END}\n` : `${PATH_BEGIN}\nexport PATH=${shellQuote(dirname(this.binary))}:"$PATH"\n${PATH_END}\n`;
426
+ if (!allowed.includes(receipt.path) || receipt.block !== expectedBlock) fail('INVALID_MANIFEST', 'PATH receipt is not valid.');
427
+ const old = readFile(receipt.path);
428
+ if (old) {
429
+ const text = old.toString('utf8');
430
+ if (!text.includes(receipt.block)) { this.warnings.push('Preserved modified shell PATH entry.'); return; }
431
+ atomicWrite(receipt.path, Buffer.from(text.replace(receipt.block, '')), { previous: old, backup: true });
432
+ }
433
+ this.manifest.path = null;
434
+ this.saveManifest();
435
+ }
436
+
437
+ removeMcp(client) {
438
+ if (!clients.has(client)) fail('INVALID_MANIFEST', 'Unknown MCP client in the installation receipt.');
439
+ const receipt = this.manifest.mcp[client], expected = this.clientDefinition(client);
440
+ if (receipt.path !== expected.path || receipt.format !== expected.format) fail('INVALID_MANIFEST', 'MCP receipt does not match this user.');
441
+ if (expected.format === 'json' && JSON.stringify(receipt.spec) !== JSON.stringify(this.mcpDefinition())) fail('INVALID_MANIFEST', 'MCP receipt is not a recognized Weave server definition.');
442
+ const old = readFile(expected.path);
443
+ if (old) {
444
+ let bytes;
445
+ if (expected.format === 'json') {
446
+ let config;
447
+ try { config = JSON.parse(old.toString('utf8')); } catch { this.warnings.push(`Preserved invalid ${client} config.`); return; }
448
+ if (!regular(config) || !regular(config.mcpServers)) { this.warnings.push(`Preserved modified ${client} config.`); return; }
449
+ if (Object.hasOwn(config.mcpServers, 'weave')) {
450
+ if (JSON.stringify(config.mcpServers.weave) !== JSON.stringify(receipt.spec)) { this.warnings.push(`Preserved modified ${client} weave MCP entry.`); return; }
451
+ delete config.mcpServers.weave;
452
+ bytes = Buffer.from(`${JSON.stringify(config, null, 2)}\n`);
453
+ }
454
+ } else {
455
+ const text = old.toString('utf8');
456
+ if (receipt.block !== this.mcpTomlBlock()) fail('INVALID_MANIFEST', 'MCP block receipt is not a recognized Weave server definition.');
457
+ if (!text.includes(receipt.block)) { this.warnings.push('Preserved modified Codex weave MCP entry.'); return; }
458
+ bytes = Buffer.from(text.replace(receipt.block, ''));
459
+ }
460
+ if (bytes) atomicWrite(expected.path, bytes, { previous: old, backup: true });
461
+ }
462
+ delete this.manifest.mcp[client];
463
+ this.saveManifest();
464
+ }
465
+
466
+ async uninstall(options) {
467
+ this.validatePlatform();
468
+ assertSafePath(this.weaveHome);
469
+ if (!fs.existsSync(this.weaveHome)) return { ok: true, action: 'uninstall', dataRetained: true, warnings: [] };
470
+ this.lock();
471
+ let purgeAfterUnlock = false;
472
+ try {
473
+ this.loadManifest();
474
+ const known = readFile(this.manifestPath);
475
+ if (!known) fail('NO_INSTALL_RECEIPT', 'No joinweave installation receipt exists. Existing files will not be removed.');
476
+ await this.removeService();
477
+ if (this.manifest.service) fail('MODIFIED_SERVICE', 'The modified service was preserved. Stop and remove it before uninstalling the binary.');
478
+ const binary = readFile(this.binary);
479
+ if (binary && this.manifest.binary && digest(binary) === this.manifest.binary.sha256) {
480
+ await this.native(['node', 'stop', '--json'], 'Node shutdown');
481
+ unlinkIfUnchanged(this.binary, this.manifest.binary.sha256);
482
+ this.manifest.binary = null;
483
+ this.saveManifest();
484
+ } else if (binary) this.warnings.push('Preserved unrelated or modified executable.');
485
+ this.removePath();
486
+ for (const client of Object.keys(this.manifest.mcp)) this.removeMcp(client);
487
+ if (options.purge && this.warnings.length) fail('PURGE_BLOCKED', 'Modified installer entries were preserved. Resolve them before purging workspace data.');
488
+ if (!this.warnings.length) {
489
+ const receipt = readFile(this.manifestPath);
490
+ if (receipt) unlinkIfUnchanged(this.manifestPath, digest(receipt));
491
+ }
492
+ purgeAfterUnlock = options.purge;
493
+ return { ok: this.warnings.length === 0, action: 'uninstall', dataRetained: !options.purge, workspace: this.weaveHome, shared: this.shared, warnings: this.warnings };
494
+ } finally {
495
+ this.unlock();
496
+ if (purgeAfterUnlock) {
497
+ assertSafePath(this.weaveHome);
498
+ fs.rmSync(this.weaveHome, { recursive: true });
499
+ // ~/Weave can contain unrelated user files, so even --purge preserves this visible folder.
500
+ }
501
+ }
502
+ }
503
+ }