|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `os doctor` never prescribes a command `os` does not register (#10680). |
| 5 | + * |
| 6 | + * ── The defect ─────────────────────────────────────────────────────────── |
| 7 | + * |
| 8 | + * After `--scan-deprecations` reported its hits, doctor printed: |
| 9 | + * |
| 10 | + * ℹ Found N deprecated pattern(s). Run `objectstack codemod v2-to-v3` to auto-fix. |
| 11 | + * |
| 12 | + * There is no `codemod` command. oclif resolves this CLI's commands by |
| 13 | + * globbing `dist/commands/**` (`package.json` → `oclif.commands`, pattern |
| 14 | + * strategy); nothing under `src/commands/` compiles to `codemod`, and neither |
| 15 | + * bundled plugin (`@oclif/plugin-help`, `@oclif/plugin-plugins`) supplies one. |
| 16 | + * An operator who followed the prescription got oclif's exit 2, |
| 17 | + * `command codemod:v2-to-v3 not found` — after spending their time on it. |
| 18 | + * `content/docs/protocol/backward-compatibility.mdx` already recorded the |
| 19 | + * automated codemod as "not yet available"; the tool was the last place still |
| 20 | + * claiming otherwise. |
| 21 | + * |
| 22 | + * This is the same class as the two defects fixed next door: `os doctor` |
| 23 | + * printing `✓` over a tree it never walked (#10679) and `os datasource |
| 24 | + * validate` passing over drift it never read. A tool that speaks with |
| 25 | + * confidence about work it cannot do costs the reader their time before they |
| 26 | + * can find out — and a WRONG prescription costs more than no prescription. |
| 27 | + * |
| 28 | + * ── Why the hint was removed rather than repointed ─────────────────────── |
| 29 | + * |
| 30 | + * The obvious repair — point it at `os migrate meta`, the registered metadata |
| 31 | + * migrator — would have been the same defect respelled, so it is deliberately |
| 32 | + * NOT what landed: |
| 33 | + * |
| 34 | + * · `os migrate meta`'s subject is an authored stack CONFIG replayed across |
| 35 | + * protocol majors. Its own header declines the rewrite this hint promises: |
| 36 | + * it "does not silently rewrite TS config source (that AST rewrite is |
| 37 | + * unsafe and lossy)". Both of its writes are `--out` JSON snapshots, and |
| 38 | + * `--from` is required, so a bare `os migrate meta` fails too. It cannot |
| 39 | + * touch the `src/**` TypeScript the scan reports on, and three of the |
| 40 | + * eight DEPRECATED_PATTERNS (`EnhancedObjectKernel` and the two |
| 41 | + * deep-import paths) are not metadata at all. |
| 42 | + * · `os lint --fix` is print-only by declaration: "Show what would be fixed |
| 43 | + * (dry-run)". |
| 44 | + * |
| 45 | + * Nothing registered does the job, so the line says nothing about a codemod |
| 46 | + * and points at the replacement it already computed for each finding instead. |
| 47 | + * |
| 48 | + * ── What this file pins ────────────────────────────────────────────────── |
| 49 | + * |
| 50 | + * The first describe closes the CLASS, not the instance: EVERY `os …` / |
| 51 | + * `objectstack …` hint doctor can print must name a command that resolves |
| 52 | + * under `src/commands/`. It fails on the shipped defect (that hint was the |
| 53 | + * only unresolvable one of the six in the file) and on any future one. The |
| 54 | + * rest drive the real command and pin both the corrected line and the scan |
| 55 | + * clauses that were already correct and must stay that way. |
| 56 | + */ |
| 57 | + |
| 58 | +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; |
| 59 | +import fs from 'node:fs'; |
| 60 | +import os from 'node:os'; |
| 61 | +import path from 'node:path'; |
| 62 | +import { fileURLToPath } from 'node:url'; |
| 63 | + |
| 64 | +import Doctor from './doctor.js'; |
| 65 | + |
| 66 | +const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 67 | +/** `packages/cli/src/commands` — where oclif's pattern strategy finds commands. */ |
| 68 | +const COMMANDS_DIR = HERE; |
| 69 | +/** `packages/cli` — the oclif root the real command is loaded against below. */ |
| 70 | +const CLI_ROOT = path.resolve(HERE, '..', '..'); |
| 71 | +const DOCTOR_SRC = path.join(COMMANDS_DIR, 'doctor.ts'); |
| 72 | + |
| 73 | +/** |
| 74 | + * chalk may or may not emit SGR codes depending on TTY detection. |
| 75 | + * |
| 76 | + * The escape is written as `\x1b`, never as the byte itself: one raw control |
| 77 | + * character makes `grep` treat the whole file as binary, and a test file no |
| 78 | + * `git grep` can find stops being maintained. |
| 79 | + */ |
| 80 | +const SGR = /\x1b\[[0-9;]*m/g; |
| 81 | +const plain = (s: string) => s.replace(SGR, ''); |
| 82 | + |
| 83 | +/** |
| 84 | + * Every backticked `os …` / `objectstack …` hint in a blob of text. |
| 85 | + * |
| 86 | + * Reads the raw source as well as rendered output, so the escaped backticks a |
| 87 | + * template literal carries (`` \` ``) are tolerated on both ends. |
| 88 | + */ |
| 89 | +function commandHintsIn(text: string): string[] { |
| 90 | + const hints: string[] = []; |
| 91 | + const re = /\\?`(os|objectstack)\s+([^`\n]*?)\\?`/g; |
| 92 | + for (const m of text.matchAll(re)) hints.push(`${m[1]} ${m[2]}`.trim()); |
| 93 | + return hints; |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * The command words of a hint: everything up to the first flag or placeholder. |
| 98 | + * |
| 99 | + * `os migrate meta --stored` addresses the command `migrate meta`; the flags |
| 100 | + * are that command's business, not the registry's. |
| 101 | + */ |
| 102 | +function commandWords(hint: string): string[] { |
| 103 | + const words = hint.split(/\s+/).slice(1); |
| 104 | + const out: string[] = []; |
| 105 | + for (const w of words) { |
| 106 | + if (!/^[a-z][a-z0-9-]*$/.test(w)) break; |
| 107 | + out.push(w); |
| 108 | + } |
| 109 | + return out; |
| 110 | +} |
| 111 | + |
| 112 | +/** |
| 113 | + * The file oclif would load for a hint, or `null` when nothing registers it. |
| 114 | + * |
| 115 | + * Longest prefix wins, mirroring oclif's topic resolution: `os migrate plan` |
| 116 | + * is `migrate/plan.ts`, `os serve` is `serve.ts`. |
| 117 | + */ |
| 118 | +function resolveCommand(hint: string): string | null { |
| 119 | + const words = commandWords(hint); |
| 120 | + for (let k = words.length; k > 0; k--) { |
| 121 | + const stem = path.join(COMMANDS_DIR, ...words.slice(0, k)); |
| 122 | + for (const candidate of [`${stem}.ts`, path.join(stem, 'index.ts')]) { |
| 123 | + if (fs.existsSync(candidate)) return candidate; |
| 124 | + } |
| 125 | + } |
| 126 | + return null; |
| 127 | +} |
| 128 | + |
| 129 | +function unregisteredHintsIn(text: string): string[] { |
| 130 | + return [...new Set(commandHintsIn(text))].filter((h) => resolveCommand(h) === null); |
| 131 | +} |
| 132 | + |
| 133 | +/** |
| 134 | + * The source with its comment lines removed — what doctor can actually PRINT. |
| 135 | + * |
| 136 | + * The rule this file enforces is about the report an operator reads, so a |
| 137 | + * command named in a comment (the print site documents the dead prescription |
| 138 | + * it replaced, verbatim) is prose, not a prescription. Only whole comment |
| 139 | + * lines are dropped, never a trailing `//`: `http://localhost:3000` lives |
| 140 | + * inside these strings, and a regex greedy enough to strip after it would |
| 141 | + * silently delete real hints and leave the sweep below passing over less than |
| 142 | + * it claims. |
| 143 | + */ |
| 144 | +function printableSource(src: string): string { |
| 145 | + return src |
| 146 | + .split('\n') |
| 147 | + .filter((line) => !/^\s*(\/\/|\/\*|\*)/.test(line)) |
| 148 | + .join('\n'); |
| 149 | +} |
| 150 | + |
| 151 | +describe('resolveCommand — the registry probe these cases are judged with', () => { |
| 152 | + // A probe that cannot fail proves nothing about the source it clears, so it |
| 153 | + // is exercised on both verdicts before being trusted below. |
| 154 | + it('resolves a real command, including a topic command', () => { |
| 155 | + expect(resolveCommand('os serve')).toBe(path.join(COMMANDS_DIR, 'serve.ts')); |
| 156 | + expect(resolveCommand('os migrate meta')).toBe(path.join(COMMANDS_DIR, 'migrate', 'meta.ts')); |
| 157 | + }); |
| 158 | + |
| 159 | + it('refuses the exact prescription this issue is about', () => { |
| 160 | + expect(resolveCommand('objectstack codemod v2-to-v3')).toBeNull(); |
| 161 | + // …and is not merely rejecting the version suffix. |
| 162 | + expect(resolveCommand('os codemod')).toBeNull(); |
| 163 | + }); |
| 164 | + |
| 165 | + it('addresses the command, not its flags', () => { |
| 166 | + expect(resolveCommand('os migrate meta --stored --apply')).toBe( |
| 167 | + path.join(COMMANDS_DIR, 'migrate', 'meta.ts'), |
| 168 | + ); |
| 169 | + expect(resolveCommand('os doctor --scan-deprecations')).toBe(path.join(COMMANDS_DIR, 'doctor.ts')); |
| 170 | + }); |
| 171 | +}); |
| 172 | + |
| 173 | +describe('doctor.ts source — no phantom prescriptions anywhere in the file', () => { |
| 174 | + const printable = printableSource(fs.readFileSync(DOCTOR_SRC, 'utf8')); |
| 175 | + |
| 176 | + it('names only commands `os` registers', () => { |
| 177 | + // The class-closing assertion. Before the fix this listed exactly one |
| 178 | + // entry, `objectstack codemod v2-to-v3`; it must stay empty. |
| 179 | + expect(unregisteredHintsIn(printable)).toEqual([]); |
| 180 | + }); |
| 181 | + |
| 182 | + it('finds enough hints for the sweep above to mean something', () => { |
| 183 | + // Guards the assertion against a haystack that quietly emptied — a regex |
| 184 | + // that stops matching, or a comment filter that ate the code with the |
| 185 | + // comments. Either would make the case above pass over nothing at all. |
| 186 | + expect(commandHintsIn(printable).length).toBeGreaterThan(10); |
| 187 | + }); |
| 188 | + |
| 189 | + it('has dropped the dead codemod prescription outright', () => { |
| 190 | + // The print site still documents the dead command in a comment, on |
| 191 | + // purpose — that is the record of why this line reads as it does. What |
| 192 | + // must not survive is the prescription reaching an operator's screen. |
| 193 | + // (The word itself does survive, in the sentence that reports there is no |
| 194 | + // codemod; banning the word would ban saying so.) |
| 195 | + expect(printable).not.toContain('codemod v2-to-v3'); |
| 196 | + expect(printable).not.toContain('os codemod'); |
| 197 | + // Not repointed at `os migrate meta` either: that command declines the TS |
| 198 | + // rewrite this hint promised, so prescribing it would restate the defect. |
| 199 | + expect(printable).not.toContain('migrate meta'); |
| 200 | + }); |
| 201 | +}); |
| 202 | + |
| 203 | +/** |
| 204 | + * `node_modules/` exists in every temp cwd on purpose — without it doctor's |
| 205 | + * `Dependencies` check is itself an `error` and exits 1 on its own, which |
| 206 | + * would make an assertion pass for a reason having nothing to do with this |
| 207 | + * change. |
| 208 | + */ |
| 209 | +function makeTempCwd(tag: string): string { |
| 210 | + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `os-doctor-10680-${tag}-`)); |
| 211 | + fs.mkdirSync(path.join(dir, 'node_modules')); |
| 212 | + fs.mkdirSync(path.join(dir, 'src')); |
| 213 | + return dir; |
| 214 | +} |
| 215 | + |
| 216 | +describe('os doctor --scan-deprecations, end to end', () => { |
| 217 | + let tmp: string; |
| 218 | + let cwdSpy: ReturnType<typeof vi.spyOn>; |
| 219 | + |
| 220 | + beforeEach(() => { |
| 221 | + tmp = makeTempCwd('scan'); |
| 222 | + cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(tmp); |
| 223 | + }); |
| 224 | + |
| 225 | + afterEach(() => { |
| 226 | + cwdSpy.mockRestore(); |
| 227 | + fs.rmSync(tmp, { recursive: true, force: true }); |
| 228 | + }); |
| 229 | + |
| 230 | + function writeDeprecatedSource(): void { |
| 231 | + fs.writeFileSync( |
| 232 | + path.join(tmp, 'src', 'legacy.ts'), |
| 233 | + [ |
| 234 | + "import { EnhancedObjectKernel } from '@objectstack/core/enhanced';", |
| 235 | + 'export const field = { max_length: 40 };', |
| 236 | + '', |
| 237 | + ].join('\n'), |
| 238 | + 'utf8', |
| 239 | + ); |
| 240 | + } |
| 241 | + |
| 242 | + async function runDoctor(argv: string[]): Promise<{ out: string; exitCode: number | undefined }> { |
| 243 | + const logs: string[] = []; |
| 244 | + const logSpy = vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => { |
| 245 | + logs.push(a.join(' ')); |
| 246 | + }); |
| 247 | + let exitCode: number | undefined; |
| 248 | + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { |
| 249 | + exitCode = code; |
| 250 | + throw new Error(`__PROCESS_EXIT__:${code}`); |
| 251 | + }) as never); |
| 252 | + |
| 253 | + try { |
| 254 | + await Doctor.run(argv, { root: CLI_ROOT }); |
| 255 | + } catch (err) { |
| 256 | + if (!(err instanceof Error) || !err.message.startsWith('__PROCESS_EXIT__')) throw err; |
| 257 | + } finally { |
| 258 | + logSpy.mockRestore(); |
| 259 | + exitSpy.mockRestore(); |
| 260 | + } |
| 261 | + return { out: plain(logs.join('\n')), exitCode }; |
| 262 | + } |
| 263 | + |
| 264 | + // A real `Doctor.run()` takes seconds (it shells out to `git --version`, |
| 265 | + // walks the workspace and reads the ledger), so every case carries an |
| 266 | + // explicit timeout instead of racing vitest's 5s default. |
| 267 | + const E2E_TIMEOUT = 60_000; |
| 268 | + |
| 269 | + it('prescribes no codemod, and nothing else `os` cannot run', async () => { |
| 270 | + writeDeprecatedSource(); |
| 271 | + const run = await runDoctor(['--scan-deprecations']); |
| 272 | + |
| 273 | + // ① THE assertion of this issue. |
| 274 | + expect(run.out).not.toContain('codemod v2-to-v3'); |
| 275 | + expect(run.out).not.toContain('to auto-fix'); |
| 276 | + |
| 277 | + // ② …and the whole report is held to the same rule, not just this line. |
| 278 | + expect(unregisteredHintsIn(run.out)).toEqual([]); |
| 279 | + }, E2E_TIMEOUT); |
| 280 | + |
| 281 | + it('still reports the count, and says plainly that no codemod exists', async () => { |
| 282 | + writeDeprecatedSource(); |
| 283 | + const run = await runDoctor(['--scan-deprecations']); |
| 284 | + |
| 285 | + // Removing a false prescription must not remove the finding's summary — |
| 286 | + // silence about the count would trade one defect for a smaller one. |
| 287 | + // 3, not 2: line 1 trips both `EnhancedObjectKernel` and the |
| 288 | + // `@objectstack/core/enhanced` import pattern. Pinning the real number |
| 289 | + // keeps this honest about what the scanner reports. |
| 290 | + expect(run.out).toContain('Found 3 deprecated pattern(s).'); |
| 291 | + expect(run.out).toContain('No automated codemod ships with the CLI'); |
| 292 | + // The remedy it points at is one that exists: the per-finding replacement, |
| 293 | + // reachable by a flag this command really declares. |
| 294 | + expect(run.out).toContain('re-run with --verbose to print them'); |
| 295 | + }, E2E_TIMEOUT); |
| 296 | + |
| 297 | + it('drops the re-run advice once --verbose is already on', async () => { |
| 298 | + writeDeprecatedSource(); |
| 299 | + const run = await runDoctor(['--scan-deprecations', '--verbose']); |
| 300 | + |
| 301 | + expect(run.out).toContain('No automated codemod ships with the CLI'); |
| 302 | + expect(run.out).not.toContain('re-run with --verbose'); |
| 303 | + // The thing it now points at is on screen: the → replacement per finding. |
| 304 | + expect(run.out).toContain('Use maxLength (camelCase)'); |
| 305 | + expect(run.out).toContain("Use import from '@objectstack/core'"); |
| 306 | + }, E2E_TIMEOUT); |
| 307 | + |
| 308 | + it('keeps file:line attribution for every hit', async () => { |
| 309 | + // A passing clause of the QA item — pinned here so this edit cannot be the |
| 310 | + // thing that regresses it. |
| 311 | + writeDeprecatedSource(); |
| 312 | + const run = await runDoctor(['--scan-deprecations']); |
| 313 | + |
| 314 | + expect(run.out).toContain('legacy.ts:1'); |
| 315 | + expect(run.out).toContain('legacy.ts:2'); |
| 316 | + expect(run.out).toContain('snake_case config key: max_length'); |
| 317 | + }, E2E_TIMEOUT); |
| 318 | + |
| 319 | + it('still warns rather than gates — hits do not change the exit code', async () => { |
| 320 | + // The other passing clause: the scan is advisory. Measured as a DELTA |
| 321 | + // against the same cwd with a clean `src/`, so an unrelated finding in the |
| 322 | + // temp cwd cannot make this pass or fail for the wrong reason. |
| 323 | + const clean = await runDoctor(['--scan-deprecations']); |
| 324 | + writeDeprecatedSource(); |
| 325 | + const dirty = await runDoctor(['--scan-deprecations']); |
| 326 | + |
| 327 | + expect(clean.out).toContain('No deprecated patterns found'); |
| 328 | + expect(dirty.exitCode).toBe(clean.exitCode); |
| 329 | + expect(dirty.exitCode).not.toBe(1); |
| 330 | + }, E2E_TIMEOUT); |
| 331 | + |
| 332 | + it('says nothing about codemods when the tree is clean', async () => { |
| 333 | + const run = await runDoctor(['--scan-deprecations']); |
| 334 | + |
| 335 | + expect(run.out).toContain('No deprecated patterns found'); |
| 336 | + expect(run.out).not.toContain('No automated codemod ships with the CLI'); |
| 337 | + }, E2E_TIMEOUT); |
| 338 | +}); |
0 commit comments