@cmdop/project-check 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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,25 @@
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
+ Offline Node.js utility for inspecting a project's CMDOP SDK metadata and creating the official SDK starter.
4
+
5
+ Requires Node 20+ and an npm-managed project. The reviewed SDK version is 3.6.1.
6
+
7
+ ## Usage
8
+
9
+ Install the utility in a separate tools project:
10
+
11
+ npm install --save-exact @cmdop/project-check@0.1.0
12
+
13
+ Use its installed command to inspect your application:
14
+
15
+ npx --no-install cmdop-project-check doctor --target /path/to/project
16
+ npx --no-install cmdop-project-check doctor --target /path/to/project --json
17
+ npx --no-install cmdop-project-check example --target /path/to/project
18
+
19
+ The doctor checks local runtime and package-manager prerequisites, declared SDK dependency and project-local SDK package metadata. A matching manifest does not verify SDK imports, code integrity, authentication or machine access. Linked SDK packages, pnpm/Yarn/workspace projects are not supported in this initial version.
20
+
21
+ If the SDK is absent, the doctor suggests installation of the official @cmdop/sdk; it never runs the command. The example command requires an explicit target with matching SDK metadata, creates cmdop-example.mjs exclusively and never runs it. Review the example and the [official SDK documentation](https://github.com/commandoperator/cmdop-sdk) before execution.
22
+
23
+ This is a first-party [CMDOP](https://cmdop.ai) utility. The archive contains readable utility sources and the SDK-owned starter, with its original MIT notice. No SDK library is bundled. No install hooks, runtime package installation, credential reads, network calls, usage analytics or machine connections. Diagnostics stay local.
24
+
25
+ License: MIT. See LICENSE and LICENSE-SDK.
@@ -0,0 +1,28 @@
1
+ {
2
+ "schema_version": 1,
3
+ "contract_version": "0.1.0",
4
+ "package_version": "0.1.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,27 @@
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": "0.1.0",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "description": "Offline local SDK project diagnostic and starter creator",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "bin": {
12
+ "cmdop-project-check": "runtime/node/project-check.mjs"
13
+ },
14
+ "files": [
15
+ "runtime/node/project-check.mjs",
16
+ "runtime/node/launcher.mjs",
17
+ "catalog/project-check.json",
18
+ "catalog/sdk-starters.json",
19
+ "README.md",
20
+ "LICENSE-SDK",
21
+ "LICENSE"
22
+ ],
23
+ "homepage": "https://cmdop.ai",
24
+ "publishConfig": {
25
+ "access": "public"
26
+ }
27
+ }
@@ -0,0 +1,340 @@
1
+ import { readFileSync, writeFileSync, readdirSync, statSync, 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
+ export function evaluate(action, options = {}, catalog = readCatalog(), context = runtimeFacts()) {
31
+ const result = { schema_version: 1, contract_version: catalog.contract_version,
32
+ requested_action: action, result: "success", error_category: null, message: "",
33
+ stages: Object.fromEntries(stageNames.map((name) => [name, "not_attempted"])),
34
+ changes: [], plan: null, diagnostics: catalog.revisions ? { revisions: structuredClone(catalog.revisions) } : {}, links: { ...catalog.links } };
35
+ const fail = (reason, message = reason, code = 3) => {
36
+ result.result = code === 2 || code === 4 ? "failed" : "blocked";
37
+ result.error_category = reason; result.message = message;
38
+ return [result, code];
39
+ };
40
+ if (action === "help") {
41
+ result.message = catalog.help_text;
42
+ return [result, 0];
43
+ }
44
+ if (action === "version") { result.message = catalog.package_version; return [result, 0]; }
45
+ if (action === "links") { result.stages.guide = "passed"; result.message = "Links are shown only; no browser was opened."; return [result, 0]; }
46
+ if (action === "explain") {
47
+ const messages = catalog.explanations;
48
+ const topic = options.topic ?? "product";
49
+ if (!Object.hasOwn(messages, topic)) return fail("usage", "Unknown explanation topic.", 2);
50
+ result.message = messages[topic]; result.stages.guide = "passed";
51
+ return [result, 0];
52
+ }
53
+ if (!["doctor", "sdk_plan", "sdk_setup"].includes(action)) return fail("usage", "Unknown action.", 2);
54
+ const language = options.language ?? context.native_language ?? "typescript";
55
+ if (!Object.hasOwn(catalog.compatibility, language)) return fail("usage", "Choose python or typescript.", 2);
56
+ const planning = action !== "doctor";
57
+ if (planning && (!options.target || !options.language)) return fail("usage", "SDK preview requires --target and --language.", 2);
58
+ const target = resolve(options.target ?? process.cwd());
59
+ const isNew = Boolean(options.new);
60
+ const blockers = [];
61
+ let names = [], packageJson = null;
62
+ if (directoryExists(target)) {
63
+ try { names = readdirSync(target); } catch { blockers.push("target_unreadable"); }
64
+ if (isNew && names.length) blockers.push("new_target_not_empty");
65
+ } else {
66
+ if (!isNew || fileExists(target)) blockers.push("target_not_directory");
67
+ }
68
+ let parent = target;
69
+ while (!directoryExists(parent) && dirname(parent) !== parent) parent = dirname(parent);
70
+ if (!writable(parent)) blockers.push("target_unwritable");
71
+ if (!blockers.length && names.includes("package.json")) {
72
+ try { packageJson = JSON.parse(readFileSync(join(target, "package.json"), "utf8")); if (!packageJson || typeof packageJson !== "object" || Array.isArray(packageJson) || Object.hasOwn(packageJson, "packageManager") && typeof packageJson.packageManager !== "string") throw Error(); }
73
+ catch { packageJson = null; blockers.push("invalid_manifest"); }
74
+ }
75
+ let manager = language === "typescript" ? "npm" : "pip";
76
+ 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));
77
+ if (locks.length > 1) blockers.push("project_conflict");
78
+ if (language === "typescript") {
79
+ if (locks.includes("pnpm-lock.yaml") || packageJson?.packageManager?.startsWith("pnpm@")) manager = "pnpm";
80
+ else if (locks.includes("yarn.lock") || packageJson?.packageManager?.startsWith("yarn@")) manager = "yarn";
81
+ else if (typeof packageJson?.packageManager === "string") manager = packageJson.packageManager.split("@")[0];
82
+ if (names.includes("pnpm-workspace.yaml")) manager = "pnpm";
83
+ if (packageJson && Object.hasOwn(packageJson, "workspaces")) blockers.push("project_conflict");
84
+ } else {
85
+ if (locks.includes("uv.lock")) manager = "uv";
86
+ else if (locks.includes("poetry.lock")) manager = "poetry";
87
+ }
88
+ if (!["npm", "pip"].includes(manager)) blockers.push("unsupported_project_manager");
89
+ const version = context.versions?.[language] ?? null;
90
+ const present = language === "python" ? context.executables?.python : context.executables?.node;
91
+ const spec = catalog.compatibility[language];
92
+ if (!present && !version) blockers.push("runtime_missing");
93
+ else if (!version) blockers.push("runtime_unverified");
94
+ else if (version[0] < spec.minimum_major || version[0] === spec.minimum_major && version[1] < spec.minimum_minor) blockers.push("runtime_unsupported");
95
+ if (language === "typescript" && manager === "npm" && !context.executables?.npm) blockers.push("manager_missing");
96
+ const pythonInVenv = context.platform === "win32" ? ".venv/Scripts/python.exe" : ".venv/bin/python";
97
+ if (planning && language === "python" && !isNew && !fileExists(join(target, pythonInVenv))) blockers.push("missing_project_venv");
98
+ 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 };
99
+ if (!["runtime_missing", "runtime_unverified", "runtime_unsupported"].some((reason) => blockers.includes(reason))) result.stages.runtime = "passed";
100
+ else result.stages.runtime = "blocked";
101
+ if (!planning) {
102
+ if (blockers.length) return fail(blockers[0], "Environment diagnostics found prerequisites: " + [...new Set(blockers)].join(", "));
103
+ result.message = "Local environment inspected. SDK import, authorization and machine access were not checked.";
104
+ return [result, 0];
105
+ }
106
+ blockers.push("sdk_baseline_pending");
107
+ const commands = language === "typescript"
108
+ ? [["npm", "install", "--save-exact", "@cmdop/sdk@<approved-version>"]]
109
+ : [...(isNew ? [["python3", "-m", "venv", ".venv"]] : []), [pythonInVenv, "-m", "pip", "install", "cmdop==<approved-version>"]];
110
+ result.plan = { language, target, mode: isNew ? "new" : "existing", manager,
111
+ package_name: spec.package_name, approved_version: null, commands,
112
+ files_may_change: language === "typescript" ? ["package.json", "package-lock.json", "node_modules"] : [...(isNew ? ["pyproject.toml"] : []), ".venv"],
113
+ install_enabled: false, blockers: [...new Set(blockers)] };
114
+ return fail(blockers[0], "Preview only. Nothing was installed or written. A verified SDK baseline and the install executor are not available yet.");
115
+ }
116
+
117
+ function parse(args) {
118
+ 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.");
119
+ const options = {}, positional = [];
120
+ let json = false, help = false, version = false;
121
+ for (let i = 0; i < args.length; i++) {
122
+ const arg = args[i];
123
+ if (arg === "--json") { json = true; continue; }
124
+ if (["--plain", "--no-color"].includes(arg)) continue;
125
+ if (arg === "--help" || arg === "-h") { help = true; continue; }
126
+ if (arg === "--version") { version = true; continue; }
127
+ if (arg === "--new") { options.new = true; continue; }
128
+ if (["--target", "--language"].includes(arg)) {
129
+ if (!args[i + 1] || args[i + 1].startsWith("--")) throw Error("Missing option value");
130
+ const key = arg.slice(2); if (Object.hasOwn(options, key)) throw Error("Duplicate option"); options[key] = args[++i]; continue;
131
+ }
132
+ if (arg.startsWith("-")) throw Error("Unknown option");
133
+ positional.push(arg);
134
+ }
135
+ if (help) return { action: "help", options: {}, json };
136
+ if (version) return { action: "version", options: {}, json };
137
+ if (!positional.length) return { action: "bare", options, json };
138
+ let action;
139
+ if (positional[0] === "sdk" && ["plan", "setup"].includes(positional[1]) && positional.length === 2) action = "sdk_" + positional[1];
140
+ else if (positional[0] === "doctor" && positional.length === 1) action = "doctor";
141
+ else if (positional[0] === "explain" && positional.length <= 2) { action = "explain"; options.topic = positional[1] ?? "product"; }
142
+ else if (["links", "help", "version"].includes(positional[0]) && positional.length === 1) action = positional[0];
143
+ else throw Error("Unknown command or extra arguments");
144
+ if (options.new && !["sdk_plan", "sdk_setup"].includes(action)) throw Error("--new is only valid for SDK preview");
145
+ if (["links", "explain", "help", "version"].includes(action) && (options.target || options.language)) throw Error("Unexpected project options");
146
+ return { action, options, json };
147
+ }
148
+ function render(result, json) {
149
+ if (json) { console.log(JSON.stringify(result)); return; }
150
+ console.log(result.message);
151
+ if (result.plan && !result.diagnostics?.plan_presented) console.log(JSON.stringify(result.plan, null, 2));
152
+ else if (result.requested_action === "doctor") console.log(JSON.stringify(result.diagnostics, null, 2));
153
+ else if (result.requested_action === "links") for (const [name, href] of Object.entries(result.links)) console.log(name + ": " + href);
154
+ }
155
+ export function writeSdkStarter(target, language) {
156
+ if (language !== "typescript") throw Error("Native starter language required.");
157
+ if (realpathSync(target) !== resolve(target) || !statSync(target).isDirectory()) throw Error("Target changed.");
158
+ const source = JSON.parse(readFileSync(join(root, "catalog/sdk-starters.json"), "utf8"));
159
+ const template = source.templates.typescript;
160
+ if (source.schema_version !== 1 || template.filename !== "cmdop-example.mjs"
161
+ || Buffer.byteLength(template.content) > 16384
162
+ || createHash("sha256").update(template.content).digest("hex") !== template.sha256) throw Error("Invalid SDK starter.");
163
+ writeFileSync(join(target, template.filename), template.content, { flag: "wx", mode: 0o644 });
164
+ return template.filename;
165
+ }
166
+
167
+ // Local setup acceptance is explicit imported API configuration, never an env/CLI override.
168
+ export async function runSdkSetup(action, options, catalog, baseline, { ask = null, write = console.log, signal } = {}) {
169
+ if (!["sdk_plan", "sdk_setup"].includes(action) || !baseline || options.language !== "typescript") return evaluate(action, options, catalog);
170
+ const [result] = evaluate("help", {}, catalog);
171
+ result.requested_action = action;
172
+ if (!options.target) {
173
+ Object.assign(result, { result: "failed", error_category: "usage", message: "SDK setup requires --target and --language." });
174
+ return [result, 2];
175
+ }
176
+ const { planSetup, executeSetup } = await import("./sdk-setup.mjs");
177
+ const plan = planSetup({ target: options.target, newProject: Boolean(options.new), baseline });
178
+ result.plan = plan;
179
+ result.diagnostics = { ...result.diagnostics, local_setup_candidate: true, install_enabled: plan.blockers.length === 0 };
180
+ if (plan.blockers.length) {
181
+ Object.assign(result, { result: "blocked", error_category: plan.blockers[0], message: "SDK setup prerequisites are not satisfied. Nothing was changed." });
182
+ return [result, 3];
183
+ }
184
+ result.stages.runtime = "passed";
185
+ if (action === "sdk_plan") {
186
+ result.message = "Reviewed local SDK candidate plan. Nothing was installed or written.";
187
+ return [result, 0];
188
+ }
189
+ if (typeof ask !== "function") {
190
+ Object.assign(result, { result: "blocked", error_category: "confirmation_required", message: "Review this plan in a terminal and explicitly confirm installation." });
191
+ return [result, 3];
192
+ }
193
+ write("Local SDK candidate: the package manager may resolve dependencies. This does not connect a machine.");
194
+ write(JSON.stringify(plan, null, 2));
195
+ result.diagnostics.plan_presented = true;
196
+ let confirmed = false;
197
+ try { confirmed = (await ask("Install this SDK in the project? Type yes [Back]: ")).trim().toLowerCase() === "yes"; }
198
+ catch { /* EOF/cancellation never confirms a plan. */ }
199
+ const execution = await executeSetup(plan, { confirmed, signal });
200
+ result.result = execution.status;
201
+ result.error_category = execution.error_category ?? null;
202
+ result.message = execution.message ?? execution.recovery ?? "SDK setup completed. Follow the official connection guide when ready.";
203
+ result.changes = execution.changes ?? [];
204
+ Object.assign(result.stages, execution.stages ?? {});
205
+ result.diagnostics.installed_version = execution.installed_version ?? null;
206
+ if (execution.exit_code === 0) {
207
+ write("SDK import checked. No authorization or machine access was performed.");
208
+ let starter = false;
209
+ try { starter = (await ask("Create the SDK example file without running it? Type yes [Back]: ")).trim().toLowerCase() === "yes"; } catch {}
210
+ if (signal?.aborted) {
211
+ result.result = "cancelled"; result.error_category = "cancelled";
212
+ result.message = "Cancelled after SDK installation/import. Existing project changes are retained.";
213
+ return [result, 130];
214
+ }
215
+ if (starter) {
216
+ try {
217
+ const filename = writeSdkStarter(plan.target, "typescript");
218
+ result.changes.push(filename); result.stages.starter = "written";
219
+ write("Created " + filename + ". It connects only when you run it after configuring CMDOP. " + catalog.links.sdk);
220
+ } catch {
221
+ result.result = "blocked"; result.error_category = "starter_not_written"; result.stages.starter = "blocked";
222
+ result.message = "SDK installed and imported. The example was not written; existing files are preserved.";
223
+ return [result, 3];
224
+ }
225
+ }
226
+ }
227
+ return [result, execution.exit_code];
228
+ }
229
+
230
+ export async function menu(catalog, observationSession = null, createMenuInterface = createInterface, setupBaseline = null) {
231
+ const rl = createMenuInterface({ input: process.stdin, output: process.stdout });
232
+ const observe = (method, ...args) => { try { observationSession?.[method](...args); } catch {} };
233
+ // readline.close() leaves an outstanding question unresolved. Settle it on
234
+ // actual EOF/SIGINT as well, so cleanup and the useful exit status still run.
235
+ const closed = Symbol("readline closed");
236
+ const didClose = new Promise(resolve => rl.on("close", () => resolve(closed)));
237
+ const question = async prompt => {
238
+ const value = await Promise.race([rl.question(prompt), didClose]);
239
+ if (value === closed) throw Object.assign(Error("Terminal input closed."), { code: "ERR_USE_AFTER_CLOSE" });
240
+ return value;
241
+ };
242
+ let cancelled = false;
243
+ const setupAbort = new AbortController();
244
+ let pendingCode = 0;
245
+ const exitChoice = catalog.menu.findIndex((item) => item.id === "exit") + 1;
246
+ const interrupt = () => { cancelled = true; setupAbort.abort(); rl.close(); };
247
+ rl.on("SIGINT", interrupt);
248
+ process.on("SIGINT", interrupt);
249
+ try {
250
+ while (!cancelled) {
251
+ 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."));
252
+ catalog.menu.forEach((item, i) => console.log(String(i + 1) + ". " + (setupBaseline && item.id === "sdk" ? "Set up SDK for my project" : item.label)));
253
+ let choice;
254
+ try { choice = await question("Choose an option [" + exitChoice + "]: "); } catch { break; }
255
+ const item = catalog.menu[(Number(choice || exitChoice) || 0) - 1];
256
+ if (!item) { console.log("Choose a number from 1 to " + catalog.menu.length + "."); continue; }
257
+ observe("action", item.id);
258
+ if (item.id === "exit") {
259
+ if (!cancelled && observationSession) {
260
+ try { await observationSession.finish({ code: pendingCode,
261
+ ask: (prompt) => question(prompt), write: (message) => console.log(message) }); } catch {}
262
+ }
263
+ return cancelled ? 130 : pendingCode;
264
+ }
265
+ if (item.id === "sdk") {
266
+ const language = (await question("Language [typescript/python]: ")).trim() || "typescript";
267
+ const target = (await question("Project directory: ")).trim();
268
+ let options = { language, target };
269
+ if (setupBaseline && language === "typescript") options.new = (await question("Create a new project? Type yes [existing]: ")).trim().toLowerCase() === "yes";
270
+ const [result, code] = setupBaseline
271
+ ? await runSdkSetup("sdk_setup", options, catalog, setupBaseline, { ask: question, signal: setupAbort.signal })
272
+ : evaluate("sdk_plan", options, catalog);
273
+ observe("outcome", item.id, result);
274
+ if (code === 130 && result.error_category !== "confirmation_required") {
275
+ render(result, false);
276
+ return 130;
277
+ }
278
+ if (code && code !== 130) pendingCode = code;
279
+ render(result, false);
280
+ } else if (item.id === "doctor") {
281
+ const [result, code] = evaluate("doctor", {}, catalog); observe("outcome", item.id, result); if (code) pendingCode = code; render(result, false);
282
+ } else if (item.id === "website") console.log(catalog.links.product);
283
+ 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]); }
284
+ }
285
+ } catch (error) { if (!cancelled && error.code !== "ERR_USE_AFTER_CLOSE") throw error; }
286
+ finally { process.removeListener("SIGINT", interrupt); observe("discard"); rl.close(); }
287
+ return cancelled ? 130 : pendingCode;
288
+ }
289
+ export async function main(args, { observationSession = null, createObservationSession = null,
290
+ createMenuInterface = createInterface, setupBaseline = null } = {}) {
291
+ const catalog = readCatalog();
292
+ let command;
293
+ try { command = parse(args); }
294
+ catch (error) {
295
+ const [result] = evaluate("help", {}, catalog);
296
+ result.requested_action = "usage"; result.result = "failed"; result.error_category = "usage"; result.message = error.message;
297
+ render(result, args.includes("--json")); return 2;
298
+ }
299
+ if (command.action === "bare") {
300
+ if (Object.keys(command.options).length) { const [result] = evaluate("unknown", {}, catalog); render(result, command.json); return 2; }
301
+ if (!command.json && process.stdin.isTTY && process.stdout.isTTY) {
302
+ if (observationSession == null && typeof createObservationSession === "function"
303
+ && process.env.DO_NOT_TRACK !== "1") {
304
+ // Loading an optional shared client cannot prevent useful CLI behavior.
305
+ try { observationSession = await createObservationSession(); } catch { observationSession = null; }
306
+ }
307
+ return menu(catalog, observationSession, createMenuInterface, setupBaseline);
308
+ }
309
+ command.action = "help";
310
+ }
311
+ if (setupBaseline && ["sdk_plan", "sdk_setup"].includes(command.action)) {
312
+ let rl = null;
313
+ const controller = new AbortController();
314
+ const interrupt = () => { controller.abort(); rl?.close(); };
315
+ try {
316
+ let ask = null;
317
+ if (command.action === "sdk_setup" && !command.json && process.stdin.isTTY && process.stdout.isTTY) {
318
+ rl = createMenuInterface({ input: process.stdin, output: process.stdout });
319
+ const closed = Symbol("setup input closed");
320
+ const didClose = new Promise(resolve => rl.on("close", () => resolve(closed)));
321
+ rl.on("SIGINT", interrupt);
322
+ process.on("SIGINT", interrupt);
323
+ ask = async prompt => {
324
+ const answer = await Promise.race([rl.question(prompt), didClose]);
325
+ if (answer === closed) throw Error("Setup input closed.");
326
+ return answer;
327
+ };
328
+ }
329
+ const [result, code] = await runSdkSetup(command.action, command.options, catalog, setupBaseline,
330
+ { ask, signal: controller.signal });
331
+ render(result, command.json); return code;
332
+ } finally { process.removeListener("SIGINT", interrupt); rl?.close(); }
333
+ }
334
+ const [result, code] = evaluate(command.action, command.options, catalog);
335
+ render(result, command.json); return code;
336
+ }
337
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
338
+ try { process.exitCode = await main(process.argv.slice(2)); } catch { console.error("Launcher inspection failed."); process.exitCode = 4; }
339
+ }
340
+
@@ -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
+ }