Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/22249-doctor-env-files-loader.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/cli': patch
---

fix(cli): in the source checkout `os dev` serves, `os doctor`'s `Environment files` row names `os serve` / `os start` as the loaders of the `node_env=production` cascade it reports (#22249)

Clause-②: no

- **What changed.** With an `objectstack.config.ts` that boots as itself (alone, or beside its own compiled `dist/objectstack.json`), the `Environment files` row now says whose `.env*` cascade it resolved. A freshly scaffolded project with no `.env*` file reads ``✓ Environment files No .env* files here (node_env=production, the cascade `os serve` / `os start` load) — environment read from this process only — no environment input set``. When files are loaded, the row reads ``.env, … (node_env=production), the cascade `os serve` / `os start` load`` where it used to end ``the cascade `os serve` loads``. Before, the no-file form named no loader at all. That left `node_env=production` sitting directly above the `NODE_ENV` row that says `os dev` runs the project as development.
- **What did not change.** Doctor still resolves the cascade exactly as `os serve` does, for `NODE_ENV || 'production'`. So it reads the same `.env*` files and every env-derived verdict, the tenancy-posture refusal among them, is unchanged in every posture. Outside the source checkout, the row is unchanged byte for byte. That covers an artifact-only project, a config beside `OS_ARTIFACT_URL` or beside an `OS_ARTIFACT_PATH` naming another artifact, and a directory with neither. Doctor's exit code is unchanged.
147 changes: 146 additions & 1 deletion packages/cli/src/commands/doctor-node-env-default.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@
* `#22163` blocks pin the posture itself and the row it selects. The new row's
* wording is pinned only by the subjects it names (`os dev`, `os start`) and by
* the production sentence being absent.
*
* ── #22249: the `Environment files` row above it, in the same posture ────
*
* #5387's ruling stands — doctor resolves the `.env*` cascade exactly as
* `os serve` does, so that row still says `node_env=production` beside a
* config `os dev` serves. In that posture only, it now names whose cascade
* that is: `os serve` / `os start`. The `#22249` blocks pin the subjects it
* names, that the cascade it reports did not move (the production file is
* read, the development one is not), and — the control — that outside the
* posture the row is the one every caller got before, field for field.
*/

import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
Expand All @@ -55,7 +65,13 @@ import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import Doctor, { nodeEnvCheck, nodeEnvSourcePosture, doctorNodeEnv } from './doctor.js';
import Doctor, {
nodeEnvCheck,
nodeEnvSourcePosture,
doctorNodeEnv,
environmentSourcesCheck,
readDotenvFiles,
} from './doctor.js';

/** `packages/cli` — the oclif root the real command is loaded against below. */
const CLI_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
Expand Down Expand Up @@ -230,6 +246,60 @@ describe('[#22163] nodeEnvSourcePosture — the source checkout `os dev` serves'
});
});

describe('[#22249] environmentSourcesCheck — in the source posture the row names its loaders', () => {
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'os-doctor-22249-'));
});
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});

const NO_ENV = {} as NodeJS.ProcessEnv;
/**
* The cascade the run resolves for an unset `NODE_ENV`, in both of the row's
* shapes: nothing in it (the freshly scaffolded project), or a file in it.
*/
const SHAPES = ['no .env* file', 'a .env file'] as const;
const readingFor = (shape: (typeof SHAPES)[number]) => {
if (shape === 'a .env file') fs.writeFileSync(path.join(dir, '.env'), 'OS_TENANCY_POSTURE=isolated\n');
return readDotenvFiles(dir, doctorNodeEnv(NO_ENV));
};

it.each(SHAPES)('in the source posture (%s): `os serve` and `os start`, beside node_env=production', (shape) => {
const check = environmentSourcesCheck(readingFor(shape), NO_ENV, { sourcePosture: true });

expect(check.status).toBe('ok');
const message = plain(check.message);
expect(message).toContain('node_env=production');
expect(message).toContain('os serve');
expect(message).toContain('os start');
});

it.each(SHAPES)('outside it (%s): the row every caller got before, field for field', (shape) => {
// The default IS "outside": a caller that never asked about the posture
// keeps the row it always had. Same shape as #22163's pin on nodeEnvCheck.
const reading = readingFor(shape);
const explicit = environmentSourcesCheck(reading, NO_ENV, { sourcePosture: false });

expect(explicit).toEqual(environmentSourcesCheck(reading, NO_ENV));
expect(plain(explicit.message)).toContain('node_env=production');
expect(plain(explicit.message)).not.toContain('os start');
});

it.each(SHAPES)('the posture moves the wording only — verdict, detail and attribution stay (%s)', (shape) => {
const reading = readingFor(shape);
const source = environmentSourcesCheck(reading, NO_ENV, { sourcePosture: true });
const other = environmentSourcesCheck(reading, NO_ENV, { sourcePosture: false });

expect(source.status).toBe(other.status);
expect(source.fix).toBe(other.fix);
// The provenance clause closes the message in both postures, unchanged.
const attribution = other.message.slice(other.message.lastIndexOf(' — '));
expect(source.message.endsWith(attribution)).toBe(true);
});
});

describe('[#5673] os doctor, end to end — the row reaches the report', () => {
/**
* `node_modules/` exists in the temp cwd on purpose — without it doctor's
Expand Down Expand Up @@ -295,6 +365,36 @@ describe('[#5673] os doctor, end to end — the row reaches the report', () => {
expect(run.out).toContain('Environment is functional');
}, E2E_TIMEOUT);

/** The report rows whose name column is `Environment files`. */
const envFilesRows = (out: string) =>
out.split('\n').filter((line) => /^\s*\S+\s+Environment files {2,}/.test(line));
/**
* The row as every caller got it before #22249 — the posture-less call, which
* the unit block above pins equal to `{ sourcePosture: false }` field for
* field — for the cascade this run resolved.
*/
const unchangedRow = () =>
environmentSourcesCheck(readDotenvFiles(tmp, doctorNodeEnv()), process.env).message;

// ── #22249 controls: outside the source posture the row does not move ──
it.each([
['an empty project directory', () => {}],
['an artifact-only project (no config)', () => {
fs.mkdirSync(path.join(tmp, 'dist'));
fs.writeFileSync(path.join(tmp, 'dist', 'objectstack.json'), '{}\n');
}],
] as const)('[#22249] %s: the Environment files row is the unchanged one', async (_label, arrange) => {
delete process.env.NODE_ENV;
arrange();

const run = await runDoctor();

const rows = envFilesRows(run.out);
expect(rows).toHaveLength(1);
expect(rows[0].endsWith(unchangedRow())).toBe(true);
expect(rows[0]).not.toContain('os start');
}, E2E_TIMEOUT);

// Both directions, because "no row" has to hold for the environment that
// agrees with the default as well as for the one that contradicts it: the row
// reports that a DEFAULT was taken, not that the mode is production.
Expand Down Expand Up @@ -413,5 +513,50 @@ describe('[#5673] os doctor, end to end — the row reaches the report', () => {
expect(run.exitCode).toBeUndefined();
}
}, E2E_TIMEOUT * 2);

// ── #22249 — the `Environment files` row above, in the same posture ──

it('(f) [#22249] the freshly scaffolded project: the sources row names `os serve` / `os start`', async () => {
delete process.env.NODE_ENV;

const run = await runDoctor();

const rows = envFilesRows(run.out);
expect(rows).toHaveLength(1);
expect(rows[0]).toContain('node_env=production');
expect(rows[0]).toContain('os serve');
expect(rows[0]).toContain('os start');
// …directly above #22163's row, which still names `os dev`.
expect(nodeEnvRows(run.out)[0]).toContain('os dev');
}, E2E_TIMEOUT);

it('(g) [#22249] …and the cascade it names did not move: the production file is read, the development one is not', async () => {
delete process.env.NODE_ENV;
// Comment-only files: present in a cascade, contributing no variable, so
// nothing but the file list can tell the two cascades apart here.
fs.writeFileSync(path.join(tmp, '.env.production'), '# production cascade\n');
fs.writeFileSync(path.join(tmp, '.env.development'), '# development cascade\n');

const run = await runDoctor();

const rows = envFilesRows(run.out);
expect(rows).toHaveLength(1);
expect(rows[0]).toContain('.env.production');
expect(rows[0]).not.toContain('.env.development');
expect(rows[0]).toContain('node_env=production');
expect(rows[0]).toContain('os start');
}, E2E_TIMEOUT);

it('(h) [#22249] a config beside a NAMED artifact is outside the posture: the unchanged sources row', async () => {
delete process.env.NODE_ENV;
process.env.OS_ARTIFACT_PATH = path.join(tmp, 'release', 'objectstack.json');

const run = await runDoctor();

const rows = envFilesRows(run.out);
expect(rows).toHaveLength(1);
expect(rows[0].endsWith(unchangedRow())).toBe(true);
expect(rows[0]).not.toContain('os start');
}, E2E_TIMEOUT);
});
});
51 changes: 42 additions & 9 deletions packages/cli/src/commands/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,10 @@ export function doctorNodeEnv(env: NodeJS.ProcessEnv = process.env): string {
*
* What the posture does NOT change: {@link doctorNodeEnv} and the `.env*`
* cascade doctor resolves (still `production`, which the `Environment files`
* row keeps saying), the `/discovery` default, and how `os serve`, `os start`
* and `os dev` resolve the mode. Only what this row says, and when.
* row keeps saying — in this posture naming `os serve` / `os start` as the
* loaders of that cascade, #22249), the `/discovery` default, and how
* `os serve`, `os start` and `os dev` resolve the mode. Only what this row
* says, and when.
*
* ── Deliberately NOT in `DOCTOR_ENV_INPUTS`, and not read through the overlay ─
*
Expand Down Expand Up @@ -277,7 +279,8 @@ export function nodeEnvCheck(
* [#22163] Is `cwd` the source checkout `os dev` serves — a cwd
* `objectstack.config.ts` that boots as itself, with no artifact from anywhere
* else? The posture {@link nodeEnvCheck} reads an unset `NODE_ENV` as
* development in.
* development in, and {@link environmentSourcesCheck} names the loaders of the
* cascade it reports in (#22249). `run()` asks once and hands both the answer.
*
* Answered by THE precedence (`utils/artifact-precedence.ts`), never by a copy
* of it: {@link resolveArtifactBootSource} for the artifact rungs, then
Expand Down Expand Up @@ -640,18 +643,41 @@ function revertDotenvOverlay(overlay: Record<string, string>, applied: string[])
* `DOCTOR_ENV_INPUTS`, so they are not enumerated here — but the files that
* supplied them are, which is what makes the wider overlay a reported fact
* rather than the silent merge #5387 refused.
*
* ── In the source checkout `os dev` serves, the row says whose cascade (#22249) ─
*
* The cascade itself does not move with the posture: #5387's ruling stands,
* doctor resolves it exactly as `os serve` does, so {@link doctorNodeEnv} and
* every env-derived verdict are the same in every posture. What moves is the
* reader. Beside a config `os dev` serves, the `NODE_ENV` row just below says
* the project runs as development under `os dev` (#22163), and `os dev` loads
* the `node_env=development` cascade — so an unattributed `node_env=production`
* one row above it reads to a newcomer as "my dev project is production". There
* the row names its loaders, `os serve` and `os start`, both of which resolve
* the cascade doctor resolved (`start.ts` and `serve.ts` derive the same mode
* from `NODE_ENV`, and `os start` forces `production` only when it is unset).
* In every other posture the row is what it was, byte for byte.
*
* @param opts.sourcePosture {@link nodeEnvSourcePosture}'s answer for the
* directory doctor runs in — the same answer {@link nodeEnvCheck} is given,
* computed once by the caller. Defaults to `false`, the unchanged row.
*/
export function environmentSourcesCheck(
reading: DotenvReading,
env: NodeJS.ProcessEnv = process.env,
opts: { sourcePosture?: boolean } = {},
): HealthCheckResult {
const loaded = reading.files.map((file) => displayEnvFile(reading, file));
const provenances = DOCTOR_ENV_INPUTS.map((name) => provenanceOf(reading, name, env));
const set = provenances.filter((p) => p.source !== 'unset');

const cascade = `node_env=${reading.nodeEnv}`;
const loader = opts.sourcePosture ? '`os serve` / `os start` load' : '`os serve` loads';
const where = loaded.length > 0
? `${loaded.join(', ')} (node_env=${reading.nodeEnv}), the cascade \`os serve\` loads`
: `No .env* files here (node_env=${reading.nodeEnv}) — environment read from this process only`;
? `${loaded.join(', ')} (${cascade}), the cascade ${loader}`
: opts.sourcePosture
? `No .env* files here (${cascade}, the cascade ${loader}) — environment read from this process only`
: `No .env* files here (${cascade}) — environment read from this process only`;
const attribution = set.length > 0
? ` — ${set.map((p) => describeProvenance(reading, p)).join(', ')}`
: ' — no environment input set';
Expand Down Expand Up @@ -2181,7 +2207,12 @@ export default class Doctor extends Command {
// derived from it. Unconditional: an env-derived verdict whose inputs are
// not attributed is a verdict the operator cannot check, and after this
// change every such verdict has four possible sources.
results.push(environmentSourcesCheck(dotenvReading));
//
// #22163 / #22249 — the source checkout `os dev` serves, asked ONCE: the
// sources row and the NODE_ENV row below both read this one answer, so the
// two rows can never describe two different postures in one report.
const sourcePosture = nodeEnvSourcePosture(cwd);
results.push(environmentSourcesCheck(dotenvReading, process.env, { sourcePosture }));

// #5673 / #22163 — what an unset NODE_ENV means here. Placed immediately
// after the sources row because it answers the question that row raises:
Expand All @@ -2191,9 +2222,11 @@ export default class Doctor extends Command {
// says that project runs as development under `os dev` and as production
// under `os start` — and the sources row above still says
// `node_env=production` there, because that is the cascade doctor resolved
// and #22163 changes only this row. Only the unset case produces a row; a
// configured environment's report is unchanged.
const nodeEnvFinding = nodeEnvCheck(process.env, { sourcePosture: nodeEnvSourcePosture(cwd) });
// (#5387); since #22249 it also names `os serve` / `os start` as the
// loaders of that cascade there, so the two rows read as one account. Only
// the unset case produces a row; a configured environment's report is
// unchanged.
const nodeEnvFinding = nodeEnvCheck(process.env, { sourcePosture });
if (nodeEnvFinding) {
results.push(nodeEnvFinding);
}
Expand Down
Loading