@yahyahammad/venastine 0.3.8 → 0.3.9

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 (128) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2030 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1034 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +528 -528
  14. package/bin/venastine.py +71 -71
  15. package/cli_commands.py +838 -835
  16. package/config.yaml +13 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +971 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2715 -2715
  28. package/core/commands.py +460 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +234 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +458 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +108 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +733 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +295 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +267 -267
  102. package/tools/builtin/arxiv.py +681 -681
  103. package/tools/builtin/fetch_url.py +371 -371
  104. package/tools/builtin/file_ops.py +720 -720
  105. package/tools/builtin/geometry.py +184 -184
  106. package/tools/builtin/load_skill.py +76 -76
  107. package/tools/builtin/pin.py +227 -227
  108. package/tools/builtin/probability_stats.py +224 -224
  109. package/tools/builtin/project_docs.py +464 -464
  110. package/tools/builtin/remember.py +175 -175
  111. package/tools/builtin/shell.py +980 -980
  112. package/tools/builtin/todo.py +149 -149
  113. package/tools/builtin/web_search.py +328 -328
  114. package/tools/context.py +159 -159
  115. package/tools/isolation.py +387 -387
  116. package/tools/registry.py +1242 -1242
  117. package/tui/app.py +8318 -8307
  118. package/tui/app.tcss +747 -739
  119. package/tui/commands.py +26 -26
  120. package/tui/diffs.py +286 -286
  121. package/tui/history.py +128 -128
  122. package/tui/hosted_driver.py +102 -102
  123. package/tui/markdown.py +1329 -1329
  124. package/tui/meters.py +364 -364
  125. package/tui/ravens.py +146 -146
  126. package/tui/screens.py +1255 -1197
  127. package/tui/themes.py +599 -599
  128. package/tui/widgets.py +3813 -3796
package/bin/venastine.mjs CHANGED
@@ -1,528 +1,528 @@
1
- #!/usr/bin/env node
2
- /**
3
- * bin/venastine.mjs -- the npm entry point (batch 35).
4
- *
5
- * npm delivers this project as a FOLDER OF SOURCE, not a binary. This file
6
- * is the only thing npm can execute, so its whole job is to hand control to
7
- * the Python that actually implements the harness:
8
- *
9
- * find a Python >= 3.11 -> make sure its dependencies exist
10
- * -> spawn `python <root>/main.py` with the user's argv, cwd and stdio
11
- *
12
- * ZERO npm DEPENDENCIES, deliberately. Node stdlib only. The tarball is
13
- * first-party source and nothing else, which is what lets
14
- * THIRD_PARTY_NOTICES.md say the npm channel adds no licence surface. Do not
15
- * add a dependency here without changing that file too.
16
- *
17
- * WHAT THIS FILE MUST NEVER DO, and why each one is a real bug and not a
18
- * style preference:
19
- *
20
- * * Never set PYTHONPATH. tools/isolation.py builds its child's PYTHONPATH
21
- * from the PARENT's resolved sys.path -- "handing the child the paths the
22
- * parent actually resolved is deterministic". A value injected here would
23
- * be inherited into that computation and poison it.
24
- * * Never set AGENT_WORKSPACE. WORKSPACE_DIR is a PERMISSION BOUNDARY, not
25
- * a storage location: file_ops auto-approves writes inside it and demands
26
- * approval outside. Redirecting it to a shared home directory would
27
- * silently auto-approve writes there from every project.
28
- * * Never install without consent. See ensureRuntime().
29
- */
30
-
31
- import { spawnSync } from 'node:child_process';
32
- import crypto from 'node:crypto';
33
- import fs from 'node:fs';
34
- import os from 'node:os';
35
- import path from 'node:path';
36
- import readline from 'node:readline';
37
- import { fileURLToPath } from 'node:url';
38
-
39
- const HERE = path.dirname(fileURLToPath(import.meta.url));
40
- const ROOT = path.dirname(HERE);
41
- const REQUIREMENTS = path.join(ROOT, 'requirements.txt');
42
- const MAIN = path.join(ROOT, 'main.py');
43
- const CONFIG_FILE = path.join(ROOT, 'config.yaml');
44
- const CONFIG_UPDATE = path.join(ROOT, 'config_update.py');
45
-
46
- /**
47
- * ~/.config/venastine ON EVERY PLATFORM, Windows included.
48
- *
49
- * Not %APPDATA%, however Node-idiomatic that would be. The Python half of
50
- * this directory is already fixed: core/config_loader.py, mcp_client/config.py
51
- * and core/workspace_trust.py all resolve their user tier with
52
- * os.path.expanduser("~/.config/venastine"). Splitting one config directory
53
- * across two locations by platform is the bug this constant exists to avoid.
54
- */
55
- const CONFIG_HOME = path.join(os.homedir(), '.config', 'venastine');
56
-
57
- /**
58
- * Where config_update.py keeps the pristine copy and the user's mirror.
59
- *
60
- * Spelled in two languages, so a docs-consistency test holds this against
61
- * `config_update.STATE_DIRNAME`. Node owns only the two cheap halves -- the
62
- * post-session copy below, and the doctor lines -- because everything else
63
- * needs a YAML parser and this file has ZERO dependencies by design.
64
- */
65
- const CONFIG_STATE = path.join(CONFIG_HOME, 'config-state');
66
-
67
- const MIN_PYTHON = [3, 11];
68
-
69
- /** Python floor, in the terms the project already states it in (#144). */
70
- const PYTHON_FLOOR_MESSAGE =
71
- `Venastine needs Python ${MIN_PYTHON.join('.')} or newer.\n` +
72
- '\n' +
73
- 'mcp_client/client.py uses asyncio.timeout (3.11+) and 27 sites use runtime\n' +
74
- '`X | Y` annotations (3.10+). On an older interpreter the harness installs\n' +
75
- 'and then fails from inside the MCP connect path, which is why this refuses\n' +
76
- 'here instead.\n' +
77
- '\n' +
78
- 'Install Python 3.11+, or point VENASTINE_PYTHON at one:\n' +
79
- ' VENASTINE_PYTHON=/path/to/python3.12 venastine';
80
-
81
- function readPackageVersion() {
82
- try {
83
- return JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
84
- } catch {
85
- return '0.0.0';
86
- }
87
- }
88
-
89
- /**
90
- * Candidate interpreters, best first. The loop takes the first that satisfies
91
- * the floor, so an old `python3` earlier in the list simply falls through to a
92
- * newer explicit one rather than failing the launch.
93
- */
94
- function pythonCandidates() {
95
- if (process.env.VENASTINE_PYTHON) {
96
- return [{ cmd: process.env.VENASTINE_PYTHON, args: [], explicit: true }];
97
- }
98
- if (process.platform === 'win32') {
99
- // `py -3` is the launcher's newest install; the explicit ones are the
100
- // fallback for machines without the py launcher on PATH.
101
- return [
102
- { cmd: 'py', args: ['-3'] },
103
- { cmd: 'python', args: [] },
104
- { cmd: 'python3', args: [] },
105
- { cmd: 'py', args: ['-3.13'] },
106
- { cmd: 'py', args: ['-3.12'] },
107
- { cmd: 'py', args: ['-3.11'] },
108
- ];
109
- }
110
- return [
111
- { cmd: 'python3', args: [] },
112
- { cmd: 'python3.13', args: [] },
113
- { cmd: 'python3.12', args: [] },
114
- { cmd: 'python3.11', args: [] },
115
- { cmd: 'python', args: [] },
116
- ];
117
- }
118
-
119
- const PROBE = 'import sys; print("%d.%d" % sys.version_info[:2]); print(sys.executable)';
120
-
121
- function probe(candidate) {
122
- const r = spawnSync(candidate.cmd, [...candidate.args, '-c', PROBE], {
123
- encoding: 'utf8',
124
- // Windows resolves `py`/`python` through PATHEXT, which needs the shell
125
- // off but the extension search on -- spawnSync does that for us. What it
126
- // does NOT do is survive a missing binary, hence the status check below.
127
- windowsHide: true,
128
- });
129
- if (r.status !== 0 || !r.stdout) return null;
130
- const [version, executable] = r.stdout.trim().split(/\r?\n/);
131
- if (!version || !executable) return null;
132
- const [major, minor] = version.split('.').map(Number);
133
- return { ...candidate, version, executable, major, minor };
134
- }
135
-
136
- function findPython() {
137
- const rejected = [];
138
- for (const candidate of pythonCandidates()) {
139
- const found = probe(candidate);
140
- if (!found) continue;
141
- if (found.major > MIN_PYTHON[0] ||
142
- (found.major === MIN_PYTHON[0] && found.minor >= MIN_PYTHON[1])) {
143
- return found;
144
- }
145
- rejected.push(`${found.executable} (${found.version})`);
146
- }
147
- const detail = rejected.length
148
- ? `\n\nFound, but too old: ${rejected.join(', ')}`
149
- : '\n\nNo Python interpreter was found on PATH.';
150
- fail(PYTHON_FLOOR_MESSAGE + detail);
151
- }
152
-
153
- function requirementsHash() {
154
- return crypto.createHash('sha256')
155
- .update(fs.readFileSync(REQUIREMENTS))
156
- .digest('hex')
157
- .slice(0, 12);
158
- }
159
-
160
- /**
161
- * The runtime directory is keyed by VERSION AND requirements hash together.
162
- *
163
- * Either alone is not enough: a version bump with unchanged pins should reuse
164
- * the environment, and an edited pin within one version must NOT. Keying on
165
- * both means every distinct dependency set gets a clean venv instead of a
166
- * half-migrated one, and switching back to an older install finds its own
167
- * environment still intact.
168
- */
169
- function runtimePaths() {
170
- const dir = path.join(CONFIG_HOME, 'runtime', `${readPackageVersion()}-${requirementsHash()}`);
171
- return {
172
- dir,
173
- python: process.platform === 'win32'
174
- ? path.join(dir, 'Scripts', 'python.exe')
175
- : path.join(dir, 'bin', 'python'),
176
- // Written LAST, and it -- not the directory -- is what "ready" means. A
177
- // venv whose pip install died half way exists on disk and would otherwise
178
- // read as installed, then fail on a missing import at the first model call.
179
- stamp: path.join(dir, 'venastine-runtime.json'),
180
- };
181
- }
182
-
183
- function isReady(rt) {
184
- return fs.existsSync(rt.stamp) && fs.existsSync(rt.python);
185
- }
186
-
187
- // Non-comment lines in requirements.txt. NOT a count of pins, which is what
188
- // it was called until batch 140: some lines are ranges (a floor and a
189
- // ceiling, like `rich`'s), so the screen that said "N pinned packages" was
190
- // promising something the file does not say. The exact set is in the file
191
- // the screen names, which is what makes the count enough. (This comment
192
- // said "2 of the 18" until batch 208, by when it was 4 of 20: a count in
193
- // prose beside the code that computes it is the copy that drifts.)
194
- function countRequirements() {
195
- return fs.readFileSync(REQUIREMENTS, 'utf8')
196
- .split(/\r?\n/)
197
- .filter((line) => line.trim() && !line.trim().startsWith('#'))
198
- .length;
199
- }
200
-
201
- // ROADMAP_v3 §88 (A83). The harness runs under this process with the console
202
- // inherited, and it is the terminal's one reader from then on, so this
203
- // process stops reading in so many words: rl.close() only ASKS libuv to stop,
204
- // and on Windows its console reader is a thread whose read in flight cannot
205
- // be cancelled. pause() is the same request made of the stream itself, and
206
- // unref() lets nothing about stdin keep this process alive. Measured in a
207
- // console of its own, five keys typed at the child after the consent all
208
- // reached it, before this and after it, three runs each: the old shape
209
- // lost nothing there, and this one loses nothing either.
210
- function ask(question) {
211
- return new Promise((resolve) => {
212
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
213
- rl.question(question, (answer) => {
214
- rl.close();
215
- process.stdin.pause();
216
- if (typeof process.stdin.unref === 'function') process.stdin.unref();
217
- resolve(/^y(es)?$/i.test(answer.trim()));
218
- });
219
- });
220
- }
221
-
222
- /**
223
- * Build the Python environment, only ever with the user's say-so.
224
- *
225
- * The consent prompt is not ceremony. This is the one action the launcher
226
- * takes on its own initiative -- it runs a network install of everything in
227
- * requirements.txt -- and the project's own rule for that case is D17/D31:
228
- *
229
- * NO COUNT IN THIS SENTENCE, deliberately (batch 140). It said "17
230
- * pinned distributions" and the file had 22 installable lines when that was
231
- * measured, 18 now that batch 136 moved the test packages out. The screen
232
- * below prints the live number; prose that restates a computed value is a
233
- * second copy of it, and this is the copy that drifted.
234
- * show what will run and confirm it. That is also why the bootstrap is here
235
- * and not in an npm `postinstall` hook, where it would run unannounced and be
236
- * skipped entirely under `--ignore-scripts`.
237
- *
238
- * NOT A TTY AND NO --venastine-yes => REFUSE AND PRINT THE COMMAND. A CI job
239
- * or a piped invocation must not be able to trigger an unattended install
240
- * just by being unable to answer.
241
- */
242
- async function ensureRuntime(python, rt, { assumeYes }) {
243
- if (isReady(rt)) return;
244
-
245
- const summary =
246
- 'Venastine needs a Python environment (first run).\n' +
247
- ` python : ${python.version} (${python.executable})\n` +
248
- ` venv : ${rt.dir}\n` +
249
- ` install : ${countRequirements()} packages from requirements.txt\n`;
250
-
251
- if (!assumeYes) {
252
- if (!process.stdin.isTTY) {
253
- fail(
254
- summary +
255
- '\nRefusing to install unattended (no terminal to ask in).\n' +
256
- 'Re-run interactively, pass --venastine-yes, or build it yourself:\n' +
257
- ` ${python.executable} -m venv "${rt.dir}"\n` +
258
- ` "${rt.python}" -m pip install -r "${REQUIREMENTS}"`
259
- );
260
- }
261
- process.stdout.write(summary);
262
- const ok = await ask('Proceed? [y/N] ');
263
- if (!ok) fail('Cancelled. Nothing was installed.');
264
- } else {
265
- process.stdout.write(summary);
266
- }
267
-
268
- try {
269
- run(python.executable, ['-m', 'venv', rt.dir]);
270
- run(rt.python, ['-m', 'pip', 'install', '--disable-pip-version-check',
271
- '-r', REQUIREMENTS]);
272
- } catch (e) {
273
- // Leave nothing half-built behind: the next run must start clean rather
274
- // than inherit a venv that is missing an unknown subset of its packages.
275
- fs.rmSync(rt.dir, { recursive: true, force: true });
276
- fail(`Environment setup failed: ${e.message}`);
277
- }
278
-
279
- fs.writeFileSync(rt.stamp, JSON.stringify({
280
- version: readPackageVersion(),
281
- requirementsHash: requirementsHash(),
282
- python: python.executable,
283
- pythonVersion: python.version,
284
- createdAt: new Date().toISOString(),
285
- }, null, 2));
286
- }
287
-
288
- function run(cmd, args) {
289
- const r = spawnSync(cmd, args, { stdio: 'inherit', windowsHide: true });
290
- if (r.error) throw r.error;
291
- if (r.status !== 0) throw new Error(`${path.basename(cmd)} ${args[0]} exited ${r.status}`);
292
- }
293
-
294
- /**
295
- * Put the user's own settings back into config.yaml after npm replaced it.
296
- *
297
- * npm replaces a package directory WHOLESALE on update -- measured with
298
- * `npm pack` and two installs into a scratch prefix: an edited
299
- * `max_tokens: 31337` came back as the shipped `16000`. `config.yaml` ships
300
- * inside the package (CONFIG_ARCHITECTURE.md locks it to one location for a
301
- * security reason that this problem does not touch), so without this the
302
- * update silently discards every value the user set.
303
- *
304
- * `config_update.py` owns every decision; this call owns none of them. It
305
- * runs on every launch and does nothing on almost all of them -- the module
306
- * imports no first-party code until it has decided there is a merge to do,
307
- * because `import config_schema` alone costs 294ms of pydantic and ruamel.
308
- *
309
- * THE STATUS IS DELIBERATELY UNCHECKED. A configuration-history feature must
310
- * not be able to stop the harness from starting; the module says so itself by
311
- * always exiting 0, and this is the other half of that promise.
312
- *
313
- * `firstRun` is the one fact Python cannot work out for itself: it is read
314
- * from the venv stamp BEFORE ensureRuntime() builds it. Without it, an
315
- * install that was already in use when this feature arrived would have its
316
- * edited config.yaml recorded as the pristine baseline, and those edits would
317
- * be lost at the next update instead of preserved by it.
318
- */
319
- function syncConfig(rt, firstRun) {
320
- try {
321
- spawnSync(rt.python, [CONFIG_UPDATE, ...(firstRun ? ['--first-run'] : [])], {
322
- stdio: 'inherit',
323
- cwd: ROOT,
324
- windowsHide: true,
325
- });
326
- } catch {
327
- // See above: never fatal.
328
- }
329
- }
330
-
331
- /**
332
- * Mirror config.yaml AFTER the session, so a /config write survives an update.
333
- *
334
- * This is the common upgrade order and the whole feature misses its own case
335
- * without it: change a setting, exit, `npm update` days later, launch. By
336
- * then npm has replaced the file, so the only copy of that change is the one
337
- * taken here. The next launch's mirror is too late.
338
- *
339
- * THIS USED TO BE FOUR LINES OF fs.copyFileSync HERE, and they were the one
340
- * writer not subject to the module's rule 1 ("the mirror is refreshed only
341
- * when the version still matches"). They copied whenever a `version` file
342
- * existed -- so a merge that FAILED, which deliberately leaves the version
343
- * and the mirror untouched so the next launch can retry, was followed at
344
- * session end by the newly shipped config.yaml being copied over the mirror.
345
- * The user's settings were then gone from every copy, permanently, and the
346
- * retry found nothing to restore. The state directory is also global while
347
- * this file's ROOT is not, so a checkout run overwrote an npm install's
348
- * mirror with the checkout's own config.yaml.
349
- *
350
- * So the decision lives in Python, where it is tested, and this spawns it.
351
- * An interpreter start at session EXIT costs nothing anybody is waiting for.
352
- */
353
- function mirrorConfig(rt) {
354
- try {
355
- spawnSync(rt.python, [CONFIG_UPDATE, '--mirror'], {
356
- stdio: 'inherit',
357
- cwd: ROOT,
358
- windowsHide: true,
359
- });
360
- } catch {
361
- // Never fatal, for syncConfig's reason.
362
- }
363
- }
364
-
365
- /** Walks up from cwd the way dotenv's find_dotenv(usecwd=True) now does. */
366
- function findEnvFile() {
367
- let dir = process.cwd();
368
- for (;;) {
369
- const candidate = path.join(dir, '.env');
370
- if (fs.existsSync(candidate)) return candidate;
371
- const parent = path.dirname(dir);
372
- if (parent === dir) return null;
373
- dir = parent;
374
- }
375
- }
376
-
377
- /**
378
- * The child's environment: inherit everything, then fill in ONLY what is
379
- * missing. Every branch here defers to a value the user already set.
380
- */
381
- function childEnv() {
382
- const env = { ...process.env };
383
- const cwd = process.cwd();
384
-
385
- // Credentials. cwd wins, because per-project keys are a real workflow; the
386
- // user-level file is the fallback that makes a globally-installed CLI
387
- // usable from directories that have no providers.json of their own.
388
- if (!env.AGENT_PROVIDERS_FILE && !fs.existsSync(path.join(cwd, 'providers.json'))) {
389
- const shared = path.join(CONFIG_HOME, 'providers.json');
390
- if (fs.existsSync(shared)) env.AGENT_PROVIDERS_FILE = shared;
391
- }
392
-
393
- // State. ONE decision drives BOTH variables -- a global database writing to
394
- // a local log is worse than either arrangement on its own.
395
- //
396
- // Why global at all: main.py sets project_path = os.getcwd(), and UserMemory
397
- // carries `scope` AND `project_path` (M12/D25) precisely so ONE database can
398
- // tell projects apart. Per-directory databases would put an accidental
399
- // scoping axis on top of that deliberate one -- `--thread <uuid>` would stop
400
- // resolving outside the directory it was created in, and a memory saved
401
- // scope="global" would be global only inside one folder.
402
- //
403
- // An existing ./app.db always wins, so running this launcher inside a
404
- // checkout keeps using the data already there instead of orphaning it.
405
- if (!env.APP_DB_PATH && !fs.existsSync(path.join(cwd, 'app.db'))) {
406
- env.APP_DB_PATH = path.join(CONFIG_HOME, 'app.db');
407
- if (!env.AGENT_LOG_FILE) env.AGENT_LOG_FILE = path.join(CONFIG_HOME, 'logs', 'app.log');
408
- }
409
-
410
- // AGENT_OUTPUT_DIR is deliberately untouched: research artifacts belong
411
- // beside the work that prompted them, and nothing reads them back -- the
412
- // report and claims live in the PipelineRunRecord row, not in output/.
413
- return env;
414
- }
415
-
416
- /**
417
- * One line about the config merge, WITHOUT starting Python.
418
- *
419
- * --venastine-doctor returns before ensureRuntime(), so there may be no
420
- * interpreter to ask. Everything here is a plain text file for that reason.
421
- */
422
- function configStateSummary() {
423
- try {
424
- // installs.json maps an install directory to its state subdirectory.
425
- // READ, never recomputed: config_update.py owns that naming, and two
426
- // languages agreeing about a hash by inspection would fail silently --
427
- // the mirror would be written where the merge does not look.
428
- const installs = JSON.parse(
429
- fs.readFileSync(path.join(CONFIG_STATE, 'installs.json'), 'utf8'));
430
- const dir = path.join(CONFIG_STATE, installs[fs.realpathSync(ROOT)]);
431
- const version = fs.readFileSync(path.join(dir, 'version'), 'utf8').trim();
432
- const record = path.join(dir, 'last-update.txt');
433
- const last = fs.existsSync(record)
434
- ? `, last merged ${fs.statSync(record).mtime.toISOString().slice(0, 10)}`
435
- : '';
436
- return `${dir} (tracking ${version}${last})`;
437
- } catch {
438
- return `${CONFIG_STATE} (not tracked yet; the next launch starts it)`;
439
- }
440
- }
441
-
442
- function doctor(python, rt) {
443
- const cwd = process.cwd();
444
- const env = childEnv();
445
- const localProviders = path.join(cwd, 'providers.json');
446
- const lines = [
447
- `venastine ${readPackageVersion()}`,
448
- ` package root : ${ROOT}`,
449
- ` node : ${process.version}`,
450
- ` python : ${python.version} (${python.executable})`,
451
- ` venv : ${rt.dir}`,
452
- ` venv ready : ${isReady(rt) ? 'yes' : 'no (first run will build it)'}`,
453
- ` cwd : ${cwd}`,
454
- ` providers.json: ${env.AGENT_PROVIDERS_FILE
455
- || (fs.existsSync(localProviders) ? localProviders : '(none found)')}`,
456
- ` .env : ${env.AGENT_ENV_FILE || findEnvFile() || '(none found)'}`,
457
- ` app.db : ${env.APP_DB_PATH || path.join(cwd, 'app.db')}`,
458
- ` log file : ${env.AGENT_LOG_FILE || path.join(cwd, 'logs', 'app.log')}`,
459
- ` output dir : ${env.AGENT_OUTPUT_DIR || path.join(cwd, 'output')}`,
460
- ` workspace : ${env.AGENT_WORKSPACE || path.join(cwd, 'workspace')}`,
461
- ` config.yaml : ${CONFIG_FILE}`,
462
- ` config state : ${configStateSummary()}`,
463
- ];
464
- process.stdout.write(lines.join('\n') + '\n');
465
- }
466
-
467
- function fail(message) {
468
- process.stderr.write(message.replace(/\n?$/, '\n'));
469
- process.exit(1);
470
- }
471
-
472
- async function main() {
473
- const argv = process.argv.slice(2);
474
-
475
- // Launcher-owned flags are PREFIXED because main.py takes a positional
476
- // `query`: a bare `venastine doctor` would be sent to the model as a
477
- // research question rather than reaching this file.
478
- const assumeYes = argv.includes('--venastine-yes');
479
- const wantDoctor = argv.includes('--venastine-doctor');
480
- const wantReinstall = argv.includes('--venastine-reinstall');
481
- const passthrough = argv.filter((a) => !a.startsWith('--venastine-'));
482
-
483
- const python = findPython();
484
- const rt = runtimePaths();
485
-
486
- // BEFORE ensureRuntime, which is what makes it an answer: "has this install
487
- // ever been launched?" is the only way to know whether the config.yaml in
488
- // front of us is pristine or already edited. See syncConfig().
489
- const firstRun = !isReady(rt);
490
-
491
- if (wantReinstall) {
492
- // The venv only. The config state in CONFIG_STATE is the user's own
493
- // settings history and has nothing to do with a broken environment --
494
- // removing it here would throw away the edits an update is about to need.
495
- fs.rmSync(rt.dir, { recursive: true, force: true });
496
- process.stdout.write(`Removed ${rt.dir}\n`);
497
- }
498
-
499
- if (wantDoctor) {
500
- doctor(python, rt);
501
- return;
502
- }
503
-
504
- await ensureRuntime(python, rt, { assumeYes });
505
- syncConfig(rt, firstRun);
506
-
507
- // Let the child own the terminal's interrupt. Without this, Ctrl+C kills
508
- // the launcher first and the harness loses its chance to shut down.
509
- process.on('SIGINT', () => {});
510
-
511
- // main.py BY PATH, so its directory becomes sys.path[0]: the harness relies
512
- // on the project root being importable (AGENTS.md, "the project root is on
513
- // sys.path"). stdio:'inherit' is what gives the Textual TUI a real terminal.
514
- const child = spawnSync(rt.python, [MAIN, ...passthrough], {
515
- stdio: 'inherit',
516
- cwd: process.cwd(),
517
- env: childEnv(),
518
- windowsHide: false,
519
- });
520
-
521
- mirrorConfig(rt);
522
-
523
- if (child.error) fail(`Could not start the harness: ${child.error.message}`);
524
- if (child.signal) process.exit(128 + (os.constants.signals[child.signal] || 0));
525
- process.exit(child.status ?? 1);
526
- }
527
-
528
- main().catch((e) => fail(e.stack || String(e)));
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bin/venastine.mjs -- the npm entry point (batch 35).
4
+ *
5
+ * npm delivers this project as a FOLDER OF SOURCE, not a binary. This file
6
+ * is the only thing npm can execute, so its whole job is to hand control to
7
+ * the Python that actually implements the harness:
8
+ *
9
+ * find a Python >= 3.11 -> make sure its dependencies exist
10
+ * -> spawn `python <root>/main.py` with the user's argv, cwd and stdio
11
+ *
12
+ * ZERO npm DEPENDENCIES, deliberately. Node stdlib only. The tarball is
13
+ * first-party source and nothing else, which is what lets
14
+ * THIRD_PARTY_NOTICES.md say the npm channel adds no licence surface. Do not
15
+ * add a dependency here without changing that file too.
16
+ *
17
+ * WHAT THIS FILE MUST NEVER DO, and why each one is a real bug and not a
18
+ * style preference:
19
+ *
20
+ * * Never set PYTHONPATH. tools/isolation.py builds its child's PYTHONPATH
21
+ * from the PARENT's resolved sys.path -- "handing the child the paths the
22
+ * parent actually resolved is deterministic". A value injected here would
23
+ * be inherited into that computation and poison it.
24
+ * * Never set AGENT_WORKSPACE. WORKSPACE_DIR is a PERMISSION BOUNDARY, not
25
+ * a storage location: file_ops auto-approves writes inside it and demands
26
+ * approval outside. Redirecting it to a shared home directory would
27
+ * silently auto-approve writes there from every project.
28
+ * * Never install without consent. See ensureRuntime().
29
+ */
30
+
31
+ import { spawnSync } from 'node:child_process';
32
+ import crypto from 'node:crypto';
33
+ import fs from 'node:fs';
34
+ import os from 'node:os';
35
+ import path from 'node:path';
36
+ import readline from 'node:readline';
37
+ import { fileURLToPath } from 'node:url';
38
+
39
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
40
+ const ROOT = path.dirname(HERE);
41
+ const REQUIREMENTS = path.join(ROOT, 'requirements.txt');
42
+ const MAIN = path.join(ROOT, 'main.py');
43
+ const CONFIG_FILE = path.join(ROOT, 'config.yaml');
44
+ const CONFIG_UPDATE = path.join(ROOT, 'config_update.py');
45
+
46
+ /**
47
+ * ~/.config/venastine ON EVERY PLATFORM, Windows included.
48
+ *
49
+ * Not %APPDATA%, however Node-idiomatic that would be. The Python half of
50
+ * this directory is already fixed: core/config_loader.py, mcp_client/config.py
51
+ * and core/workspace_trust.py all resolve their user tier with
52
+ * os.path.expanduser("~/.config/venastine"). Splitting one config directory
53
+ * across two locations by platform is the bug this constant exists to avoid.
54
+ */
55
+ const CONFIG_HOME = path.join(os.homedir(), '.config', 'venastine');
56
+
57
+ /**
58
+ * Where config_update.py keeps the pristine copy and the user's mirror.
59
+ *
60
+ * Spelled in two languages, so a docs-consistency test holds this against
61
+ * `config_update.STATE_DIRNAME`. Node owns only the two cheap halves -- the
62
+ * post-session copy below, and the doctor lines -- because everything else
63
+ * needs a YAML parser and this file has ZERO dependencies by design.
64
+ */
65
+ const CONFIG_STATE = path.join(CONFIG_HOME, 'config-state');
66
+
67
+ const MIN_PYTHON = [3, 11];
68
+
69
+ /** Python floor, in the terms the project already states it in (#144). */
70
+ const PYTHON_FLOOR_MESSAGE =
71
+ `Venastine needs Python ${MIN_PYTHON.join('.')} or newer.\n` +
72
+ '\n' +
73
+ 'mcp_client/client.py uses asyncio.timeout (3.11+) and 27 sites use runtime\n' +
74
+ '`X | Y` annotations (3.10+). On an older interpreter the harness installs\n' +
75
+ 'and then fails from inside the MCP connect path, which is why this refuses\n' +
76
+ 'here instead.\n' +
77
+ '\n' +
78
+ 'Install Python 3.11+, or point VENASTINE_PYTHON at one:\n' +
79
+ ' VENASTINE_PYTHON=/path/to/python3.12 venastine';
80
+
81
+ function readPackageVersion() {
82
+ try {
83
+ return JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
84
+ } catch {
85
+ return '0.0.0';
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Candidate interpreters, best first. The loop takes the first that satisfies
91
+ * the floor, so an old `python3` earlier in the list simply falls through to a
92
+ * newer explicit one rather than failing the launch.
93
+ */
94
+ function pythonCandidates() {
95
+ if (process.env.VENASTINE_PYTHON) {
96
+ return [{ cmd: process.env.VENASTINE_PYTHON, args: [], explicit: true }];
97
+ }
98
+ if (process.platform === 'win32') {
99
+ // `py -3` is the launcher's newest install; the explicit ones are the
100
+ // fallback for machines without the py launcher on PATH.
101
+ return [
102
+ { cmd: 'py', args: ['-3'] },
103
+ { cmd: 'python', args: [] },
104
+ { cmd: 'python3', args: [] },
105
+ { cmd: 'py', args: ['-3.13'] },
106
+ { cmd: 'py', args: ['-3.12'] },
107
+ { cmd: 'py', args: ['-3.11'] },
108
+ ];
109
+ }
110
+ return [
111
+ { cmd: 'python3', args: [] },
112
+ { cmd: 'python3.13', args: [] },
113
+ { cmd: 'python3.12', args: [] },
114
+ { cmd: 'python3.11', args: [] },
115
+ { cmd: 'python', args: [] },
116
+ ];
117
+ }
118
+
119
+ const PROBE = 'import sys; print("%d.%d" % sys.version_info[:2]); print(sys.executable)';
120
+
121
+ function probe(candidate) {
122
+ const r = spawnSync(candidate.cmd, [...candidate.args, '-c', PROBE], {
123
+ encoding: 'utf8',
124
+ // Windows resolves `py`/`python` through PATHEXT, which needs the shell
125
+ // off but the extension search on -- spawnSync does that for us. What it
126
+ // does NOT do is survive a missing binary, hence the status check below.
127
+ windowsHide: true,
128
+ });
129
+ if (r.status !== 0 || !r.stdout) return null;
130
+ const [version, executable] = r.stdout.trim().split(/\r?\n/);
131
+ if (!version || !executable) return null;
132
+ const [major, minor] = version.split('.').map(Number);
133
+ return { ...candidate, version, executable, major, minor };
134
+ }
135
+
136
+ function findPython() {
137
+ const rejected = [];
138
+ for (const candidate of pythonCandidates()) {
139
+ const found = probe(candidate);
140
+ if (!found) continue;
141
+ if (found.major > MIN_PYTHON[0] ||
142
+ (found.major === MIN_PYTHON[0] && found.minor >= MIN_PYTHON[1])) {
143
+ return found;
144
+ }
145
+ rejected.push(`${found.executable} (${found.version})`);
146
+ }
147
+ const detail = rejected.length
148
+ ? `\n\nFound, but too old: ${rejected.join(', ')}`
149
+ : '\n\nNo Python interpreter was found on PATH.';
150
+ fail(PYTHON_FLOOR_MESSAGE + detail);
151
+ }
152
+
153
+ function requirementsHash() {
154
+ return crypto.createHash('sha256')
155
+ .update(fs.readFileSync(REQUIREMENTS))
156
+ .digest('hex')
157
+ .slice(0, 12);
158
+ }
159
+
160
+ /**
161
+ * The runtime directory is keyed by VERSION AND requirements hash together.
162
+ *
163
+ * Either alone is not enough: a version bump with unchanged pins should reuse
164
+ * the environment, and an edited pin within one version must NOT. Keying on
165
+ * both means every distinct dependency set gets a clean venv instead of a
166
+ * half-migrated one, and switching back to an older install finds its own
167
+ * environment still intact.
168
+ */
169
+ function runtimePaths() {
170
+ const dir = path.join(CONFIG_HOME, 'runtime', `${readPackageVersion()}-${requirementsHash()}`);
171
+ return {
172
+ dir,
173
+ python: process.platform === 'win32'
174
+ ? path.join(dir, 'Scripts', 'python.exe')
175
+ : path.join(dir, 'bin', 'python'),
176
+ // Written LAST, and it -- not the directory -- is what "ready" means. A
177
+ // venv whose pip install died half way exists on disk and would otherwise
178
+ // read as installed, then fail on a missing import at the first model call.
179
+ stamp: path.join(dir, 'venastine-runtime.json'),
180
+ };
181
+ }
182
+
183
+ function isReady(rt) {
184
+ return fs.existsSync(rt.stamp) && fs.existsSync(rt.python);
185
+ }
186
+
187
+ // Non-comment lines in requirements.txt. NOT a count of pins, which is what
188
+ // it was called until batch 140: some lines are ranges (a floor and a
189
+ // ceiling, like `rich`'s), so the screen that said "N pinned packages" was
190
+ // promising something the file does not say. The exact set is in the file
191
+ // the screen names, which is what makes the count enough. (This comment
192
+ // said "2 of the 18" until batch 208, by when it was 4 of 20: a count in
193
+ // prose beside the code that computes it is the copy that drifts.)
194
+ function countRequirements() {
195
+ return fs.readFileSync(REQUIREMENTS, 'utf8')
196
+ .split(/\r?\n/)
197
+ .filter((line) => line.trim() && !line.trim().startsWith('#'))
198
+ .length;
199
+ }
200
+
201
+ // ROADMAP_v3 §88 (A83). The harness runs under this process with the console
202
+ // inherited, and it is the terminal's one reader from then on, so this
203
+ // process stops reading in so many words: rl.close() only ASKS libuv to stop,
204
+ // and on Windows its console reader is a thread whose read in flight cannot
205
+ // be cancelled. pause() is the same request made of the stream itself, and
206
+ // unref() lets nothing about stdin keep this process alive. Measured in a
207
+ // console of its own, five keys typed at the child after the consent all
208
+ // reached it, before this and after it, three runs each: the old shape
209
+ // lost nothing there, and this one loses nothing either.
210
+ function ask(question) {
211
+ return new Promise((resolve) => {
212
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
213
+ rl.question(question, (answer) => {
214
+ rl.close();
215
+ process.stdin.pause();
216
+ if (typeof process.stdin.unref === 'function') process.stdin.unref();
217
+ resolve(/^y(es)?$/i.test(answer.trim()));
218
+ });
219
+ });
220
+ }
221
+
222
+ /**
223
+ * Build the Python environment, only ever with the user's say-so.
224
+ *
225
+ * The consent prompt is not ceremony. This is the one action the launcher
226
+ * takes on its own initiative -- it runs a network install of everything in
227
+ * requirements.txt -- and the project's own rule for that case is D17/D31:
228
+ *
229
+ * NO COUNT IN THIS SENTENCE, deliberately (batch 140). It said "17
230
+ * pinned distributions" and the file had 22 installable lines when that was
231
+ * measured, 18 now that batch 136 moved the test packages out. The screen
232
+ * below prints the live number; prose that restates a computed value is a
233
+ * second copy of it, and this is the copy that drifted.
234
+ * show what will run and confirm it. That is also why the bootstrap is here
235
+ * and not in an npm `postinstall` hook, where it would run unannounced and be
236
+ * skipped entirely under `--ignore-scripts`.
237
+ *
238
+ * NOT A TTY AND NO --venastine-yes => REFUSE AND PRINT THE COMMAND. A CI job
239
+ * or a piped invocation must not be able to trigger an unattended install
240
+ * just by being unable to answer.
241
+ */
242
+ async function ensureRuntime(python, rt, { assumeYes }) {
243
+ if (isReady(rt)) return;
244
+
245
+ const summary =
246
+ 'Venastine needs a Python environment (first run).\n' +
247
+ ` python : ${python.version} (${python.executable})\n` +
248
+ ` venv : ${rt.dir}\n` +
249
+ ` install : ${countRequirements()} packages from requirements.txt\n`;
250
+
251
+ if (!assumeYes) {
252
+ if (!process.stdin.isTTY) {
253
+ fail(
254
+ summary +
255
+ '\nRefusing to install unattended (no terminal to ask in).\n' +
256
+ 'Re-run interactively, pass --venastine-yes, or build it yourself:\n' +
257
+ ` ${python.executable} -m venv "${rt.dir}"\n` +
258
+ ` "${rt.python}" -m pip install -r "${REQUIREMENTS}"`
259
+ );
260
+ }
261
+ process.stdout.write(summary);
262
+ const ok = await ask('Proceed? [y/N] ');
263
+ if (!ok) fail('Cancelled. Nothing was installed.');
264
+ } else {
265
+ process.stdout.write(summary);
266
+ }
267
+
268
+ try {
269
+ run(python.executable, ['-m', 'venv', rt.dir]);
270
+ run(rt.python, ['-m', 'pip', 'install', '--disable-pip-version-check',
271
+ '-r', REQUIREMENTS]);
272
+ } catch (e) {
273
+ // Leave nothing half-built behind: the next run must start clean rather
274
+ // than inherit a venv that is missing an unknown subset of its packages.
275
+ fs.rmSync(rt.dir, { recursive: true, force: true });
276
+ fail(`Environment setup failed: ${e.message}`);
277
+ }
278
+
279
+ fs.writeFileSync(rt.stamp, JSON.stringify({
280
+ version: readPackageVersion(),
281
+ requirementsHash: requirementsHash(),
282
+ python: python.executable,
283
+ pythonVersion: python.version,
284
+ createdAt: new Date().toISOString(),
285
+ }, null, 2));
286
+ }
287
+
288
+ function run(cmd, args) {
289
+ const r = spawnSync(cmd, args, { stdio: 'inherit', windowsHide: true });
290
+ if (r.error) throw r.error;
291
+ if (r.status !== 0) throw new Error(`${path.basename(cmd)} ${args[0]} exited ${r.status}`);
292
+ }
293
+
294
+ /**
295
+ * Put the user's own settings back into config.yaml after npm replaced it.
296
+ *
297
+ * npm replaces a package directory WHOLESALE on update -- measured with
298
+ * `npm pack` and two installs into a scratch prefix: an edited
299
+ * `max_tokens: 31337` came back as the shipped `16000`. `config.yaml` ships
300
+ * inside the package (CONFIG_ARCHITECTURE.md locks it to one location for a
301
+ * security reason that this problem does not touch), so without this the
302
+ * update silently discards every value the user set.
303
+ *
304
+ * `config_update.py` owns every decision; this call owns none of them. It
305
+ * runs on every launch and does nothing on almost all of them -- the module
306
+ * imports no first-party code until it has decided there is a merge to do,
307
+ * because `import config_schema` alone costs 294ms of pydantic and ruamel.
308
+ *
309
+ * THE STATUS IS DELIBERATELY UNCHECKED. A configuration-history feature must
310
+ * not be able to stop the harness from starting; the module says so itself by
311
+ * always exiting 0, and this is the other half of that promise.
312
+ *
313
+ * `firstRun` is the one fact Python cannot work out for itself: it is read
314
+ * from the venv stamp BEFORE ensureRuntime() builds it. Without it, an
315
+ * install that was already in use when this feature arrived would have its
316
+ * edited config.yaml recorded as the pristine baseline, and those edits would
317
+ * be lost at the next update instead of preserved by it.
318
+ */
319
+ function syncConfig(rt, firstRun) {
320
+ try {
321
+ spawnSync(rt.python, [CONFIG_UPDATE, ...(firstRun ? ['--first-run'] : [])], {
322
+ stdio: 'inherit',
323
+ cwd: ROOT,
324
+ windowsHide: true,
325
+ });
326
+ } catch {
327
+ // See above: never fatal.
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Mirror config.yaml AFTER the session, so a /config write survives an update.
333
+ *
334
+ * This is the common upgrade order and the whole feature misses its own case
335
+ * without it: change a setting, exit, `npm update` days later, launch. By
336
+ * then npm has replaced the file, so the only copy of that change is the one
337
+ * taken here. The next launch's mirror is too late.
338
+ *
339
+ * THIS USED TO BE FOUR LINES OF fs.copyFileSync HERE, and they were the one
340
+ * writer not subject to the module's rule 1 ("the mirror is refreshed only
341
+ * when the version still matches"). They copied whenever a `version` file
342
+ * existed -- so a merge that FAILED, which deliberately leaves the version
343
+ * and the mirror untouched so the next launch can retry, was followed at
344
+ * session end by the newly shipped config.yaml being copied over the mirror.
345
+ * The user's settings were then gone from every copy, permanently, and the
346
+ * retry found nothing to restore. The state directory is also global while
347
+ * this file's ROOT is not, so a checkout run overwrote an npm install's
348
+ * mirror with the checkout's own config.yaml.
349
+ *
350
+ * So the decision lives in Python, where it is tested, and this spawns it.
351
+ * An interpreter start at session EXIT costs nothing anybody is waiting for.
352
+ */
353
+ function mirrorConfig(rt) {
354
+ try {
355
+ spawnSync(rt.python, [CONFIG_UPDATE, '--mirror'], {
356
+ stdio: 'inherit',
357
+ cwd: ROOT,
358
+ windowsHide: true,
359
+ });
360
+ } catch {
361
+ // Never fatal, for syncConfig's reason.
362
+ }
363
+ }
364
+
365
+ /** Walks up from cwd the way dotenv's find_dotenv(usecwd=True) now does. */
366
+ function findEnvFile() {
367
+ let dir = process.cwd();
368
+ for (;;) {
369
+ const candidate = path.join(dir, '.env');
370
+ if (fs.existsSync(candidate)) return candidate;
371
+ const parent = path.dirname(dir);
372
+ if (parent === dir) return null;
373
+ dir = parent;
374
+ }
375
+ }
376
+
377
+ /**
378
+ * The child's environment: inherit everything, then fill in ONLY what is
379
+ * missing. Every branch here defers to a value the user already set.
380
+ */
381
+ function childEnv() {
382
+ const env = { ...process.env };
383
+ const cwd = process.cwd();
384
+
385
+ // Credentials. cwd wins, because per-project keys are a real workflow; the
386
+ // user-level file is the fallback that makes a globally-installed CLI
387
+ // usable from directories that have no providers.json of their own.
388
+ if (!env.AGENT_PROVIDERS_FILE && !fs.existsSync(path.join(cwd, 'providers.json'))) {
389
+ const shared = path.join(CONFIG_HOME, 'providers.json');
390
+ if (fs.existsSync(shared)) env.AGENT_PROVIDERS_FILE = shared;
391
+ }
392
+
393
+ // State. ONE decision drives BOTH variables -- a global database writing to
394
+ // a local log is worse than either arrangement on its own.
395
+ //
396
+ // Why global at all: main.py sets project_path = os.getcwd(), and UserMemory
397
+ // carries `scope` AND `project_path` (M12/D25) precisely so ONE database can
398
+ // tell projects apart. Per-directory databases would put an accidental
399
+ // scoping axis on top of that deliberate one -- `--thread <uuid>` would stop
400
+ // resolving outside the directory it was created in, and a memory saved
401
+ // scope="global" would be global only inside one folder.
402
+ //
403
+ // An existing ./app.db always wins, so running this launcher inside a
404
+ // checkout keeps using the data already there instead of orphaning it.
405
+ if (!env.APP_DB_PATH && !fs.existsSync(path.join(cwd, 'app.db'))) {
406
+ env.APP_DB_PATH = path.join(CONFIG_HOME, 'app.db');
407
+ if (!env.AGENT_LOG_FILE) env.AGENT_LOG_FILE = path.join(CONFIG_HOME, 'logs', 'app.log');
408
+ }
409
+
410
+ // AGENT_OUTPUT_DIR is deliberately untouched: research artifacts belong
411
+ // beside the work that prompted them, and nothing reads them back -- the
412
+ // report and claims live in the PipelineRunRecord row, not in output/.
413
+ return env;
414
+ }
415
+
416
+ /**
417
+ * One line about the config merge, WITHOUT starting Python.
418
+ *
419
+ * --venastine-doctor returns before ensureRuntime(), so there may be no
420
+ * interpreter to ask. Everything here is a plain text file for that reason.
421
+ */
422
+ function configStateSummary() {
423
+ try {
424
+ // installs.json maps an install directory to its state subdirectory.
425
+ // READ, never recomputed: config_update.py owns that naming, and two
426
+ // languages agreeing about a hash by inspection would fail silently --
427
+ // the mirror would be written where the merge does not look.
428
+ const installs = JSON.parse(
429
+ fs.readFileSync(path.join(CONFIG_STATE, 'installs.json'), 'utf8'));
430
+ const dir = path.join(CONFIG_STATE, installs[fs.realpathSync(ROOT)]);
431
+ const version = fs.readFileSync(path.join(dir, 'version'), 'utf8').trim();
432
+ const record = path.join(dir, 'last-update.txt');
433
+ const last = fs.existsSync(record)
434
+ ? `, last merged ${fs.statSync(record).mtime.toISOString().slice(0, 10)}`
435
+ : '';
436
+ return `${dir} (tracking ${version}${last})`;
437
+ } catch {
438
+ return `${CONFIG_STATE} (not tracked yet; the next launch starts it)`;
439
+ }
440
+ }
441
+
442
+ function doctor(python, rt) {
443
+ const cwd = process.cwd();
444
+ const env = childEnv();
445
+ const localProviders = path.join(cwd, 'providers.json');
446
+ const lines = [
447
+ `venastine ${readPackageVersion()}`,
448
+ ` package root : ${ROOT}`,
449
+ ` node : ${process.version}`,
450
+ ` python : ${python.version} (${python.executable})`,
451
+ ` venv : ${rt.dir}`,
452
+ ` venv ready : ${isReady(rt) ? 'yes' : 'no (first run will build it)'}`,
453
+ ` cwd : ${cwd}`,
454
+ ` providers.json: ${env.AGENT_PROVIDERS_FILE
455
+ || (fs.existsSync(localProviders) ? localProviders : '(none found)')}`,
456
+ ` .env : ${env.AGENT_ENV_FILE || findEnvFile() || '(none found)'}`,
457
+ ` app.db : ${env.APP_DB_PATH || path.join(cwd, 'app.db')}`,
458
+ ` log file : ${env.AGENT_LOG_FILE || path.join(cwd, 'logs', 'app.log')}`,
459
+ ` output dir : ${env.AGENT_OUTPUT_DIR || path.join(cwd, 'output')}`,
460
+ ` workspace : ${env.AGENT_WORKSPACE || path.join(cwd, 'workspace')}`,
461
+ ` config.yaml : ${CONFIG_FILE}`,
462
+ ` config state : ${configStateSummary()}`,
463
+ ];
464
+ process.stdout.write(lines.join('\n') + '\n');
465
+ }
466
+
467
+ function fail(message) {
468
+ process.stderr.write(message.replace(/\n?$/, '\n'));
469
+ process.exit(1);
470
+ }
471
+
472
+ async function main() {
473
+ const argv = process.argv.slice(2);
474
+
475
+ // Launcher-owned flags are PREFIXED because main.py takes a positional
476
+ // `query`: a bare `venastine doctor` would be sent to the model as a
477
+ // research question rather than reaching this file.
478
+ const assumeYes = argv.includes('--venastine-yes');
479
+ const wantDoctor = argv.includes('--venastine-doctor');
480
+ const wantReinstall = argv.includes('--venastine-reinstall');
481
+ const passthrough = argv.filter((a) => !a.startsWith('--venastine-'));
482
+
483
+ const python = findPython();
484
+ const rt = runtimePaths();
485
+
486
+ // BEFORE ensureRuntime, which is what makes it an answer: "has this install
487
+ // ever been launched?" is the only way to know whether the config.yaml in
488
+ // front of us is pristine or already edited. See syncConfig().
489
+ const firstRun = !isReady(rt);
490
+
491
+ if (wantReinstall) {
492
+ // The venv only. The config state in CONFIG_STATE is the user's own
493
+ // settings history and has nothing to do with a broken environment --
494
+ // removing it here would throw away the edits an update is about to need.
495
+ fs.rmSync(rt.dir, { recursive: true, force: true });
496
+ process.stdout.write(`Removed ${rt.dir}\n`);
497
+ }
498
+
499
+ if (wantDoctor) {
500
+ doctor(python, rt);
501
+ return;
502
+ }
503
+
504
+ await ensureRuntime(python, rt, { assumeYes });
505
+ syncConfig(rt, firstRun);
506
+
507
+ // Let the child own the terminal's interrupt. Without this, Ctrl+C kills
508
+ // the launcher first and the harness loses its chance to shut down.
509
+ process.on('SIGINT', () => {});
510
+
511
+ // main.py BY PATH, so its directory becomes sys.path[0]: the harness relies
512
+ // on the project root being importable (AGENTS.md, "the project root is on
513
+ // sys.path"). stdio:'inherit' is what gives the Textual TUI a real terminal.
514
+ const child = spawnSync(rt.python, [MAIN, ...passthrough], {
515
+ stdio: 'inherit',
516
+ cwd: process.cwd(),
517
+ env: childEnv(),
518
+ windowsHide: false,
519
+ });
520
+
521
+ mirrorConfig(rt);
522
+
523
+ if (child.error) fail(`Could not start the harness: ${child.error.message}`);
524
+ if (child.signal) process.exit(128 + (os.constants.signals[child.signal] || 0));
525
+ process.exit(child.status ?? 1);
526
+ }
527
+
528
+ main().catch((e) => fail(e.stack || String(e)));