brainiac-install 0.16.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 (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +70 -0
  3. package/bin/cli.js +583 -0
  4. package/package.json +38 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # brainiac-install
2
+
3
+ Thin bootstrap for the [Brainiac](https://github.com/Autopsias/brainiac) `brain`
4
+ CLI engine. One command on any machine with Node.js >=18:
5
+
6
+ ```
7
+ npx brainiac-install
8
+ ```
9
+
10
+ ## What it does
11
+
12
+ 1. **Detects** an existing `brain` on PATH. If found, it skips reinstalling
13
+ and points you at `brain update` instead.
14
+ 2. **Installs the engine from PyPI** (`brainiac-cli[mcp]`), trying in order:
15
+ `uv tool install` -> `pipx install` -> `python3 -m pip install --user`
16
+ (Windows: `py -3` / `python`). First one available on PATH wins. If none
17
+ of uv/pipx/Python >=3.9 are found, it prints the two official install
18
+ commands (the uv standalone installer, and python.org) and exits — it
19
+ never installs anything on your behalf beyond the `brainiac-cli` package
20
+ itself.
21
+ 3. **Verifies** the install (`brain --version`) and prints a PATH hint if the
22
+ new shim directory isn't on PATH in the current shell yet.
23
+ 4. **Initializes a vault** — prompts for a workspace directory (or accept one
24
+ via `--vault <path>`) and runs `brain init --full --apply` against
25
+ `<path>/vault`, so the bootstrap ends at a searchable vault, not just an
26
+ installed CLI. Decline (or run non-interactively without `--vault`) and it
27
+ prints the exact command to run yourself later.
28
+ 5. **Optionally wires one client** with `--client <name>` (one of
29
+ `claude-code`, `claude-desktop`, `codex`, `gemini`), delegating to
30
+ `brain connect --client <name>`. Without the flag it just lists the
31
+ available clients.
32
+
33
+ Add `--dry-run` to print the full command plan without executing anything —
34
+ no installs, no network access, no filesystem writes.
35
+
36
+ ## What it never does
37
+
38
+ - **No telemetry.** This script makes zero network calls itself; every
39
+ network access happens inside the tools it invokes (`uv`, `pipx`, `pip`),
40
+ which you can inspect independently.
41
+ - **No shell strings.** Every subprocess is spawned from an explicit argv
42
+ array (`spawnSync(..., { shell: false })`) against a binary this script
43
+ resolved to an absolute path itself. The one narrow exception: on Windows,
44
+ a resolved binary that turns out to be a `.cmd`/`.bat`/`.ps1` shim can't be
45
+ exec'd without a shell, so *that one call* is shell-routed with fully
46
+ static, hardcoded arguments — never user input, never a piped remote
47
+ script.
48
+ - **No runtime dependencies.** Pure Node.js stdlib (`node:child_process`,
49
+ `node:fs`, `node:os`, `node:path`, `node:readline`).
50
+ - **The engine is Python, distributed on PyPI** — this package is a thin
51
+ wrapper that shells out to `uv`/`pipx`/`pip` to install it. It is not a
52
+ reimplementation of `brain` in JavaScript, and it does not vendor or bundle
53
+ the engine.
54
+ - **Not for Node-free machines.** If Node.js itself isn't available, this
55
+ package can't run — use the `uvx`-based install path documented in the
56
+ main repo's `docs/install/` instead.
57
+
58
+ ## Flags
59
+
60
+ ```
61
+ --dry-run print the command plan; execute nothing
62
+ --vault <path> workspace directory; vault created at <path>/vault
63
+ --no-vault skip the vault-init step
64
+ --client <name> claude-code | claude-desktop | codex | gemini
65
+ -h, --help show help
66
+ ```
67
+
68
+ ## License
69
+
70
+ Apache-2.0
package/bin/cli.js ADDED
@@ -0,0 +1,583 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /*
5
+ * brainiac-install — thin npx bootstrap for the Brainiac `brain` CLI engine.
6
+ *
7
+ * What it does: detects an existing `brain` install, otherwise installs the
8
+ * `brainiac-cli[mcp]` distribution from PyPI via uv -> pipx -> pip --user
9
+ * (first available wins), verifies it, offers to initialize a vault
10
+ * (`brain init --full --apply`), and optionally wires one client
11
+ * (`brain connect --client <name>`).
12
+ *
13
+ * What it never does: no telemetry, no piping a remote script into a shell,
14
+ * no runtime dependencies. Every subprocess is spawned with an explicit argv
15
+ * array (spawnSync, shell:false) against a binary this script resolved to an
16
+ * absolute path itself — see resolveBinary()/needsShellRoute() below for the
17
+ * one narrow exception (Windows .cmd/.ps1 shims can't be exec'd without a
18
+ * shell; when that happens only THAT one call is shell-routed, with fully
19
+ * static args).
20
+ */
21
+
22
+ const { spawnSync } = require('node:child_process');
23
+ const fs = require('node:fs');
24
+ const os = require('node:os');
25
+ const path = require('node:path');
26
+
27
+ const PKG_SPEC = "brainiac-cli[mcp]";
28
+ // Mirrors src/brain/connect.py CLIENTS. Kept as a local, no-subprocess copy
29
+ // on purpose: --dry-run must validate --client without ever invoking `brain`.
30
+ // If connect.py grows a 5th client, add it here too (or drop this check and
31
+ // let `brain connect` be the sole validator — but that breaks dry-run
32
+ // validation, so the duplication is the deliberate tradeoff).
33
+ const CLIENTS = ['claude-code', 'claude-desktop', 'codex', 'gemini'];
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // argv parsing
37
+ // ---------------------------------------------------------------------------
38
+
39
+ // A missing token (undefined — off the end of argv) and a present-but-empty
40
+ // token (`--client ''` / `--client=`) both fail the same way: exit 2 with an
41
+ // actionable message. One helper, four call sites (space-form + `=`-form for
42
+ // each of --client/--vault) instead of the guard copy-pasted four times.
43
+ function requireValue(flagName, rawValue) {
44
+ if (rawValue === undefined || rawValue === '') {
45
+ console.error(`--${flagName} requires a value.\nRun with --help for usage.`);
46
+ process.exit(2);
47
+ }
48
+ return rawValue;
49
+ }
50
+
51
+ function parseArgs(argv) {
52
+ const opts = { dryRun: false, client: null, vault: null, noVault: false, help: false };
53
+ for (let i = 0; i < argv.length; i++) {
54
+ const a = argv[i];
55
+ if (a === '--dry-run') opts.dryRun = true;
56
+ else if (a === '--client') {
57
+ requireValue('client', argv[i + 1]);
58
+ opts.client = argv[++i];
59
+ }
60
+ else if (a.startsWith('--client=')) {
61
+ const v = a.slice('--client='.length);
62
+ requireValue('client', v);
63
+ opts.client = v;
64
+ }
65
+ else if (a === '--vault') {
66
+ requireValue('vault', argv[i + 1]);
67
+ opts.vault = argv[++i];
68
+ }
69
+ else if (a.startsWith('--vault=')) {
70
+ const v = a.slice('--vault='.length);
71
+ requireValue('vault', v);
72
+ opts.vault = v;
73
+ }
74
+ else if (a === '--no-vault') opts.noVault = true;
75
+ else if (a === '--help' || a === '-h') opts.help = true;
76
+ else {
77
+ console.error(`Unknown argument: ${a}\nRun with --help for usage.`);
78
+ process.exit(2);
79
+ }
80
+ }
81
+ if (opts.client && !CLIENTS.includes(opts.client)) {
82
+ console.error(`--client must be one of: ${CLIENTS.join(', ')}`);
83
+ process.exit(2);
84
+ }
85
+ return opts;
86
+ }
87
+
88
+ function printHelp() {
89
+ console.log(`brainiac-install — install the Brainiac 'brain' CLI engine and set up a vault.
90
+
91
+ Usage: npx brainiac-install [options]
92
+
93
+ Options:
94
+ --dry-run print the command plan; execute nothing (no network, no writes)
95
+ --vault <path> workspace directory; vault is created at <path>/vault
96
+ --no-vault skip the vault-init step (prints the command to run yourself)
97
+ --client <name> wire one client after install: ${CLIENTS.join(', ')}
98
+ -h, --help show this help
99
+
100
+ This tool never pipes a remote script into a shell. The engine ships on PyPI
101
+ as 'brainiac-cli' (Python >=3.9 required); see README.md for the full
102
+ install chain (uv -> pipx -> pip --user) and what happens with none present.`);
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // workspace path resolution — the SINGLE point that feeds BRAIN_VAULT,
107
+ // `connect --target`, and the printed "try it:" line. path.resolve() alone
108
+ // does not expand a leading `~`, so `~/my-brain` from the interactive prompt
109
+ // (or --vault ~/my-brain) would otherwise become `<cwd>/~/my-brain` (fix #2).
110
+ // ---------------------------------------------------------------------------
111
+
112
+ // Expand a bare `~` or a `~/...` (`~\...` on Windows) prefix to the home
113
+ // directory. Deliberately does NOT expand `~user` — no such lookup here.
114
+ function expandHome(p) {
115
+ if (p === '~') return os.homedir();
116
+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
117
+ return p;
118
+ }
119
+
120
+ function resolveWorkspace(raw) {
121
+ return path.resolve(expandHome(raw));
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // binary resolution — pure fs.PATH scan, no subprocess (works in --dry-run
126
+ // without executing anything; also sidesteps depending on which/where
127
+ // being present at all).
128
+ // ---------------------------------------------------------------------------
129
+
130
+ // A regular file on PATH isn't necessarily runnable — on non-Windows, only
131
+ // accept candidates that also carry the executable bit (mirrors what
132
+ // which/where actually check), so a non-executable file named e.g. `uv`
133
+ // can't short-circuit the install chain before uv/pipx/pip are all tried.
134
+ // Windows has no POSIX x-bit; the PATHEXT extension match is the gate there.
135
+ function isExecutableFile(candidate, isWin) {
136
+ try {
137
+ if (!fs.statSync(candidate).isFile()) return false;
138
+ } catch {
139
+ return false;
140
+ }
141
+ if (isWin) return true;
142
+ try {
143
+ fs.accessSync(candidate, fs.constants.X_OK);
144
+ return true;
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+
150
+ function resolveBinary(name) {
151
+ const isWin = process.platform === 'win32';
152
+ if (path.isAbsolute(name)) {
153
+ return isExecutableFile(name, isWin) ? name : null;
154
+ }
155
+ const pathEnv = process.env.PATH || process.env.Path || '';
156
+ const dirs = pathEnv.split(path.delimiter).filter(Boolean);
157
+ const exts = isWin ? (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';') : [''];
158
+ for (const dir of dirs) {
159
+ for (const ext of exts) {
160
+ const hasExt = ext && name.toLowerCase().endsWith(ext.toLowerCase());
161
+ const candidate = path.join(dir, hasExt ? name : name + ext);
162
+ if (isExecutableFile(candidate, isWin)) return candidate;
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+
168
+ // Windows-only: a resolved binary that is a .cmd/.bat/.ps1 shim (npm.cmd,
169
+ // scoop/choco wrappers) cannot be exec'd by spawnSync with shell:false.
170
+ // Route ONLY that one call through the shell, with fully static argv (never
171
+ // user input). Real .exe binaries (uv, pipx, python, brain) stay shell:false.
172
+ function needsShellRoute(resolvedPath) {
173
+ if (process.platform !== 'win32') return false;
174
+ const ext = path.extname(resolvedPath).toLowerCase();
175
+ return ext === '.cmd' || ext === '.bat' || ext === '.ps1';
176
+ }
177
+
178
+ // node's shell:true join ([file, ...args].join(' ')) does NOT quote
179
+ // anything itself before handing the string to cmd.exe — a resolved path
180
+ // under a directory with a space (e.g. a scoop/choco shim at
181
+ // "C:\Users\First Last\scoop\shims\brain.cmd") gets parsed as just
182
+ // "C:\Users\First", "is not recognized". Beyond whitespace, cmd.exe treats
183
+ // &, ^, (, ), <, > and | as metacharacters — an unquoted arg carrying one of
184
+ // these (e.g. a --target path like "C:\proj&test") gets mis-split and can
185
+ // run a second command (fix #2). Quote any token containing a space or one
186
+ // of these metachars, or an empty token, before it goes into a shell-routed
187
+ // command line.
188
+ //
189
+ // % and " are NOT in that quoted set — double-quoting can't neutralize
190
+ // either: cmd.exe still expands %VAR% inside double quotes, and a literal "
191
+ // can't be escaped/balanced through the plain [file, ...args].join(' ')
192
+ // shell:true route. Rather than silently pass a corrupted/expanded arg to
193
+ // cmd.exe, quoteForShell REJECTS (throws) on % or " — see spawnResolved,
194
+ // the only caller, which turns that into a clear CLI error + exit(2).
195
+ const CMD_METACHAR_RE = /[\s&^()<>|]/;
196
+ const CMD_UNSAFE_RE = /[%"]/;
197
+ function quoteForShell(s) {
198
+ const bad = CMD_UNSAFE_RE.exec(s);
199
+ if (bad) {
200
+ throw new Error(
201
+ `path contains a character unsupported on Windows shim invocation (${bad[0]}): ${s}. Use a path without % or ".`,
202
+ );
203
+ }
204
+ return (s === '' || CMD_METACHAR_RE.test(s)) ? `"${s}"` : s;
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // subprocess runner — argv array, shell:false unless the resolved binary is
209
+ // a Windows shim (see needsShellRoute), in which case the executable path
210
+ // and every arg are quoted first (see quoteForShell). Every spawnSync call
211
+ // in this file routes through here so the Windows quoting fix lives once.
212
+ // The shell:false path (the common case) never rejects anything — only the
213
+ // Windows shell-route branch can throw, on an unescapable %/" arg.
214
+ // ---------------------------------------------------------------------------
215
+
216
+ function spawnResolved(resolvedBin, args, spawnOpts) {
217
+ const shellRoute = needsShellRoute(resolvedBin);
218
+ if (!shellRoute) {
219
+ return spawnSync(resolvedBin, args, { ...spawnOpts, shell: false });
220
+ }
221
+ let bin, spawnArgs;
222
+ try {
223
+ bin = quoteForShell(resolvedBin);
224
+ spawnArgs = args.map(quoteForShell);
225
+ } catch (err) {
226
+ console.error(`Error: ${err.message}`);
227
+ process.exit(2);
228
+ }
229
+ return spawnSync(bin, spawnArgs, { ...spawnOpts, shell: true });
230
+ }
231
+
232
+ function resolvePython() {
233
+ if (process.platform === 'win32') {
234
+ // python3 does not exist on Windows; probe order is `py -3` then `python`.
235
+ const py = resolveBinary('py');
236
+ if (py) return { resolvedPath: py, label: 'py', argsPrefix: ['-3'] };
237
+ const python = resolveBinary('python');
238
+ if (python) return { resolvedPath: python, label: 'python', argsPrefix: [] };
239
+ return null;
240
+ }
241
+ const python3 = resolveBinary('python3');
242
+ if (python3) return { resolvedPath: python3, label: 'python3', argsPrefix: [] };
243
+ // Some systems only ship the 3.9+ interpreter as `python` (never
244
+ // `python3`) — mirror the Windows py -> python fallback above. Still
245
+ // gated by pythonVersionOk() before it's actually used.
246
+ const python = resolveBinary('python');
247
+ if (python) return { resolvedPath: python, label: 'python', argsPrefix: [] };
248
+ return null;
249
+ }
250
+
251
+ function pythonVersionOk(py) {
252
+ const res = spawnResolved(
253
+ py.resolvedPath,
254
+ [...py.argsPrefix, '-c', 'import sys; print(sys.version_info >= (3, 9))'],
255
+ { encoding: 'utf8' },
256
+ );
257
+ return res.status === 0 && (res.stdout || '').trim() === 'True';
258
+ }
259
+
260
+ function runCommand(resolvedBin, args, { dryRun, env } = {}) {
261
+ const display = [resolvedBin, ...args].join(' ');
262
+ if (dryRun) {
263
+ console.log(` [dry-run] would run: ${display}`);
264
+ return { ok: true, dryRun: true };
265
+ }
266
+ console.log(` $ ${display}`);
267
+ const res = spawnResolved(resolvedBin, args, {
268
+ stdio: 'inherit',
269
+ env: env ? { ...process.env, ...env } : process.env,
270
+ });
271
+ if (res.error) {
272
+ console.error(` error: ${res.error.message}`);
273
+ return { ok: false, error: res.error };
274
+ }
275
+ return { ok: res.status === 0, status: res.status };
276
+ }
277
+
278
+ function printNoPythonInstructions() {
279
+ console.log('No uv, pipx, or Python >=3.9 found on PATH.');
280
+ console.log('Install one of these yourself, then re-run this command:');
281
+ console.log('');
282
+ if (process.platform === 'win32') {
283
+ console.log(' uv (standalone): powershell -ExecutionPolicy Bypass -c "irm https://astral.sh/uv/install.ps1 | iex"');
284
+ } else {
285
+ console.log(' uv (standalone): curl -LsSf https://astral.sh/uv/install.sh | sh');
286
+ }
287
+ console.log(' Python: https://www.python.org/downloads/');
288
+ }
289
+
290
+ function printPathHint() {
291
+ const home = os.homedir();
292
+ console.log('brain installed but not found on PATH in this shell.');
293
+ console.log('Common shim locations (add to PATH, then open a new shell):');
294
+ console.log(` uv tool: ${path.join(home, '.local', 'bin')}`);
295
+ console.log(` pipx: ${path.join(home, '.local', 'bin')}`);
296
+ if (process.platform === 'win32') {
297
+ console.log(` pip --user: ${path.join(home, 'AppData', 'Roaming', 'Python', 'Scripts')}`);
298
+ } else if (process.platform === 'darwin') {
299
+ // macOS framework/python.org Python installs --user console scripts
300
+ // under ~/Library/Python/<X.Y>/bin, NOT ~/.local/bin (fix #5). The exact
301
+ // <X.Y> depends on which interpreter ran pip, so list the pattern
302
+ // alongside the Linux-style path rather than resolving one version.
303
+ console.log(` pip --user: ${path.join(home, '.local', 'bin')}`);
304
+ console.log(` ${path.join(home, 'Library', 'Python', '<X.Y>', 'bin')} (framework/python.org Python)`);
305
+ } else {
306
+ console.log(` pip --user: ${path.join(home, '.local', 'bin')}`);
307
+ }
308
+ }
309
+
310
+ // Pure — computes the Step 4 client-connect plan (or the reason to skip it)
311
+ // from state Step 3 already resolved. Side-effect-free (no console/spawn) so
312
+ // test/cli.test.js can exercise the --target/BRAIN_VAULT gating logic
313
+ // directly without spawning a real `brain` process.
314
+ function buildConnectPlan(o, state) {
315
+ if (!o.client) return { skip: 'no-client' };
316
+ if (state.stepFailed) return { skip: 'init-failed' };
317
+ const isDesktop = o.client === 'claude-desktop';
318
+ if (isDesktop && !state.vaultDir) return { skip: 'desktop-no-vault' };
319
+ const target = state.workspaceRoot || process.cwd();
320
+ // Marked-block clients (codex/claude-code/gemini) don't need a vault to
321
+ // exist, but Step 4 still spawns `brain connect` — with no BRAIN_VAULT in
322
+ // env, the engine's config.vault_root(None) falls through to its
323
+ // CWD/vault default and prints a multi-line stderr warning that's
324
+ // irrelevant here. Point BRAIN_VAULT at the (possibly not-yet-created)
325
+ // <target>/vault so vault_root() takes the explicit-env branch and stays
326
+ // quiet (fix #3). claude-desktop already requires a real vaultDir
327
+ // (refused above when absent), so state.vaultDir wins whenever it's set.
328
+ const vaultForEnv = state.vaultDir || path.join(target, 'vault');
329
+ return {
330
+ target,
331
+ args: ['connect', '--client', o.client, '--target', target, '--yes'],
332
+ env: { BRAIN_VAULT: vaultForEnv },
333
+ warnUninitialized: isDesktop && o.noVault === true,
334
+ };
335
+ }
336
+
337
+ // ---------------------------------------------------------------------------
338
+ // main
339
+ // ---------------------------------------------------------------------------
340
+
341
+ async function main() {
342
+ const opts = parseArgs(process.argv.slice(2));
343
+ if (opts.help) {
344
+ printHelp();
345
+ return 0;
346
+ }
347
+ const dryRun = opts.dryRun;
348
+
349
+ console.log(`Brainiac bootstrap${dryRun ? ' — DRY RUN (executes nothing, no network)' : ''}`);
350
+ console.log(`platform: ${process.platform}`);
351
+ console.log('');
352
+
353
+ // -- Step 1: engine ---------------------------------------------------
354
+ console.log('== Step 1/4: engine (brainiac-cli on PyPI) ==');
355
+ let brainBin = resolveBinary('brain');
356
+ let installOk = true;
357
+
358
+ if (brainBin) {
359
+ console.log(`already installed: ${brainBin}`);
360
+ console.log('to upgrade later, run: brain update');
361
+ } else {
362
+ const uv = resolveBinary('uv');
363
+ const pipx = resolveBinary('pipx');
364
+
365
+ if (uv) {
366
+ installOk = runCommand(uv, ['tool', 'install', PKG_SPEC], { dryRun }).ok;
367
+ } else if (pipx) {
368
+ installOk = runCommand(pipx, ['install', PKG_SPEC], { dryRun }).ok;
369
+ } else {
370
+ // Only scan PATH for a Python interpreter once uv AND pipx are both
371
+ // absent — resolvePython() does its own PATH walk(s), wasted work when
372
+ // either of the above already won (fix #6).
373
+ const py = resolvePython();
374
+ if (py && (dryRun || pythonVersionOk(py))) {
375
+ installOk = runCommand(
376
+ py.resolvedPath,
377
+ [...py.argsPrefix, '-m', 'pip', 'install', '--user', PKG_SPEC],
378
+ { dryRun },
379
+ ).ok;
380
+ } else {
381
+ printNoPythonInstructions();
382
+ if (!dryRun) {
383
+ process.exitCode = 2;
384
+ return 2;
385
+ }
386
+ installOk = false;
387
+ }
388
+ }
389
+
390
+ if (!dryRun && !installOk) {
391
+ console.log('Engine install failed — see output above.');
392
+ process.exitCode = 1;
393
+ return 1;
394
+ }
395
+ }
396
+
397
+ // -- Step 2: verify -----------------------------------------------------
398
+ console.log('');
399
+ console.log('== Step 2/4: verify ==');
400
+ if (dryRun) {
401
+ console.log(' [dry-run] would run: brain --version');
402
+ } else {
403
+ brainBin = resolveBinary('brain');
404
+ if (!brainBin) {
405
+ printPathHint();
406
+ process.exitCode = 2;
407
+ return 2;
408
+ }
409
+ const res = spawnResolved(brainBin, ['--version'], { encoding: 'utf8' });
410
+ if (res.status !== 0) {
411
+ console.log(res.error ? `❌ brain --version failed: ${res.error.message}` : '❌ brain --version failed');
412
+ process.exitCode = 2;
413
+ return 2;
414
+ }
415
+ console.log(`✅ ${(res.stdout || '').trim()}`);
416
+ }
417
+
418
+ // stepFailed tracks Step 3/4 failures so main() can exit non-zero even
419
+ // though those steps (unlike Steps 1/2) don't return early — a failed
420
+ // vault init or client connect must still fail `npx brainiac-install … && next`.
421
+ let stepFailed = false;
422
+ // workspaceRoot is the PROJECT ROOT (where CLAUDE.md/AGENTS.md/
423
+ // .gemini/settings.json live — see `brain connect --target`, DEFAULT ".").
424
+ // It is SEPARATE from vaultDir (workspaceRoot/vault, only relevant to
425
+ // BRAIN_VAULT). Both are resolved once here and reused by both Step 3 and
426
+ // Step 4 so they can never drift apart.
427
+ let workspaceRoot = null;
428
+ let vaultDir = null;
429
+ let initVault = false;
430
+
431
+ // -- Step 3: vault init ---------------------------------------------------
432
+ // Bootstrap ends at a usable vault, not a bare CLI — the ≤2-step promise is
433
+ // measured to first search, not to `brain --version`.
434
+ console.log('');
435
+ console.log('== Step 3/4: vault ==');
436
+
437
+ if (opts.noVault) {
438
+ if (opts.vault) {
439
+ // --no-vault skips *init*, but --vault still names the project root a
440
+ // marked-block client (codex/claude-code/gemini) should be wired
441
+ // into, and the (uninitialized) vault claude-desktop's stanza would
442
+ // point at — resolve it now so Step 4 has an explicit target (fix #5).
443
+ workspaceRoot = resolveWorkspace(opts.vault);
444
+ vaultDir = path.join(workspaceRoot, 'vault');
445
+ console.log(`--no-vault set; skipping vault init (workspace resolved for Step 4: ${workspaceRoot}).`);
446
+ } else {
447
+ console.log('--no-vault set; skipping vault init.');
448
+ }
449
+ } else {
450
+ let workspaceRaw = opts.vault;
451
+ if (!workspaceRaw) {
452
+ if (dryRun) {
453
+ // no interactive prompt in dry-run; fall through to the placeholder
454
+ // branch below so the full plan (incl. Step 4's --target) still
455
+ // prints deterministically with zero subprocess/stdin use.
456
+ } else if (process.stdin.isTTY) {
457
+ const readline = require('node:readline/promises');
458
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
459
+ const answer = (await rl.question(
460
+ 'Workspace directory for your vault (blank to skip; vault -> <path>/vault): ',
461
+ )).trim();
462
+ rl.close();
463
+ workspaceRaw = answer || null;
464
+ }
465
+ }
466
+ if (workspaceRaw) {
467
+ workspaceRoot = resolveWorkspace(workspaceRaw);
468
+ vaultDir = path.join(workspaceRoot, 'vault');
469
+ initVault = true;
470
+ } else if (dryRun) {
471
+ workspaceRoot = '<workspace>';
472
+ vaultDir = '<workspace>/vault';
473
+ initVault = true;
474
+ }
475
+ }
476
+
477
+ if (initVault) {
478
+ const cmdLine = `BRAIN_VAULT=${vaultDir} brain init --full --apply`;
479
+ console.log(` $ ${cmdLine}`);
480
+ if (dryRun) {
481
+ console.log(' [dry-run] would run the above');
482
+ } else {
483
+ const res = spawnResolved(brainBin, ['init', '--full', '--apply'], {
484
+ stdio: 'inherit',
485
+ env: { ...process.env, BRAIN_VAULT: vaultDir },
486
+ });
487
+ if (res.error) {
488
+ console.log(`❌ vault init: ${res.error.message}`);
489
+ stepFailed = true;
490
+ } else if (res.status === 0) {
491
+ console.log('✅ vault init');
492
+ console.log(` try it: BRAIN_VAULT=${vaultDir} brain search "<query>" --json`);
493
+ } else {
494
+ console.log('❌ vault init');
495
+ stepFailed = true;
496
+ }
497
+ }
498
+ } else if (!opts.noVault) {
499
+ console.log('Skipped — run this yourself when ready:');
500
+ console.log(' BRAIN_VAULT=<workspace>/vault brain init --full --apply');
501
+ }
502
+
503
+ // -- Step 4: client -------------------------------------------------------
504
+ // --yes: this is a non-interactive installer, so `brain connect` (which
505
+ // otherwise refuses to proceed without a TTY) must get the non-interactive
506
+ // opt-in explicitly. --target: `connect` writes CLAUDE.md/AGENTS.md/
507
+ // .gemini/settings.json under --target (default "." — the CWD `brain`
508
+ // itself would use, NOT the vault) — always pass it explicitly
509
+ // (workspaceRoot when known, else cwd) so wiring never silently lands
510
+ // wherever `npx` happened to be invoked from (fix #1). BRAIN_VAULT only
511
+ // matters to claude-desktop's stanza (codex/claude-code/gemini are
512
+ // pointer-only, no vault dependency); when no vault is known at all,
513
+ // claude-desktop is refused rather than silently pointing at brain's own
514
+ // $CWD/vault default (fix #5).
515
+ console.log('');
516
+ console.log('== Step 4/4: client ==');
517
+ if (opts.client) {
518
+ const plan = buildConnectPlan(opts, { workspaceRoot, vaultDir, stepFailed });
519
+ if (plan.skip === 'init-failed') {
520
+ console.log('Skipping client wiring: vault init failed.');
521
+ } else if (plan.skip === 'desktop-no-vault') {
522
+ console.log('⚠️ claude-desktop needs an explicit vault to point at; none is known');
523
+ console.log(' (pass --vault <path>, or drop --no-vault). Refusing to wire a silent');
524
+ console.log(' $CWD/vault default into the claude-desktop MCP stanza.');
525
+ // Same dry-run exemption as Step 1's no-Python case: a dry-run always
526
+ // previews the full plan and exits 0 (barring upfront arg-parse
527
+ // errors) — only a REAL run that truly cannot proceed fails.
528
+ if (!dryRun) stepFailed = true;
529
+ } else {
530
+ if (plan.warnUninitialized) {
531
+ console.log(`⚠️ --no-vault set: the claude-desktop stanza will point at ${vaultDir},`);
532
+ console.log(' which has not been initialized yet. Run the init command above first.');
533
+ }
534
+ const envLine = plan.env.BRAIN_VAULT ? `BRAIN_VAULT=${plan.env.BRAIN_VAULT} ` : '';
535
+ console.log(` $ ${envLine}brain ${plan.args.join(' ')}`);
536
+ if (dryRun) {
537
+ console.log(' [dry-run] would run the above');
538
+ } else {
539
+ const res = spawnResolved(brainBin, plan.args, {
540
+ stdio: 'inherit',
541
+ env: plan.env.BRAIN_VAULT ? { ...process.env, ...plan.env } : process.env,
542
+ });
543
+ if (res.error) {
544
+ console.log(`❌ client connect failed: ${res.error.message}`);
545
+ stepFailed = true;
546
+ } else if (res.status === 0) {
547
+ console.log('✅ client connected');
548
+ } else {
549
+ console.log('❌ client connect failed');
550
+ stepFailed = true;
551
+ }
552
+ }
553
+ }
554
+ } else {
555
+ console.log(`No --client given. Available: ${CLIENTS.join(', ')}`);
556
+ console.log('Re-run with --client <name> to wire one, e.g.: npx brainiac-install --client claude-code');
557
+ }
558
+
559
+ if (stepFailed) {
560
+ process.exitCode = 1;
561
+ return 1;
562
+ }
563
+ return 0;
564
+ }
565
+
566
+ // Exported for test/cli.test.js (node:test, stdlib only) to exercise the
567
+ // platform-conditional branches (Windows quoting, non-Windows executable-bit
568
+ // gating, python3->python fallback) that this repo's OS can't observe just
569
+ // by running the CLI end-to-end. require.main guard below keeps `require()`
570
+ // side-effect-free for that — main() only runs when this file is the entry.
571
+ module.exports = {
572
+ parseArgs, resolveBinary, isExecutableFile, needsShellRoute, quoteForShell,
573
+ resolvePython, CLIENTS, expandHome, resolveWorkspace, buildConnectPlan,
574
+ };
575
+
576
+ if (require.main === module) {
577
+ main()
578
+ .then((code) => { process.exitCode = code || 0; })
579
+ .catch((err) => {
580
+ console.error(err && err.stack ? err.stack : String(err));
581
+ process.exitCode = 1;
582
+ });
583
+ }
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "brainiac-install",
3
+ "version": "0.16.0",
4
+ "description": "One-command bootstrap for the Brainiac 'brain' CLI engine — installs brainiac-cli from PyPI (uv/pipx/pip), verifies it, and initializes a vault.",
5
+ "bin": {
6
+ "brainiac-install": "bin/cli.js"
7
+ },
8
+ "files": [
9
+ "bin/",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "scripts": {
14
+ "test": "node --test"
15
+ },
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Autopsias/brainiac.git",
23
+ "directory": "packaging/npm/brainiac-install"
24
+ },
25
+ "homepage": "https://github.com/Autopsias/brainiac",
26
+ "bugs": {
27
+ "url": "https://github.com/Autopsias/brainiac/issues"
28
+ },
29
+ "keywords": [
30
+ "brainiac",
31
+ "second-brain",
32
+ "bootstrap",
33
+ "installer",
34
+ "cli"
35
+ ],
36
+ "author": "Autopsias",
37
+ "dependencies": {}
38
+ }