@neuralbridge/bio-pipelines-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ NeuralBridge MCP servers
2
+ Copyright 2026 NeuralBridge — https://neuralbridge.ru
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # @neuralbridge/bio-pipelines-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP server for bioinformatics pipelines written for Nextflow, WDL (run with miniwdl) and Snakemake. It is the server
4
+ behind the `nb-bio-pipelines` power of NeuralBridge IDE, and works with any MCP client over stdio.
5
+
6
+ ## Tools
7
+
8
+ | Tool | What it does | Changes |
9
+ |---|---|---|
10
+ | `bio_detect` | Which of `nextflow`, `miniwdl`, `snakemake` are installed and their versions; with `dir`, lists `main.nf`, `nextflow.config`, `.wdl` files and Snakefiles | nothing |
11
+ | `bio_lint` | `nextflow lint -o json`, `miniwdl check`, `snakemake --lint json`; findings as `file:line:column: message` | nothing (Snakemake evaluates the Snakefile) |
12
+ | `bio_plan` | Dry run: Nextflow `run -preview -with-dag` (processes of the DAG), Snakemake `--dry-run` (jobs per rule), miniwdl `check` + required inputs + `run --json`; saves the exact command and file hashes as a plan | tool metadata (`.nextflow`, `.snakemake`) in the launch directory |
13
+ | `bio_run` | Starts exactly the planned command in the background, once, and returns a run id | **runs the pipeline**: computes, writes results, may overwrite outputs |
14
+ | `bio_run_status` | Running or finished, exit code, duration, progress, last 100 lines of the log | nothing |
15
+ | `bio_run_stop_plan` | Shows what is running and for how long; saves a stop plan | a plan file in the data folder |
16
+ | `bio_run_stop_apply` | Sends SIGTERM to the planned run, once | **stops the run** |
17
+ | `bio_runs` | Runs started through this server, newest first | nothing |
18
+
19
+ Read-only are only `bio_detect`, `bio_run_status` and `bio_runs`. `bio_lint` is not marked read-only because
20
+ `snakemake --lint` executes the Snakefile, which is Python code; `bio_plan` evaluates the pipeline code of all three tools.
21
+ `bio_run` and `bio_run_stop_apply` are marked destructive.
22
+
23
+ ### Plan, then run
24
+
25
+ `bio_run` takes only a plan id. Before starting, it checks that the program still resolves to the same binary, that the
26
+ launch directory exists and that the pipeline file, the `nextflow.config` files (pipeline and launch directory), the
27
+ params file, the Snakemake config and profile files and the WDL inputs file have the same sha256 as at planning time.
28
+ Then it runs exactly the saved arguments and removes the plan. Plans expire after 24 hours.
29
+
30
+ The run is a detached process: its stdout and stderr go to `runs/<id>.log`, the PID and start time to `runs/<id>.json`.
31
+ While the server is alive, it records the exit code when the process ends. If the server was restarted during a run,
32
+ `bio_run_status` checks the PID (on Linux also its command line) and guesses the outcome from the end of the log. Records
33
+ of finished runs, their logs and Nextflow reports are removed after 7 days.
34
+
35
+ | Tool | Command started by `bio_run` |
36
+ |---|---|
37
+ | Nextflow | `nextflow run <main.nf> [-params-file F] [-profile P] [-work-dir D] [-resume] -with-report <data>/runs/<id>-report.html` |
38
+ | Snakemake | `snakemake [targets] --snakefile S --directory D --nocolor --cores N [--configfile …] [--profile P] [--software-deployment-method …]` |
39
+ | miniwdl | `miniwdl run <file.wdl> [-i inputs.json] [--task T] --dir <outputDir> --no-color` (a timestamp-named run directory is created under it) |
40
+
41
+ Stopping sends SIGTERM to the program itself; Nextflow, Snakemake and miniwdl then cancel their running tasks and exit.
42
+
43
+ ## Local pipelines only, and what the tools download
44
+
45
+ The server installs and downloads nothing. It starts only programs already installed, found on `PATH` or through
46
+ `NB_BIO_NEXTFLOW`, `NB_BIO_MINIWDL`, `NB_BIO_SNAKEMAKE`.
47
+
48
+ - **Pipelines must be local.** `pipeline` is an absolute path to `main.nf` (or the directory that contains it), a
49
+ Snakefile (or its project directory with `Snakefile` / `workflow/Snakefile`), or a `.wdl` file. Names like
50
+ `owner/repo`, which Nextflow would download from a git hosting service, and URLs are not accepted. Clone the pipeline
51
+ first and point to the local copy.
52
+ - **Nextflow** downloads plugins and, on the very first start of its launcher, its own runtime into `~/.nextflow`. With
53
+ `offline: true` the server sets `NXF_OFFLINE=true`: Nextflow downloads no pipelines and no plugins (since 24.04), so the
54
+ plugins must already be installed. Tasks run with the executor configured in `nextflow.config`.
55
+ - **Container images and Conda environments** used by the processes, rules or tasks are pulled or created by Nextflow,
56
+ Snakemake (only with `softwareDeployment`) and the container runtime of miniwdl when the run starts. miniwdl also
57
+ downloads input files given as URIs. The plan says so in its answer.
58
+ - Snakemake software deployment (`--software-deployment-method conda|apptainer|env-modules`) is off unless requested.
59
+
60
+ ## Environment
61
+
62
+ | Variable | Meaning |
63
+ |---|---|
64
+ | `NB_BIO_NEXTFLOW`, `NB_BIO_MINIWDL`, `NB_BIO_SNAKEMAKE` | Path of the program; default — the name on `PATH`. Each program is optional |
65
+ | `PLUGIN_DATA` | Data folder for plans and runs; default — `nb-bio-pipelines` in the system temp folder. Mode 0700, files 0600 |
66
+
67
+ Programs run without a shell, with closed stdin, `NO_COLOR=1` and a time limit (lint 5 minutes, plan 30 minutes, the
68
+ run itself has none). Nextflow also gets `NXF_ANSI_LOG=false`, `NXF_DISABLE_CHECK_LATEST=true` (no check for a newer
69
+ version) and `NXF_AGENT_MODE=false` (keeps the normal log format the progress parser reads). Credentials stay where the
70
+ tools read them (their config files and the environment of the server). Answers mask passwords in URLs (`user:***@`),
71
+ `password=` / `token:` pairs and bearer tokens; params files are shown by key names only. Logs of the server go to
72
+ stderr.
73
+
74
+ ## Versions
75
+
76
+ - `nextflow lint` needs Nextflow 25.04 or newer; with older versions `bio_lint` skips Nextflow files with a note.
77
+ `-preview` needs Nextflow 22.10 or newer.
78
+ - `softwareDeployment` needs Snakemake 8 or newer. Dry-run job statistics are read from the `Job stats:` table.
79
+ - miniwdl: `check`, `input-template` and `run --json` of current releases (1.x).
80
+
81
+ ## Run
82
+
83
+ ```bash
84
+ npx -y @neuralbridge/bio-pipelines-mcp@1.0.0
85
+ ```
86
+
87
+ Requires Node.js 20+.
88
+
89
+ ## Develop
90
+
91
+ ```bash
92
+ npm install
93
+ npm test # build + unit and end-to-end tests with fake nextflow, miniwdl and snakemake programs
94
+ ```
95
+
96
+ ## License
97
+
98
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,23 @@
1
+ // Copyright (c) NeuralBridge. Licensed under the Apache License, Version 2.0. See LICENSE.
2
+ // Состояние сервера на время его жизни: окружение, кэш найденных программ и исход прогонов, запущенных этим
3
+ // процессом сервера (код выхода известен сразу, до записи на диск). Используют все обработчики.
4
+ import { PROGRAMS, resolveProgram } from './runner.js';
5
+ export function createContext(env) {
6
+ return { env, programs: {}, exits: new Map(), children: new Map() };
7
+ }
8
+ /** Программа или `undefined`; неудачный поиск не кэшируется — пользователь может поставить программу без перезапуска. */
9
+ export async function findProgram(ctx, kind) {
10
+ ctx.programs[kind] ??= resolveProgram(kind, ctx.env);
11
+ const program = await ctx.programs[kind];
12
+ if (!program) {
13
+ delete ctx.programs[kind];
14
+ }
15
+ return program;
16
+ }
17
+ export async function programOf(ctx, kind) {
18
+ const program = await findProgram(ctx, kind);
19
+ if (!program) {
20
+ throw new Error(PROGRAMS[kind].notFound);
21
+ }
22
+ return program;
23
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // Copyright (c) NeuralBridge. Licensed under the Apache License, Version 2.0. See LICENSE.
3
+ // Точка входа пакета `@neuralbridge/bio-pipelines-mcp`: сервер `server.ts` на транспорте stdio. Логи — только в
4
+ // stderr: stdout занят протоколом.
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { createServer } from './server.js';
7
+ const server = createServer();
8
+ await server.connect(new StdioServerTransport());
9
+ process.stderr.write('nb-bio-pipelines MCP server ready\n');
@@ -0,0 +1,100 @@
1
+ // Copyright (c) NeuralBridge. Licensed under the Apache License, Version 2.0. See LICENSE.
2
+ // Обработчики `bio_detect` и `bio_lint`: какие программы установлены, какие пайплайны лежат в каталоге, и статическая
3
+ // проверка `nextflow lint`, `miniwdl check`, `snakemake --lint`. Регистрация в MCP — `server.ts`.
4
+ import { promises as fs } from 'node:fs';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { findProgram } from './context.js';
7
+ import { parseMiniwdlCheck, parseNextflowLint, parseSnakemakeLint } from './parse.js';
8
+ import { existingPath, findPipelineFiles, pipelineOf } from './paths.js';
9
+ import { compareVersions, failure, MINUTE, PROGRAM_KINDS, PROGRAMS, programEnv, run } from './runner.js';
10
+ /** `nextflow lint` появился в Nextflow 25.04. */
11
+ export const NEXTFLOW_LINT_SINCE = '25.04.0';
12
+ const LINT_TIMEOUT = 5 * MINUTE;
13
+ const MAX_WDL = 20;
14
+ const MAX_SNAKEFILES = 5;
15
+ export async function detect(ctx, args) {
16
+ const lines = [];
17
+ for (const kind of PROGRAM_KINDS) {
18
+ const program = await findProgram(ctx, kind);
19
+ lines.push(program ? `${kind} ${program.version} (${program.path})` : `${kind}: not found. ${PROGRAMS[kind].notFound}`);
20
+ }
21
+ if (args.dir) {
22
+ const root = await existingPath(args.dir, '"dir"', 'dir');
23
+ const found = await findPipelineFiles(root);
24
+ const list = (title, files) => files.length ? [`${title}:`, ...files.map(f => ` ${f}`)] : [];
25
+ const files = [...list('Nextflow (main.nf, nextflow.config)', found.nextflow), ...list('WDL', found.wdl), ...list('Snakemake', found.snakemake)];
26
+ lines.push('', files.length ? `Pipelines under ${root}:\n${files.join('\n')}` : `No main.nf, nextflow.config, .wdl or Snakefile under ${root}.`);
27
+ }
28
+ return lines.join('\n');
29
+ }
30
+ /** Что проверять: файл — по имени; папка — все найденные пайплайны (Nextflow — папкой целиком). */
31
+ async function lintTargets(path, only) {
32
+ const stat = await fs.stat(path);
33
+ const targets = [];
34
+ if (stat.isFile()) {
35
+ const name = basename(path);
36
+ const kind = /\.(nf|config)$/.test(name) ? 'nextflow' : name.endsWith('.wdl') ? 'miniwdl' : /^[Ss]nakefile$|\.smk$/.test(name) ? 'snakemake' : undefined;
37
+ if (!kind) {
38
+ throw new Error(`Cannot tell the pipeline language of ${path}: expected .nf, .config, .wdl, Snakefile or .smk.`);
39
+ }
40
+ targets.push({ kind, path, cwd: dirname(path) });
41
+ }
42
+ else {
43
+ const found = await findPipelineFiles(path);
44
+ if (found.nextflow.length) {
45
+ targets.push({ kind: 'nextflow', path, cwd: path });
46
+ }
47
+ for (const file of found.wdl.slice(0, MAX_WDL)) {
48
+ targets.push({ kind: 'miniwdl', path: join(path, file), cwd: dirname(join(path, file)) });
49
+ }
50
+ for (const file of found.snakemake.filter(f => !/(^|[\\/])rules[\\/]/.test(f)).slice(0, MAX_SNAKEFILES)) {
51
+ const pipeline = await pipelineOf('snakemake', join(path, file));
52
+ targets.push({ kind: 'snakemake', path: pipeline.file, cwd: pipeline.root });
53
+ }
54
+ }
55
+ return only ? targets.filter(t => t.kind === only) : targets;
56
+ }
57
+ async function lintOne(program, target, env) {
58
+ const options = { cwd: target.cwd, timeoutMs: LINT_TIMEOUT, env: programEnv(program.kind, env, { offline: true }) };
59
+ if (program.kind === 'nextflow') {
60
+ if (compareVersions(program.version, NEXTFLOW_LINT_SINCE) < 0) {
61
+ return `nextflow lint ${target.path}: skipped — "nextflow lint" needs Nextflow 25.04 or newer, found ${program.version}. Use bio_plan (nextflow -preview) to check that the script compiles.`;
62
+ }
63
+ const result = await run(program.path, ['lint', '-o', 'json', target.path], options);
64
+ const findings = parseNextflowLint(result.stdout);
65
+ if (!findings) {
66
+ throw failure('nextflow lint', result);
67
+ }
68
+ return `nextflow lint ${target.path}: ${findings.length ? `${findings.length} finding(s)\n${findings.join('\n')}` : 'no errors or warnings.'}`;
69
+ }
70
+ if (program.kind === 'miniwdl') {
71
+ const result = await run(program.path, ['check', target.path], options);
72
+ const { findings } = parseMiniwdlCheck(target.path, result.stdout, result.stderr);
73
+ const head = result.code === 0 ? 'parsed and type-checked' : 'FAILED to parse or type-check';
74
+ const extra = result.code !== 0 && !findings.some(f => f.startsWith('error:')) ? `\n${(result.stderr || result.stdout).trim()}` : '';
75
+ return `miniwdl check ${target.path}: ${head}${findings.length ? `, ${findings.length} finding(s)\n${findings.join('\n')}` : '.'}${extra}`;
76
+ }
77
+ const result = await run(program.path, ['--lint', 'json', '--snakefile', target.path, '--directory', target.cwd, '--nocolor'], options);
78
+ const findings = parseSnakemakeLint(result.stdout);
79
+ if (!findings) {
80
+ throw failure('snakemake --lint', result);
81
+ }
82
+ return `snakemake --lint ${target.path}: ${findings.length ? `${findings.length} finding(s)\n${findings.join('\n')}` : 'no lints.'}`;
83
+ }
84
+ export async function lint(ctx, args) {
85
+ const path = await existingPath(args.path, '"path"');
86
+ const targets = await lintTargets(path, args.program);
87
+ if (!targets.length) {
88
+ return `Nothing to lint under ${path}${args.program ? ` for ${args.program}` : ''}.`;
89
+ }
90
+ const sections = [];
91
+ for (const target of targets) {
92
+ const program = await findProgram(ctx, target.kind);
93
+ if (!program) {
94
+ sections.push(`${target.path}: skipped — ${PROGRAMS[target.kind].notFound}`);
95
+ continue;
96
+ }
97
+ sections.push(await lintOne(program, target, ctx.env).catch((error) => `${target.path}: ${error.message}`));
98
+ }
99
+ return sections.join('\n\n');
100
+ }
@@ -0,0 +1,144 @@
1
+ /** JSON из вывода, перед которым программа могла напечатать что-то ещё. */
2
+ function jsonOf(text) {
3
+ const start = text.indexOf('{');
4
+ if (start < 0) {
5
+ return undefined;
6
+ }
7
+ try {
8
+ return JSON.parse(text.slice(start));
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
14
+ /** `nextflow lint -o json`: `{ errors: [...], warnings: [...] }` с полями filename, startLine, startColumn, message. */
15
+ export function parseNextflowLint(stdout) {
16
+ const parsed = jsonOf(stdout);
17
+ if (!parsed || typeof parsed !== 'object') {
18
+ return undefined;
19
+ }
20
+ const line = (severity, item) => `${severity}: ${String(item.filename ?? '?')}:${Number(item.startLine ?? 0)}:${Number(item.startColumn ?? 0)}: ${String(item.message ?? '').replace(/\s+/g, ' ').trim()}`;
21
+ const list = (value) => Array.isArray(value) ? value : [];
22
+ return [...list(parsed.errors).map(e => line('error', e)), ...list(parsed.warnings).map(w => line('warning', w))];
23
+ }
24
+ /**
25
+ * `miniwdl check`: в stdout — схема документа с замечаниями «(Ln 2, Col 7) UnusedDeclaration, …» и строками `call`;
26
+ * ошибки разбора и типов — в stderr «(file.wdl Ln 3 Col 5) …».
27
+ */
28
+ export function parseMiniwdlCheck(file, stdout, stderr) {
29
+ const findings = [];
30
+ let calls = 0;
31
+ for (const line of stdout.split('\n')) {
32
+ const warning = /^\s*\(Ln (\d+), Col (\d+)\)\s*(.*)$/.exec(line);
33
+ if (warning) {
34
+ findings.push(`warning: ${file}:${warning[1]}:${warning[2]}: ${warning[3].trim()}`);
35
+ }
36
+ else if (/^\s+call\s+\S/.test(line)) {
37
+ calls++;
38
+ }
39
+ }
40
+ for (const line of stderr.split('\n')) {
41
+ const error = /^\((.+?) Ln (\d+) Col (\d+)\)\s*(.*)$/.exec(line.trim());
42
+ if (error) {
43
+ findings.push(`error: ${error[1]}:${error[2]}:${error[3]}: ${error[4].trim()}`);
44
+ }
45
+ }
46
+ return { calls, findings };
47
+ }
48
+ /** `snakemake --lint json`: `{ snakefiles: [{ for: { snakefile }, lints }], rules: [{ for: { rule, line, snakefile }, lints }] }`. */
49
+ export function parseSnakemakeLint(stdout) {
50
+ const parsed = jsonOf(stdout);
51
+ if (!parsed || typeof parsed !== 'object' || (!('snakefiles' in parsed) && !('rules' in parsed))) {
52
+ return undefined;
53
+ }
54
+ const out = [];
55
+ const groups = (value) => Array.isArray(value) ? value : [];
56
+ for (const group of [...groups(parsed.snakefiles), ...groups(parsed.rules)]) {
57
+ const where = `${String(group.for?.snakefile ?? '?')}${group.for?.line !== undefined && group.for.line !== null ? `:${Number(group.for.line)}` : ''}`;
58
+ const rule = group.for?.rule ? ` rule ${String(group.for.rule)}:` : '';
59
+ for (const lint of Array.isArray(group.lints) ? group.lints : []) {
60
+ out.push(`lint: ${where}:${rule} ${String(lint.title ?? '')} — ${String(lint.body ?? '').replace(/\s+/g, ' ').trim()}`);
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ /** Таблица «Job stats» сухого прогона Snakemake: число заданий по правилам и итог. */
66
+ export function parseSnakemakeJobStats(text) {
67
+ const lines = text.split('\n');
68
+ const start = lines.findIndex(line => line.trim() === 'Job stats:');
69
+ if (start < 0) {
70
+ return undefined;
71
+ }
72
+ const rules = [];
73
+ for (const line of lines.slice(start + 1)) {
74
+ const row = /^\s*(\S+)\s+(\d+)\s*$/.exec(line);
75
+ if (row) {
76
+ if (row[1] === 'total') {
77
+ return { total: Number(row[2]), rules };
78
+ }
79
+ rules.push({ name: row[1], count: Number(row[2]) });
80
+ }
81
+ else if (line.trim() && !/^[-\s]+$/.test(line) && !/^\s*job\s+count\s*$/.test(line)) {
82
+ break;
83
+ }
84
+ }
85
+ return rules.length ? { total: rules.reduce((sum, r) => sum + r.count, 0), rules } : undefined;
86
+ }
87
+ /** Процессы в DAG Nextflow в формате Mermaid: узлы процессов — `v3(["NAME"])`; операторы без `-verbose` — `(( ))`. */
88
+ export function parseNextflowDag(mermaid) {
89
+ const names = new Set();
90
+ for (const match of mermaid.matchAll(/\b[a-z]?\d+\(\["?([^"\]]+)"?\]\)/g)) {
91
+ names.add(match[1].trim());
92
+ }
93
+ return [...names];
94
+ }
95
+ /**
96
+ * Прогресс Nextflow по логу без ANSI: строки «[ab/123456] Submitted process > NAME (1)», «Cached process >», а в
97
+ * ANSI-сводке «[ab/123456] process > NAME (3) [100%] 3 of 3 ✔» — берётся последняя строка каждого процесса.
98
+ */
99
+ export function nextflowProgress(log) {
100
+ const ansi = new Map();
101
+ const counts = new Map();
102
+ let executor = '';
103
+ for (const line of log.split('\n')) {
104
+ const exec = /^executor\s*>\s*(.+)$/.exec(line.trim());
105
+ if (exec) {
106
+ executor = `executor > ${exec[1].trim()}`;
107
+ }
108
+ const bar = /\[[0-9a-f-]{2}\/[0-9a-f-]{6}\]\s+process\s*>\s*(\S+)(.*\[\s*\d+%\].*)$/.exec(line);
109
+ if (bar) {
110
+ ansi.set(bar[1], `${bar[1]}${bar[2]}`.replace(/\s+/g, ' ').trim());
111
+ continue;
112
+ }
113
+ const plain = /\[[0-9a-f]{2}\/[0-9a-f]{6}\]\s+(Submitted|Re-submitted|Cached) process\s*>\s*(\S+)/.exec(line);
114
+ if (plain) {
115
+ const entry = counts.get(plain[2]) ?? { submitted: 0, cached: 0 };
116
+ if (plain[1] === 'Cached') {
117
+ entry.cached++;
118
+ }
119
+ else {
120
+ entry.submitted++;
121
+ }
122
+ counts.set(plain[2], entry);
123
+ }
124
+ }
125
+ const rows = ansi.size
126
+ ? [...ansi.values()]
127
+ : [...counts.entries()].map(([name, c]) => `${name}: ${c.submitted} submitted${c.cached ? `, ${c.cached} cached` : ''}`);
128
+ return executor && rows.length ? [executor, ...rows] : rows;
129
+ }
130
+ /** Прогресс Snakemake: последняя строка «3 of 5 steps (60%) done». */
131
+ export function snakemakeProgress(log) {
132
+ const matches = [...log.matchAll(/^\s*(\d+ of \d+ steps \(\d+%\) done)/gm)];
133
+ return matches.length ? [matches[matches.length - 1][1]] : [];
134
+ }
135
+ /** Исход по хвосту лога, когда код выхода неизвестен (сервер перезапускался во время прогона). */
136
+ export function inferOutcome(program, log) {
137
+ const patterns = {
138
+ nextflow: { ok: /^Succeeded\s*:|Workflow completed successfully|^Completed at:/m, fail: /^ERROR ~|Execution aborted|Workflow failed/m },
139
+ snakemake: { ok: /\(100%\) done|Nothing to be done/, fail: /Exiting because a job execution failed|^Error in rule|WorkflowError/m },
140
+ miniwdl: { ok: /"outputs"\s*:/, fail: /\bfailed\b.*\btask\b|"error"\s*:|Traceback/i },
141
+ };
142
+ const { ok, fail } = patterns[program];
143
+ return fail.test(log) ? 'failed' : ok.test(log) ? 'succeeded' : undefined;
144
+ }