@cmdop/project-check 0.0.0-stage → 4.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CMDOP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/LICENSE-SDK ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 CMDOP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # CMDOP Project Check
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
+ Check a Node.js project's CMDOP SDK configuration before running your first machine request. **@cmdop/project-check** is an offline CLI for inspecting project metadata and creating the official TypeScript SDK starter without executing it.
4
+
5
+ ![Illustrated CMDOP SDK workflow: application code connects to a computer and reads a selected file.](https://raw.githubusercontent.com/commandoperator/assets/6c26ca88ca56a0a5f65adb28e5079447932bae08/promo/sdk-readfirst-v2.webp)
6
+
7
+ *Illustration of the SDK workflow you can build after setup, not an execution by Project Check.*
8
+
9
+ [CMDOP](https://cmdop.ai) · [Documentation](https://docs.cmdop.ai) · [Official SDK quickstart](https://github.com/commandoperator/cmdop-sdk/blob/main/docs/quickstart.md)
10
+
11
+ ## Requirements
12
+
13
+ - Node.js 20 or newer, with npm.
14
+ - An npm-managed application directory. Linked SDK packages, pnpm, Yarn and workspaces are not supported by this utility.
15
+ - SDK 3.6.1 is the reviewed version for starter creation.
16
+
17
+ ## Install and check your project
18
+
19
+ Install the utility in a separate tools directory:
20
+
21
+ ```sh
22
+ npm install --save-exact @cmdop/project-check@4.0.0
23
+ ```
24
+
25
+ From that directory, point the CLI at your application:
26
+
27
+ ```sh
28
+ npx --no-install cmdop-project-check doctor --target /path/to/project
29
+ npx --no-install cmdop-project-check doctor --target /path/to/project --json
30
+ ```
31
+
32
+ The check reads local runtime prerequisites, package-manager and lockfile compatibility, the declared SDK dependency, and the SDK manifest under your application's node_modules directory. It never runs SDK code or your application's lifecycle scripts.
33
+
34
+ ## Interpret the SDK result
35
+
36
+ | SDK status | Meaning |
37
+ | --- | --- |
38
+ | `matches_reviewed_version` | Local SDK metadata identifies the reviewed version. |
39
+ | `missing` | No project-local SDK manifest was found. |
40
+ | `different_version` | The installed manifest reports another version. |
41
+ | Other status or blocked diagnostic | Resolve the reported metadata or environment problem first. |
42
+
43
+ The CLI rejects unsuitable project metadata rather than trying to repair or install anything automatically. A successful diagnostic is not an SDK import, integrity, login or machine connection check.
44
+
45
+ If the SDK is missing, review the suggested install command and run it yourself in the application directory:
46
+
47
+ ```sh
48
+ npm install --save-exact @cmdop/sdk@3.6.1
49
+ ```
50
+
51
+ ## Create the official starter example
52
+
53
+ After the diagnostic reports the reviewed SDK version, run this from your tools directory:
54
+
55
+ ```sh
56
+ npx --no-install cmdop-project-check example --target /path/to/project
57
+ ```
58
+
59
+ This creates `cmdop-example.mjs` only if that file does not already exist. It does not run the example or connect to a machine. Review the generated code, [install the CMDOP machine program](https://cmdop.ai/download) separately, and follow the [SDK authentication guide](https://github.com/commandoperator/cmdop-sdk/blob/main/docs/authentication.md) before running it.
60
+
61
+ ## CLI reference
62
+
63
+ | Command | Behavior |
64
+ | --- | --- |
65
+ | `doctor [--target DIR] [--json]` | Inspect local project metadata; default target is the current directory. |
66
+ | `example --target DIR [--json]` | Create one starter file after a matching SDK metadata check. |
67
+ | `--help`, `--version` | Display usage or utility version. |
68
+
69
+ Exit code 0 indicates completion of the requested operation, 2 invalid usage, 3 a blocked operation, and 4 an unexpected inspection failure. A missing SDK can be reported by a successful inspection; consult the SDK status in the JSON result.
70
+
71
+ ## Privacy and license
72
+
73
+ This first-party CMDOP utility includes readable JavaScript sources and the SDK-owned starter. It does not bundle the SDK, run install hooks, install dependencies at runtime, read credentials, make network requests, send analytics or connect to machines. Diagnostics stay local.
74
+
75
+ MIT. See LICENSE and LICENSE-SDK in the archive. The SDK source and technical documentation are available at [commandoperator/cmdop-sdk](https://github.com/commandoperator/cmdop-sdk).
@@ -0,0 +1,28 @@
1
+ {
2
+ "schema_version": 1,
3
+ "contract_version": "0.1.0",
4
+ "package_version": "4.0.0",
5
+ "brand": {
6
+ "name": "CMDOP"
7
+ },
8
+ "identity": {
9
+ "family_id": "cmdop-project-check",
10
+ "entry_name": "cmdop-project-check",
11
+ "publisher": "CMDOP"
12
+ },
13
+ "links": {
14
+ "sdk": "https://github.com/commandoperator/cmdop-sdk",
15
+ "product": "https://cmdop.ai"
16
+ },
17
+ "compatibility": {
18
+ "typescript": {
19
+ "package_name": "@cmdop/sdk",
20
+ "minimum_major": 20,
21
+ "minimum_minor": 0,
22
+ "approved_version": "3.6.1",
23
+ "status": "published-artifact-accepted"
24
+ }
25
+ },
26
+ "help_text": "CMDOP Project Check: local project metadata, no network.",
27
+ "explanations": {}
28
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "schema_version": 1,
3
+ "status": "sdk-owned-example-copy-not-execution-proof",
4
+ "templates": {
5
+ "typescript": {
6
+ "filename": "cmdop-example.mjs",
7
+ "content": "import { connect } from \"@cmdop/sdk\";\n\nconst client = connect();\ntry {\n const online = (await client.machines()).find((machine) => machine.online);\n if (!online) throw new Error(\"Bring a machine online on your CMDOP page.\");\n const info = await client.machine(online.id).sys.info({});\n console.log(info.os, info.arch, info.cpus);\n} finally {\n await client.close();\n}\n",
8
+ "sha256": "bdb3914ef6b9df76c19575213ef02a50d6de0bb5f199582fc795be3104ac775a"
9
+ }
10
+ }
11
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@cmdop/project-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.0.0",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "description": "Offline CLI to check Node.js CMDOP SDK metadata and create a TypeScript starter",
7
+ "keywords": [
8
+ "cmdop",
9
+ "sdk",
10
+ "cli",
11
+ "nodejs",
12
+ "typescript",
13
+ "project-diagnostics",
14
+ "starter"
15
+ ],
16
+ "type": "module",
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "bin": {
21
+ "cmdop-project-check": "runtime/node/project-check.mjs"
22
+ },
23
+ "files": [
24
+ "runtime/node/project-check.mjs",
25
+ "runtime/node/launcher.mjs",
26
+ "catalog/project-check.json",
27
+ "catalog/sdk-starters.json",
28
+ "README.md",
29
+ "LICENSE-SDK",
30
+ "LICENSE"
31
+ ],
32
+ "homepage": "https://cmdop.ai",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
@@ -0,0 +1,362 @@
1
+ import { readFileSync, writeFileSync, readdirSync, statSync, lstatSync, fstatSync, openSync, closeSync, readSync, realpathSync, accessSync, constants } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { dirname, resolve, join, delimiter } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createInterface } from "node:readline/promises";
6
+
7
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
8
+ const stageNames = ["runtime", "installed", "imported", "configured", "authenticated", "machine_ready", "machine_read", "starter", "guide"];
9
+ const legacyFlags = new Set(["--force", "--install-only", "--prefix", "--quiet", "--"]);
10
+ export const readCatalog = () => JSON.parse(readFileSync(join(root, "catalog/launcher.json"), "utf8"));
11
+
12
+ function executable(name) {
13
+ for (const directory of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
14
+ for (const suffix of process.platform === "win32" ? ["", ".exe", ".cmd"] : [""]) {
15
+ const candidate = resolve(directory, name + suffix);
16
+ try { if (statSync(candidate).isFile()) { accessSync(candidate, constants.X_OK); return candidate; } } catch {}
17
+ }
18
+ }
19
+ return null;
20
+ }
21
+ export function runtimeFacts() {
22
+ return { platform: process.platform, native_language: "typescript",
23
+ versions: { python: null, typescript: process.versions.node.split(".").map(Number) },
24
+ executables: { python: executable("python3") ?? executable("python"), node: process.execPath, npm: executable("npm") } };
25
+ }
26
+ const directoryExists = (path) => { try { return statSync(path).isDirectory(); } catch { return false; } };
27
+ const fileExists = (path) => { try { return statSync(path).isFile(); } catch { return false; } };
28
+ const writable = (path) => { try { accessSync(path, constants.W_OK); return true; } catch { return false; } };
29
+
30
+ // Inspect only a bounded, ordinary project manifest. Do not follow a final symlink.
31
+ const MAX_MANIFEST_BYTES = 256 * 1024;
32
+ function readProjectManifest(path) {
33
+ const initial = lstatSync(path);
34
+ if (!initial.isFile() || initial.size > MAX_MANIFEST_BYTES) throw Error("Invalid manifest");
35
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
36
+ try {
37
+ const before = fstatSync(fd);
38
+ const stamp = s => [s.dev, s.ino, s.mode, s.size, s.mtimeMs, s.ctimeMs].join(":");
39
+ if (!before.isFile() || before.size > MAX_MANIFEST_BYTES || stamp(initial) !== stamp(before)) throw Error("Invalid manifest");
40
+ const bytes = Buffer.alloc(before.size + 1);
41
+ let count = 0;
42
+ while (count < bytes.length) {
43
+ const n = readSync(fd, bytes, count, bytes.length - count, null);
44
+ if (!n) break;
45
+ count += n;
46
+ }
47
+ if (count !== before.size || stamp(before) !== stamp(fstatSync(fd))) throw Error("Manifest changed");
48
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)));
49
+ } finally { closeSync(fd); }
50
+ }
51
+
52
+ export function evaluate(action, options = {}, catalog = readCatalog(), context = runtimeFacts()) {
53
+ const result = { schema_version: 1, contract_version: catalog.contract_version,
54
+ requested_action: action, result: "success", error_category: null, message: "",
55
+ stages: Object.fromEntries(stageNames.map((name) => [name, "not_attempted"])),
56
+ changes: [], plan: null, diagnostics: catalog.revisions ? { revisions: structuredClone(catalog.revisions) } : {}, links: { ...catalog.links } };
57
+ const fail = (reason, message = reason, code = 3) => {
58
+ result.result = code === 2 || code === 4 ? "failed" : "blocked";
59
+ result.error_category = reason; result.message = message;
60
+ return [result, code];
61
+ };
62
+ if (action === "help") {
63
+ result.message = catalog.help_text;
64
+ return [result, 0];
65
+ }
66
+ if (action === "version") { result.message = catalog.package_version; return [result, 0]; }
67
+ if (action === "links") { result.stages.guide = "passed"; result.message = "Links are shown only; no browser was opened."; return [result, 0]; }
68
+ if (action === "explain") {
69
+ const messages = catalog.explanations;
70
+ const topic = options.topic ?? "product";
71
+ if (!Object.hasOwn(messages, topic)) return fail("usage", "Unknown explanation topic.", 2);
72
+ result.message = messages[topic]; result.stages.guide = "passed";
73
+ return [result, 0];
74
+ }
75
+ if (!["doctor", "sdk_plan", "sdk_setup"].includes(action)) return fail("usage", "Unknown action.", 2);
76
+ const language = options.language ?? context.native_language ?? "typescript";
77
+ if (!Object.hasOwn(catalog.compatibility, language)) return fail("usage", "Choose python or typescript.", 2);
78
+ const planning = action !== "doctor";
79
+ if (planning && (!options.target || !options.language)) return fail("usage", "SDK preview requires --target and --language.", 2);
80
+ const target = resolve(options.target ?? process.cwd());
81
+ const isNew = Boolean(options.new);
82
+ const blockers = [];
83
+ let names = [], packageJson = null;
84
+ if (directoryExists(target)) {
85
+ try { names = readdirSync(target); } catch { blockers.push("target_unreadable"); }
86
+ if (isNew && names.length) blockers.push("new_target_not_empty");
87
+ } else {
88
+ if (!isNew || fileExists(target)) blockers.push("target_not_directory");
89
+ }
90
+ let parent = target;
91
+ while (!directoryExists(parent) && dirname(parent) !== parent) parent = dirname(parent);
92
+ if (!writable(parent)) blockers.push("target_unwritable");
93
+ if (!blockers.length && names.includes("package.json")) {
94
+ try { packageJson = readProjectManifest(join(target, "package.json")); if (!packageJson || typeof packageJson !== "object" || Array.isArray(packageJson) || Object.hasOwn(packageJson, "packageManager") && typeof packageJson.packageManager !== "string") throw Error(); }
95
+ catch { packageJson = null; blockers.push("invalid_manifest"); }
96
+ }
97
+ let manager = language === "typescript" ? "npm" : "pip";
98
+ const locks = language === "typescript" ? ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"].filter((name) => names.includes(name)) : ["uv.lock", "poetry.lock"].filter((name) => names.includes(name));
99
+ if (locks.length > 1) blockers.push("project_conflict");
100
+ if (language === "typescript") {
101
+ if (locks.includes("pnpm-lock.yaml") || packageJson?.packageManager?.startsWith("pnpm@")) manager = "pnpm";
102
+ else if (locks.includes("yarn.lock") || packageJson?.packageManager?.startsWith("yarn@")) manager = "yarn";
103
+ else if (typeof packageJson?.packageManager === "string") manager = packageJson.packageManager.split("@")[0];
104
+ if (names.includes("pnpm-workspace.yaml")) manager = "pnpm";
105
+ if (packageJson && Object.hasOwn(packageJson, "workspaces")) blockers.push("project_conflict");
106
+ } else {
107
+ if (locks.includes("uv.lock")) manager = "uv";
108
+ else if (locks.includes("poetry.lock")) manager = "poetry";
109
+ }
110
+ if (!["npm", "pip"].includes(manager)) blockers.push("unsupported_project_manager");
111
+ const version = context.versions?.[language] ?? null;
112
+ const present = language === "python" ? context.executables?.python : context.executables?.node;
113
+ const spec = catalog.compatibility[language];
114
+ if (!present && !version) blockers.push("runtime_missing");
115
+ else if (!version) blockers.push("runtime_unverified");
116
+ else if (version[0] < spec.minimum_major || version[0] === spec.minimum_major && version[1] < spec.minimum_minor) blockers.push("runtime_unsupported");
117
+ if (language === "typescript" && manager === "npm" && !context.executables?.npm) blockers.push("manager_missing");
118
+ const pythonInVenv = context.platform === "win32" ? ".venv/Scripts/python.exe" : ".venv/bin/python";
119
+ if (planning && language === "python" && !isNew && !fileExists(join(target, pythonInVenv))) blockers.push("missing_project_venv");
120
+ result.diagnostics = { ...result.diagnostics, target, language, mode: isNew ? "new" : "existing", manager, lockfiles: locks, runtime_version: version, runtime_presence: Boolean(present || version), offline: true, install_enabled: false };
121
+ if (!["runtime_missing", "runtime_unverified", "runtime_unsupported"].some((reason) => blockers.includes(reason))) result.stages.runtime = "passed";
122
+ else result.stages.runtime = "blocked";
123
+ if (!planning) {
124
+ if (blockers.length) return fail(blockers[0], "Environment diagnostics found prerequisites: " + [...new Set(blockers)].join(", "));
125
+ result.message = "Local environment inspected. SDK import, authorization and machine access were not checked.";
126
+ return [result, 0];
127
+ }
128
+ blockers.push("sdk_baseline_pending");
129
+ const commands = language === "typescript"
130
+ ? [["npm", "install", "--save-exact", "@cmdop/sdk@<approved-version>"]]
131
+ : [...(isNew ? [["python3", "-m", "venv", ".venv"]] : []), [pythonInVenv, "-m", "pip", "install", "cmdop==<approved-version>"]];
132
+ result.plan = { language, target, mode: isNew ? "new" : "existing", manager,
133
+ package_name: spec.package_name, approved_version: null, commands,
134
+ files_may_change: language === "typescript" ? ["package.json", "package-lock.json", "node_modules"] : [...(isNew ? ["pyproject.toml"] : []), ".venv"],
135
+ install_enabled: false, blockers: [...new Set(blockers)] };
136
+ return fail(blockers[0], "Preview only. Nothing was installed or written. A verified SDK baseline and the install executor are not available yet.");
137
+ }
138
+
139
+ function parse(args) {
140
+ if (args.some((arg) => legacyFlags.has(arg) || arg.startsWith("--prefix="))) throw Error("Legacy installer options are not supported; use an explicit SDK preview or machine guide.");
141
+ const options = {}, positional = [];
142
+ let json = false, help = false, version = false;
143
+ for (let i = 0; i < args.length; i++) {
144
+ const arg = args[i];
145
+ if (arg === "--json") { json = true; continue; }
146
+ if (["--plain", "--no-color"].includes(arg)) continue;
147
+ if (arg === "--help" || arg === "-h") { help = true; continue; }
148
+ if (arg === "--version") { version = true; continue; }
149
+ if (arg === "--new") { options.new = true; continue; }
150
+ if (["--target", "--language"].includes(arg)) {
151
+ if (!args[i + 1] || args[i + 1].startsWith("--")) throw Error("Missing option value");
152
+ const key = arg.slice(2); if (Object.hasOwn(options, key)) throw Error("Duplicate option"); options[key] = args[++i]; continue;
153
+ }
154
+ if (arg.startsWith("-")) throw Error("Unknown option");
155
+ positional.push(arg);
156
+ }
157
+ if (help) return { action: "help", options: {}, json };
158
+ if (version) return { action: "version", options: {}, json };
159
+ if (!positional.length) return { action: "bare", options, json };
160
+ let action;
161
+ if (positional[0] === "sdk" && ["plan", "setup"].includes(positional[1]) && positional.length === 2) action = "sdk_" + positional[1];
162
+ else if (positional[0] === "doctor" && positional.length === 1) action = "doctor";
163
+ else if (positional[0] === "explain" && positional.length <= 2) { action = "explain"; options.topic = positional[1] ?? "product"; }
164
+ else if (["links", "help", "version"].includes(positional[0]) && positional.length === 1) action = positional[0];
165
+ else throw Error("Unknown command or extra arguments");
166
+ if (options.new && !["sdk_plan", "sdk_setup"].includes(action)) throw Error("--new is only valid for SDK preview");
167
+ if (["links", "explain", "help", "version"].includes(action) && (options.target || options.language)) throw Error("Unexpected project options");
168
+ return { action, options, json };
169
+ }
170
+ function render(result, json) {
171
+ if (json) { console.log(JSON.stringify(result)); return; }
172
+ console.log(result.message);
173
+ if (result.plan && !result.diagnostics?.plan_presented) console.log(JSON.stringify(result.plan, null, 2));
174
+ else if (result.requested_action === "doctor") console.log(JSON.stringify(result.diagnostics, null, 2));
175
+ else if (result.requested_action === "links") for (const [name, href] of Object.entries(result.links)) console.log(name + ": " + href);
176
+ }
177
+ export function writeSdkStarter(target, language) {
178
+ if (language !== "typescript") throw Error("Native starter language required.");
179
+ if (realpathSync(target) !== resolve(target) || !statSync(target).isDirectory()) throw Error("Target changed.");
180
+ const source = JSON.parse(readFileSync(join(root, "catalog/sdk-starters.json"), "utf8"));
181
+ const template = source.templates.typescript;
182
+ if (source.schema_version !== 1 || template.filename !== "cmdop-example.mjs"
183
+ || Buffer.byteLength(template.content) > 16384
184
+ || createHash("sha256").update(template.content).digest("hex") !== template.sha256) throw Error("Invalid SDK starter.");
185
+ writeFileSync(join(target, template.filename), template.content, { flag: "wx", mode: 0o644 });
186
+ return template.filename;
187
+ }
188
+
189
+ // Local setup acceptance is explicit imported API configuration, never an env/CLI override.
190
+ export async function runSdkSetup(action, options, catalog, baseline, { ask = null, write = console.log, signal } = {}) {
191
+ if (!["sdk_plan", "sdk_setup"].includes(action) || !baseline || options.language !== "typescript") return evaluate(action, options, catalog);
192
+ const [result] = evaluate("help", {}, catalog);
193
+ result.requested_action = action;
194
+ if (!options.target) {
195
+ Object.assign(result, { result: "failed", error_category: "usage", message: "SDK setup requires --target and --language." });
196
+ return [result, 2];
197
+ }
198
+ const { planSetup, executeSetup } = await import("./sdk-setup.mjs");
199
+ const plan = planSetup({ target: options.target, newProject: Boolean(options.new), baseline });
200
+ result.plan = plan;
201
+ result.diagnostics = { ...result.diagnostics, local_setup_candidate: true, install_enabled: plan.blockers.length === 0 };
202
+ if (plan.blockers.length) {
203
+ Object.assign(result, { result: "blocked", error_category: plan.blockers[0], message: "SDK setup prerequisites are not satisfied. Nothing was changed." });
204
+ return [result, 3];
205
+ }
206
+ result.stages.runtime = "passed";
207
+ if (action === "sdk_plan") {
208
+ result.message = "Reviewed local SDK candidate plan. Nothing was installed or written.";
209
+ return [result, 0];
210
+ }
211
+ if (typeof ask !== "function") {
212
+ Object.assign(result, { result: "blocked", error_category: "confirmation_required", message: "Review this plan in a terminal and explicitly confirm installation." });
213
+ return [result, 3];
214
+ }
215
+ write("Local SDK candidate: the package manager may resolve dependencies. This does not connect a machine.");
216
+ write(JSON.stringify(plan, null, 2));
217
+ result.diagnostics.plan_presented = true;
218
+ let confirmed = false;
219
+ try { confirmed = (await ask("Install this SDK in the project? Type yes [Back]: ")).trim().toLowerCase() === "yes"; }
220
+ catch { /* EOF/cancellation never confirms a plan. */ }
221
+ const execution = await executeSetup(plan, { confirmed, signal });
222
+ result.result = execution.status;
223
+ result.error_category = execution.error_category ?? null;
224
+ result.message = execution.message ?? execution.recovery ?? "SDK setup completed. Follow the official connection guide when ready.";
225
+ result.changes = execution.changes ?? [];
226
+ Object.assign(result.stages, execution.stages ?? {});
227
+ result.diagnostics.installed_version = execution.installed_version ?? null;
228
+ if (execution.exit_code === 0) {
229
+ write("SDK import checked. No authorization or machine access was performed.");
230
+ let starter = false;
231
+ try { starter = (await ask("Create the SDK example file without running it? Type yes [Back]: ")).trim().toLowerCase() === "yes"; } catch {}
232
+ if (signal?.aborted) {
233
+ result.result = "cancelled"; result.error_category = "cancelled";
234
+ result.message = "Cancelled after SDK installation/import. Existing project changes are retained.";
235
+ return [result, 130];
236
+ }
237
+ if (starter) {
238
+ try {
239
+ const filename = writeSdkStarter(plan.target, "typescript");
240
+ result.changes.push(filename); result.stages.starter = "written";
241
+ write("Created " + filename + ". It connects only when you run it after configuring CMDOP. " + catalog.links.sdk);
242
+ } catch {
243
+ result.result = "blocked"; result.error_category = "starter_not_written"; result.stages.starter = "blocked";
244
+ result.message = "SDK installed and imported. The example was not written; existing files are preserved.";
245
+ return [result, 3];
246
+ }
247
+ }
248
+ }
249
+ return [result, execution.exit_code];
250
+ }
251
+
252
+ export async function menu(catalog, observationSession = null, createMenuInterface = createInterface, setupBaseline = null) {
253
+ const rl = createMenuInterface({ input: process.stdin, output: process.stdout });
254
+ const observe = (method, ...args) => { try { observationSession?.[method](...args); } catch {} };
255
+ // readline.close() leaves an outstanding question unresolved. Settle it on
256
+ // actual EOF/SIGINT as well, so cleanup and the useful exit status still run.
257
+ const closed = Symbol("readline closed");
258
+ const didClose = new Promise(resolve => rl.on("close", () => resolve(closed)));
259
+ const question = async prompt => {
260
+ const value = await Promise.race([rl.question(prompt), didClose]);
261
+ if (value === closed) throw Object.assign(Error("Terminal input closed."), { code: "ERR_USE_AFTER_CLOSE" });
262
+ return value;
263
+ };
264
+ let cancelled = false;
265
+ const setupAbort = new AbortController();
266
+ let pendingCode = 0;
267
+ const exitChoice = catalog.menu.findIndex((item) => item.id === "exit") + 1;
268
+ const interrupt = () => { cancelled = true; setupAbort.abort(); rl.close(); };
269
+ rl.on("SIGINT", interrupt);
270
+ process.on("SIGINT", interrupt);
271
+ try {
272
+ while (!cancelled) {
273
+ console.log("\n" + catalog.brand.name + " · cmdop.ai\n" + catalog.brand.tagline + "\n" + catalog.identity.notice + (setupBaseline ? "\nLocal SDK setup candidate. Project changes require confirmation." : "\nOffline prototype: nothing has been installed or connected."));
274
+ catalog.menu.forEach((item, i) => console.log(String(i + 1) + ". " + (setupBaseline && item.id === "sdk" ? "Set up SDK for my project" : item.label)));
275
+ let choice;
276
+ try { choice = await question("Choose an option [" + exitChoice + "]: "); } catch { break; }
277
+ const item = catalog.menu[(Number(choice || exitChoice) || 0) - 1];
278
+ if (!item) { console.log("Choose a number from 1 to " + catalog.menu.length + "."); continue; }
279
+ observe("action", item.id);
280
+ if (item.id === "exit") {
281
+ if (!cancelled && observationSession) {
282
+ try { await observationSession.finish({ code: pendingCode,
283
+ ask: (prompt) => question(prompt), write: (message) => console.log(message) }); } catch {}
284
+ }
285
+ return cancelled ? 130 : pendingCode;
286
+ }
287
+ if (item.id === "sdk") {
288
+ const language = (await question("Language [typescript/python]: ")).trim() || "typescript";
289
+ const target = (await question("Project directory: ")).trim();
290
+ let options = { language, target };
291
+ if (setupBaseline && language === "typescript") options.new = (await question("Create a new project? Type yes [existing]: ")).trim().toLowerCase() === "yes";
292
+ const [result, code] = setupBaseline
293
+ ? await runSdkSetup("sdk_setup", options, catalog, setupBaseline, { ask: question, signal: setupAbort.signal })
294
+ : evaluate("sdk_plan", options, catalog);
295
+ observe("outcome", item.id, result);
296
+ if (code === 130 && result.error_category !== "confirmation_required") {
297
+ render(result, false);
298
+ return 130;
299
+ }
300
+ if (code && code !== 130) pendingCode = code;
301
+ render(result, false);
302
+ } else if (item.id === "doctor") {
303
+ const [result, code] = evaluate("doctor", {}, catalog); observe("outcome", item.id, result); if (code) pendingCode = code; render(result, false);
304
+ } else if (item.id === "website") console.log(catalog.links.product);
305
+ else { const [result] = evaluate("explain", { topic: item.id }, catalog); observe("outcome", item.id, result); render(result, false); console.log(catalog.links[item.id === "product" ? "product" : item.id]); }
306
+ }
307
+ } catch (error) { if (!cancelled && error.code !== "ERR_USE_AFTER_CLOSE") throw error; }
308
+ finally { process.removeListener("SIGINT", interrupt); observe("discard"); rl.close(); }
309
+ return cancelled ? 130 : pendingCode;
310
+ }
311
+ export async function main(args, { observationSession = null, createObservationSession = null,
312
+ createMenuInterface = createInterface, setupBaseline = null } = {}) {
313
+ const catalog = readCatalog();
314
+ let command;
315
+ try { command = parse(args); }
316
+ catch (error) {
317
+ const [result] = evaluate("help", {}, catalog);
318
+ result.requested_action = "usage"; result.result = "failed"; result.error_category = "usage"; result.message = error.message;
319
+ render(result, args.includes("--json")); return 2;
320
+ }
321
+ if (command.action === "bare") {
322
+ if (Object.keys(command.options).length) { const [result] = evaluate("unknown", {}, catalog); render(result, command.json); return 2; }
323
+ if (!command.json && process.stdin.isTTY && process.stdout.isTTY) {
324
+ if (observationSession == null && typeof createObservationSession === "function"
325
+ && process.env.DO_NOT_TRACK !== "1") {
326
+ // Loading an optional shared client cannot prevent useful CLI behavior.
327
+ try { observationSession = await createObservationSession(); } catch { observationSession = null; }
328
+ }
329
+ return menu(catalog, observationSession, createMenuInterface, setupBaseline);
330
+ }
331
+ command.action = "help";
332
+ }
333
+ if (setupBaseline && ["sdk_plan", "sdk_setup"].includes(command.action)) {
334
+ let rl = null;
335
+ const controller = new AbortController();
336
+ const interrupt = () => { controller.abort(); rl?.close(); };
337
+ try {
338
+ let ask = null;
339
+ if (command.action === "sdk_setup" && !command.json && process.stdin.isTTY && process.stdout.isTTY) {
340
+ rl = createMenuInterface({ input: process.stdin, output: process.stdout });
341
+ const closed = Symbol("setup input closed");
342
+ const didClose = new Promise(resolve => rl.on("close", () => resolve(closed)));
343
+ rl.on("SIGINT", interrupt);
344
+ process.on("SIGINT", interrupt);
345
+ ask = async prompt => {
346
+ const answer = await Promise.race([rl.question(prompt), didClose]);
347
+ if (answer === closed) throw Error("Setup input closed.");
348
+ return answer;
349
+ };
350
+ }
351
+ const [result, code] = await runSdkSetup(command.action, command.options, catalog, setupBaseline,
352
+ { ask, signal: controller.signal });
353
+ render(result, command.json); return code;
354
+ } finally { process.removeListener("SIGINT", interrupt); rl?.close(); }
355
+ }
356
+ const [result, code] = evaluate(command.action, command.options, catalog);
357
+ render(result, command.json); return code;
358
+ }
359
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
360
+ try { process.exitCode = await main(process.argv.slice(2)); } catch { console.error("Launcher inspection failed."); process.exitCode = 4; }
361
+ }
362
+
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ // First-party offline project diagnostic. Never execute SDK/target code or send observations.
3
+ import { readFileSync, lstatSync, statSync, realpathSync, readdirSync } from "node:fs";
4
+ import { resolve, dirname, join, relative, isAbsolute, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { evaluate, runtimeFacts, writeSdkStarter } from "./launcher.mjs";
7
+
8
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
9
+ const profile = () => JSON.parse(readFileSync(join(root, "catalog/project-check.json"), "utf8"));
10
+ const help = "CMDOP Project Check\n doctor [--target DIR] [--json]\n example --target DIR [--json]\n --help | --version\nDoctor inspects metadata only. Example creates one file without executing it. No install, login, network or telemetry.";
11
+ const inside = (parent, child) => {
12
+ const r = relative(parent, child);
13
+ return r !== "" && !isAbsolute(r) && r !== ".." && !r.startsWith(".." + sep);
14
+ };
15
+ function manifest(target, relativeName) {
16
+ const path = join(target, relativeName);
17
+ try {
18
+ // Refuse links or unbounded manifest files, even inside an explicitly chosen project.
19
+ const actual = realpathSync(path);
20
+ if (!inside(target, actual) || actual !== path) return { status: "unsafe_path" };
21
+ const stat = lstatSync(path);
22
+ if (!stat.isFile() || stat.size > 262144) return { status: "unreadable" };
23
+ const data = JSON.parse(readFileSync(path, "utf8"));
24
+ if (!data || typeof data !== "object" || Array.isArray(data)) return { status: "invalid" };
25
+ return { status: "present", data };
26
+ } catch (err) {
27
+ return { status: err.code === "ENOENT" || err.code === "ENOTDIR" ? "missing" : "unreadable" };
28
+ }
29
+ }
30
+
31
+ export function inspectProject(target, catalog = profile(), context = runtimeFacts()) {
32
+ const result = { schema_version: 1, utility: "cmdop-project-check", action: "doctor",
33
+ target: resolve(target), runtime_version: process.versions.node,
34
+ expected_sdk: catalog.compatibility.typescript.approved_version,
35
+ sdk: { status: "not_checked", installed_version: null, declared_spec: null },
36
+ network_used: false, sdk_executed: false, credentials_read: false, changes: [] };
37
+ const refuse = (reason, code = 3) => [{ ...result, status: "blocked", reason }, code];
38
+ let canonical;
39
+ try {
40
+ canonical = realpathSync(result.target);
41
+ if (canonical !== result.target || !statSync(canonical).isDirectory()) return refuse("target_not_canonical_directory");
42
+ if (readdirSync(canonical).length > 20000) return refuse("target_too_large");
43
+ } catch { return refuse("target_unavailable"); }
44
+ const project = manifest(canonical, "package.json");
45
+ if (!["present", "missing"].includes(project.status)) return refuse("project_manifest_" + project.status);
46
+ // Reuse existing doctor for supported runtime, manager and lock conflict detection.
47
+ const [local, code] = evaluate("doctor", {target: canonical, language: "typescript"}, catalog, context);
48
+ result.environment = { manager: local.diagnostics.manager, lockfiles: local.diagnostics.lockfiles,
49
+ status: local.result, reason: local.error_category };
50
+ if (code !== 0) return refuse(local.error_category ?? "environment_blocked");
51
+ const declared = project.data?.dependencies?.["@cmdop/sdk"] ?? project.data?.devDependencies?.["@cmdop/sdk"];
52
+ if (typeof declared === "string" && declared.length <= 120 && /^[~^<>=* .0-9a-zA-Z|-]+$/.test(declared)) {
53
+ result.sdk.declared_spec = declared;
54
+ } else if (declared !== undefined) {
55
+ result.sdk.declared_spec = "nonstandard_spec";
56
+ }
57
+ const sdk = manifest(canonical, "node_modules/@cmdop/sdk/package.json");
58
+ result.sdk.status = sdk.status;
59
+ if (sdk.status === "present") {
60
+ const version = sdk.data.version;
61
+ if (sdk.data.name !== "@cmdop/sdk" || typeof version !== "string" ||
62
+ !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
63
+ result.sdk.status = "invalid_identity";
64
+ } else {
65
+ result.sdk.installed_version = version;
66
+ result.sdk.status = version === result.expected_sdk ? "matches_reviewed_version" : "different_version";
67
+ }
68
+ }
69
+ result.next = result.sdk.status === "matches_reviewed_version"
70
+ ? "SDK metadata matches the reviewed version. Import and connection are not tested; use the official quickstart."
71
+ : result.sdk.status === "missing"
72
+ ? "No local SDK manifest. Review installation of the official SDK in this project."
73
+ : "Review the local SDK metadata and compatibility before changing your project.";
74
+ if (result.sdk.status === "missing") result.suggested_command = ["npm","install","--save-exact","@cmdop/sdk@" + result.expected_sdk];
75
+ result.docs = catalog.links.sdk;
76
+ result.status = "inspected";
77
+ return [result, 0];
78
+ }
79
+
80
+ export function createExample(target, catalog = profile()) {
81
+ const [diagnostic, code] = inspectProject(target, catalog);
82
+ if (code !== 0) return [{...diagnostic, action:"example"}, code];
83
+ if (diagnostic.sdk.status !== "matches_reviewed_version") return [
84
+ {...diagnostic, action:"example", status:"blocked", reason:"reviewed_sdk_not_found"},3];
85
+ try {
86
+ const filename = writeSdkStarter(diagnostic.target, "typescript");
87
+ return [{...diagnostic, action:"example", status:"created", changes:[filename],
88
+ next:"Review the example and official authentication guide before running it. It has not been executed."},0];
89
+ } catch (err) {
90
+ return [{...diagnostic, action:"example", status:"blocked",
91
+ reason:err.code === "EEXIST" ? "example_already_exists" : "example_write_refused"},3];
92
+ }
93
+ }
94
+
95
+ export function main(argv) {
96
+ let target = process.cwd(), command = null, asJson = false, targetSeen = false;
97
+ for (let i=0;i<argv.length;i++) {
98
+ const a=argv[i];
99
+ if (a==="--json" && !asJson) {asJson=true;continue;}
100
+ if (a==="--target" && !targetSeen && i+1<argv.length && !argv[i+1].startsWith("-")) {
101
+ target=argv[++i];targetSeen=true;continue;
102
+ }
103
+ if (["doctor","example","--help","-h","--version"].includes(a) && command===null) {command=a;continue;}
104
+ console.error("Unknown or duplicate argument. Use --help.");return 2;
105
+ }
106
+ if (command===null || command==="--help" || command==="-h") {console.log(help);return 0;}
107
+ if (command==="--version") {console.log(profile().package_version);return 0;}
108
+ if (command==="example" && !targetSeen) {console.error("Example requires explicit --target DIR.");return 2;}
109
+ const [result,code]=command==="doctor" ? inspectProject(target) : createExample(target);
110
+ if (asJson) console.log(JSON.stringify(result));
111
+ else {
112
+ console.log("CMDOP Project Check: "+result.status);
113
+ console.log("Project: "+result.target);
114
+ console.log("SDK: "+result.sdk.status+(result.sdk.installed_version ? " ("+result.sdk.installed_version+")" : ""));
115
+ if(result.reason) console.log("Reason: "+result.reason);
116
+ if(result.changes.length) console.log("Created: "+result.changes.join(", "));
117
+ if(result.next) console.log(result.next);
118
+ if(result.suggested_command) console.log("Suggested (not executed): "+result.suggested_command.join(" "));
119
+ }
120
+ return code;
121
+ }
122
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
123
+ try {process.exitCode=main(process.argv.slice(2));}
124
+ catch {console.error("Project check could not complete safely.");process.exitCode=4;}
125
+ }