Skip to content

Commit f9bf191

Browse files
authored
feat: run a zero-config first-run forecast (#319)
1 parent 0cb2353 commit f9bf191

15 files changed

Lines changed: 401 additions & 39 deletions

‎benchmarks/first-run.ts‎

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,103 @@
11
import { spawnSync } from "node:child_process";
22
import { appendFileSync, existsSync } from "node:fs";
3-
import { copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import { copyFile, cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
44
import { tmpdir } from "node:os";
55
import { join, resolve } from "node:path";
66
import { performance } from "node:perf_hooks";
77
import { pathToFileURL } from "node:url";
8+
import { restoreFixtureNames } from "../src/fixture-names.js";
9+
10+
const exampleGroups = new Set(["agents", "codemods", "drift", "gallery", "starters", "upgrade"]);
11+
const EXAMPLE_BUDGET_MS = 5000;
12+
13+
async function directories(root: string): Promise<string[]> {
14+
return (await readdir(root, { withFileTypes: true }))
15+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
16+
.map((entry) => entry.name)
17+
.sort();
18+
}
19+
20+
export async function exampleRepositories(root: string): Promise<string[]> {
21+
const examples: string[] = [];
22+
for (const name of await directories(root)) {
23+
if (exampleGroups.has(name)) {
24+
examples.push(...(await directories(join(root, name))).map((child) => `${name}/${child}`));
25+
} else {
26+
examples.push(name);
27+
}
28+
}
29+
return examples;
30+
}
31+
32+
function timeExample(root: string, name: string, cli: string): { seconds: string; passed: boolean } {
33+
const start = performance.now();
34+
const result = spawnSync(process.execPath, [cli], {
35+
cwd: join(root, name),
36+
env: { ...process.env, CI: "true", OFFING_NO_CACHE: "1" },
37+
encoding: "utf8",
38+
timeout: EXAMPLE_BUDGET_MS,
39+
});
40+
const duration = performance.now() - start;
41+
const passed = result.status === 0 && result.stdout.startsWith("Weather: ") && duration < EXAMPLE_BUDGET_MS;
42+
if (!passed) console.error(`${name}: ${result.error?.message ?? result.stderr}`);
43+
return { seconds: (duration / 1000).toFixed(3), passed };
44+
}
45+
46+
async function timeExamples(): Promise<void> {
47+
const root = await mkdtemp(join(tmpdir(), "offing-examples-first-run-"));
48+
try {
49+
await cp("examples", root, { recursive: true });
50+
await restoreFixtureNames(root);
51+
const cli = resolve("dist/src/cli.js");
52+
const rows = ["| Example repository | First run | Under 5 s |", "|---|---:|---|"];
53+
for (const name of await exampleRepositories(root)) {
54+
const { seconds, passed } = timeExample(root, name, cli);
55+
rows.push(`| ${name} | ${seconds} s | ${passed ? "Pass" : "Fail"} |`);
56+
if (!passed) process.exitCode = 1;
57+
}
58+
console.log(rows.join("\n"));
59+
} finally {
60+
await rm(root, { recursive: true, force: true });
61+
}
62+
}
63+
64+
export async function cachedTarballBytes(cache: string): Promise<{ tarballs: number; bytes: number }> {
65+
// shortcut: npm's HTTP cache index is not a public API; revisit if npm changes its layout.
66+
const index = join(cache, "_cacache", "index-v5");
67+
const tarballs = new Map<string, number>();
68+
for (const entry of await readdir(index, { recursive: true, withFileTypes: true })) {
69+
if (!entry.isFile()) continue;
70+
const contents = await readFile(join(entry.parentPath, entry.name), "utf8");
71+
for (const line of contents.trim().split("\n")) {
72+
if (!line) continue;
73+
const { key, size } = JSON.parse(line.slice(line.indexOf("\t") + 1)) as { key: string; size?: number };
74+
if (key.startsWith("make-fetch-happen:request-cache:") && key.endsWith(".tgz") && size !== undefined) {
75+
tarballs.set(key, size);
76+
}
77+
}
78+
}
79+
return { tarballs: tarballs.size, bytes: [...tarballs.values()].reduce((sum, size) => sum + size, 0) };
80+
}
81+
82+
async function measureNpxDownload(): Promise<void> {
83+
const root = await mkdtemp(join(tmpdir(), "offing-npx-first-run-"));
84+
try {
85+
const cache = join(root, "cache");
86+
const result = spawnSync("npx", ["--yes", "--ignore-scripts", "@velella/offing", "--version"], {
87+
cwd: root,
88+
encoding: "utf8",
89+
env: { ...process.env, npm_config_cache: cache, npm_config_registry: "https://registry.npmjs.org" },
90+
shell: process.platform === "win32",
91+
timeout: 180_000,
92+
});
93+
if (result.status !== 0) throw new Error(result.error?.message ?? result.stderr);
94+
const { bytes, tarballs } = await cachedTarballBytes(cache);
95+
if (tarballs === 0) throw new Error("No downloaded tarballs were recorded in the clean npm cache.");
96+
console.log(`@velella/offing ${result.stdout.trim()}: ${bytes} compressed bytes across ${tarballs} tarballs.`);
97+
} finally {
98+
await rm(root, { recursive: true, force: true });
99+
}
100+
}
8101

9102
/** Target budget for time to first useful finding: 2 minutes = 120,000 ms. */
10103
export const TWO_MINUTE_BUDGET_MS = 120_000;
@@ -247,6 +340,8 @@ function appendMarkdownSummary(summaryPath: string, result: FirstRunBenchmarkRes
247340
}
248341

249342
export async function runCli(argv = process.argv.slice(2)): Promise<void> {
343+
if (argv.length === 0 || argv[0] === "--examples") return timeExamples();
344+
if (argv[0] === "--npx-size") return measureNpxDownload();
250345
let packageSpec: string | undefined;
251346
let targetDir: string | undefined;
252347
let useNpx = false;

‎changes/zero-config-first-run.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Run a local scan and show a short lifecycle forecast when Offing is invoked without a subcommand.

‎docs/BENCHMARKS.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,9 @@ The benchmark corpus is intentionally controlled. The automated test suite separ
210210

211211
## Time to first useful finding
212212

213-
Run `npm run benchmark:first-run` to time a clean run of the quickstart to its first useful finding.
213+
Run `npm run benchmark:first-run` to time bare `offing` on clean copies of the example repositories. The table measures process launch through completion with the scan cache disabled; the command fails if any example does not print a forecast in under 5 seconds. Download time is not part of this budget.
214+
215+
Use `npm run benchmark:first-run -- --npx-size` to measure the compressed package downloads from an empty npm cache. Use `npm run benchmark:first-run -- --check` to time the original smoke fixture and check that it reports a finding.
214216

215217
The benchmark tracks Offing's adoption goal: a new user goes from `npx` to a useful, explained finding in under two minutes (120 s) on any supported OS without prior installation or configuration.
216218

@@ -222,7 +224,7 @@ The local benchmark (`benchmarks/first-run.ts`) measures wall-clock time from in
222224
2. Rule evaluation against bundled offline lifecycle data.
223225
3. Emission of the first useful finding (`npm.package.request.deprecated` at `package.json:5` and the Node.js end-of-life runtime).
224226

225-
On 2026-10-28, running `npm run benchmark:first-run` against the local build on macOS (Apple silicon, Node.js 26) completed the clean scan in 0.28 s, reporting 4 findings. Treat this duration as an observational local reference point.
227+
On 2026-10-28, the smoke fixture against the local build on macOS (Apple silicon, Node.js 26) completed the clean scan in 0.28 s, reporting 4 findings. Treat this duration as an observational local reference point.
226228

227229
### Release workflow timing
228230

‎docs/CLI.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Every command runs locally. Scans read repository files and bundled lifecycle da
1313

1414
| Option | What it does |
1515
| --- | --- |
16-
| `-h`, `--help` | Print the command list and exit `0`. Running `offing` with no arguments prints the same text. |
16+
| `-h`, `--help` | Print the command list and exit `0`. |
1717
| `-v`, `--version` | Print the package version and exit `0`. |
1818
| `--debug` | On an unexpected failure (`internal`, exit `5`), print the stack trace to stderr. |
1919
| `--json` | Print a machine-readable document where the command supports one. Same as `--format json` for `scan`, `check`, and `forecast`. |
@@ -23,6 +23,8 @@ Every command runs locally. Scans read repository files and bundled lifecycle da
2323

2424
## Scanning and reporting
2525

26+
With no subcommand, `offing` scans the current directory and prints a short forecast without prompting. Use `offing --as-of YYYY-MM-DD` to set the reference date, or `offing --json` for the same machine-readable output as `offing forecast --json`.
27+
2628
### `scan`
2729

2830
```bash

‎docs/PERFORMANCE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ npm run benchmark:monorepo -- --check
116116
# CLI start-up budget.
117117
npm run benchmark:startup
118118

119-
# Time to first useful finding.
119+
# Bare Offing on the example repositories.
120120
npm run benchmark:first-run
121121

122122
# Source-usage precision, recall, and engine comparison.

‎docs/QUICKSTART.md‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,47 @@ description: "Five copy-paste steps, from the first scan to a baseline in CI. Yo
88
Five copy-paste steps, from the first scan to a baseline in CI. You need Node.js 22 or newer and a repository to scan. Every command runs locally; nothing is uploaded.
99

1010
> [!NOTE]
11-
> Every command on this page runs locally. Nothing is uploaded.
11+
> Scans run locally and upload nothing. `npx` may download Offing and its dependencies before the scan starts.
1212
13-
## 1. Run the first scan
13+
## 1. Run Offing without configuration
14+
15+
From the directory you want to scan:
16+
17+
```bash
18+
npx --yes @velella/offing
19+
```
20+
21+
No subcommand is needed. Offing scans the current directory and prints the top findings and upcoming lifecycle deadlines. It never prompts or opens a browser, even on a terminal. If Git history is unavailable, it still scans the files on disk. For the full report with finding IDs, replacements, and evidence, run `npx --yes @velella/offing scan .`. Use `npx --yes @velella/offing --json` for the structured forecast without the next-step hints.
22+
23+
The bare invocation starts working with the release that includes this change. To try it before then, use a checkout of Offing as shown below.
24+
25+
### Try the demo
26+
27+
From a checkout of [Offing](https://github.com/velella-sh/offing), run:
1428

1529
```bash
16-
npx @velella/offing scan .
30+
npm ci
31+
npm run example --silent -- demo --as-of 2026-10-25
1732
```
1833

19-
Each finding names its severity, the exact file and line, the replacement, and the source. The first lines look like this on the demo project:
34+
The example runner copies the demo into a temporary directory and runs Offing there without a subcommand. The fixed date makes the output reproducible:
2035

2136
```text
22-
Found 5 lifecycle risks. The most urgent:
37+
Weather: clear
38+
Forecast: 2026-10-25 to 2027-10-25
39+
Lifecycle findings: 5; upcoming deadlines: 0; no data: 0.
2340
HIGH Unsupported actions/checkout runtime (.github/workflows/ci.yml:9)
2441
MEDIUM Node.js 18 is end-of-life (package.json:5)
25-
…
42+
MEDIUM Node.js 19 is end-of-life (package.json:5)
43+
Git history is not available; Offing scanned the files on disk.
44+
45+
Next: offing forecast
46+
Next: offing init --hooks
2647
```
2748

28-
Add `--json` for machine-readable output, or `--format compact` for one line per finding when an agent reads the result.
49+
### First download size
50+
51+
On macOS arm64 with Node.js 22.23.1 and npm 10.9.8, a clean-cache `npx` install of the published `@velella/offing@0.1.1` downloaded **5,208,351 compressed bytes** (about 5.21 MB) across 12 package tarballs, including dependencies. This excludes registry metadata and protocol overhead; the exact size can vary by platform and dependency versions. To remeasure from the Offing checkout, run `npm run benchmark:first-run -- --npx-size`.
2952

3053
## 2. Check one dependency before adding it
3154

@@ -37,7 +60,7 @@ The command prints the lifecycle problem, the replacement, and the evidence. It
3760

3861
## 3. Read the evidence for one finding
3962

40-
Take a finding id from step 1 and inspect it:
63+
Take a finding ID from the full `scan .` report in step 1 and inspect it:
4164

4265
```bash
4366
npx @velella/offing explain '<finding-id>' .

‎src/cli-main.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { bindContext, createCommandContext, fail } from "./commands/runtime.js";
66
import { isCompletionShell, renderCompletions, renderHelp } from "./completions.js";
77
import { unexpectedFailure } from "./errors.js";
88
import { classifyError } from "./offing-error.js";
9+
import { runOnboarding } from "./onboarding/first-run.js";
910
import { VERSION } from "./version.js";
1011

1112
const HELP = renderHelp(commands);
@@ -18,7 +19,7 @@ export async function main(rawArgs: readonly string[]): Promise<number> {
1819
);
1920
bindContext(ctx);
2021
const args = optionArgs.filter((argument) => argument !== "--debug");
21-
if (args.includes("--help") || args.includes("-h") || args.length === 0) {
22+
if (args.includes("--help") || args.includes("-h")) {
2223
process.stdout.write(HELP);
2324
return 0;
2425
}
@@ -27,6 +28,7 @@ export async function main(rawArgs: readonly string[]): Promise<number> {
2728
return 0;
2829
}
2930
const name = args[0];
31+
if (name === undefined || name === "--as-of" || name === "--json") return runOnboarding(args, ctx);
3032
const command = commands.find((candidate) => candidate.name === name);
3133
if (!command) return ctx.fail("usage", `Unknown command: ${name ?? ""}`, `\n${HELP}`, "unknown-command");
3234
return command.run([...args.slice(1), ...rawArgs.slice(optionArgs.length)], ctx);

‎src/forecast-core.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,14 @@ export function forecastWeather(events: readonly ForecastEvent[], hasNoData: boo
2626
}
2727

2828
/** Keep each data value on one terminal line, even when a repository supplies control characters. */
29-
function singleLine(text: string): string {
29+
export function singleLine(text: string): string {
3030
return text.replace(
3131
/\p{Cc}|\p{Zl}|\p{Zp}/gu,
3232
(character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`,
3333
);
3434
}
3535

36-
function locationText({ path, line }: SourceLocation): string {
36+
export function locationText({ path, line }: SourceLocation): string {
3737
return line === undefined ? singleLine(path) : `${singleLine(path)}:${line}`;
3838
}
3939

‎src/onboarding/first-run.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { execFile } from "node:child_process";
2+
import { readdir } from "node:fs/promises";
3+
import { dirname } from "node:path";
4+
import process from "node:process";
5+
import { parseArgs, promisify } from "node:util";
6+
import { DEFAULT_FORECAST_MONTHS } from "@velella/ebb/forecast";
7+
import { isIsoDate } from "@velella/ebb/registry";
8+
import { command as forecastCommand } from "../commands/forecast.js";
9+
import type { CommandContext } from "../commands/types.js";
10+
import type { ScanResult } from "../domain.js";
11+
import { forecastWeather, locationText, singleLine } from "../forecast-core.js";
12+
import { forecastBuckets } from "../forecast-timeline.js";
13+
import { buildRepositoryForecast, replayScanOptions, type RepositoryForecast } from "../forecast.js";
14+
import { scanWithBuiltIns } from "../scan-builtins.js";
15+
16+
const execute = promisify(execFile);
17+
const exampleUrl = "https://github.com/velella-sh/offing/blob/main/docs/QUICKSTART.md#try-the-demo";
18+
19+
async function hasGitHistory(root: string): Promise<boolean> {
20+
try {
21+
await execute("git", ["-C", root, "rev-parse", "--verify", "--quiet", "HEAD"], {
22+
// On Windows, executable lookup can search the child's working directory.
23+
cwd: dirname(process.execPath),
24+
timeout: 1000,
25+
});
26+
return true;
27+
} catch {
28+
return false;
29+
}
30+
}
31+
32+
function renderFirstRun(scan: ScanResult, forecast: RepositoryForecast, empty: boolean, history: boolean): string {
33+
const buckets = forecastBuckets(forecast);
34+
const upcoming = buckets.flatMap(({ events }) => events.filter((event) => event.findings.length > 0));
35+
const nearest = buckets[0]?.events.filter((event) => event.findings.length > 0) ?? [];
36+
const lines = [
37+
`Weather: ${forecastWeather(nearest, forecast.noData.length > 0)}`,
38+
`Forecast: ${forecast.today} to ${forecast.until}`,
39+
`Lifecycle findings: ${scan.findings.length}; upcoming deadlines: ${upcoming.length}; no data: ${forecast.noData.length}.`,
40+
];
41+
for (const finding of scan.findings.slice(0, 3)) {
42+
lines.push(` ${finding.severity.toUpperCase()} ${singleLine(finding.title)} (${locationText(finding.location)})`);
43+
}
44+
for (const event of upcoming.slice(0, 3)) {
45+
lines.push(` ${event.date} ${singleLine(event.title)}`);
46+
}
47+
if (empty) {
48+
lines.push(
49+
"This folder is empty. Offing looks for manifests, lockfiles, and CI workflows.",
50+
`Try the demo: ${exampleUrl}`,
51+
);
52+
}
53+
if (!history) lines.push("Git history is not available; Offing scanned the files on disk.");
54+
lines.push("", "Next: offing forecast", "Next: offing init --hooks");
55+
return `${lines.join("\n")}\n`;
56+
}
57+
58+
/** The default invocation is read-only and never asks for input, even on a terminal. */
59+
export async function runOnboarding(args: readonly string[], ctx: CommandContext): Promise<number> {
60+
let asOf: string | undefined;
61+
let json: boolean | undefined;
62+
try {
63+
const { values } = parseArgs({
64+
args: [...args],
65+
options: { "as-of": { type: "string" }, json: { type: "boolean" } },
66+
});
67+
asOf = values["as-of"];
68+
json = values.json;
69+
} catch {
70+
return ctx.fail("usage", "Usage: offing [--as-of <YYYY-MM-DD>] [--json]");
71+
}
72+
if (asOf !== undefined && !isIsoDate(asOf)) return ctx.fail("usage", "--as-of must be a date (YYYY-MM-DD).");
73+
if (json) return forecastCommand.run(asOf === undefined ? ["--json"] : ["--json", "--as-of", asOf], ctx);
74+
75+
const root = process.cwd();
76+
const [scan, entries, history] = await Promise.all([
77+
scanWithBuiltIns(root, asOf === undefined ? undefined : replayScanOptions(asOf)),
78+
readdir(root),
79+
hasGitHistory(root),
80+
]);
81+
const forecast = await buildRepositoryForecast(scan, DEFAULT_FORECAST_MONTHS);
82+
process.stdout.write(
83+
renderFirstRun(
84+
scan,
85+
forecast,
86+
entries.every((entry) => entry === ".git"),
87+
history,
88+
),
89+
);
90+
return 0;
91+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
=== examples/demo ===
2+
Weather: clear
3+
Forecast: 2026-10-25 to 2027-10-25
4+
Lifecycle findings: 5; upcoming deadlines: 0; no data: 0.
5+
HIGH Unsupported actions/checkout runtime (.github/workflows/ci.yml:9)
6+
MEDIUM Node.js 18 is end-of-life (package.json:5)
7+
MEDIUM Node.js 19 is end-of-life (package.json:5)
8+
Git history is not available; Offing scanned the files on disk.
9+
10+
Next: offing forecast
11+
Next: offing init --hooks
12+
13+
=== examples/gallery/container ===
14+
Weather: storm
15+
Forecast: 2026-10-25 to 2027-10-25
16+
Lifecycle findings: 18; upcoming deadlines: 2; no data: 0.
17+
HIGH Alpine Linux image release lines 3.20 and older are end-of-life (os-images.Dockerfile:3)
18+
HIGH Alpine Linux image release line 3.21 is end-of-life (os-images.Dockerfile:8)
19+
HIGH Debian image release lines 11 and older are end-of-life (os-images.Dockerfile:2)
20+
2026-11-01 Alpine Linux image release line 3.21 is end-of-life
21+
2027-06-01 Ubuntu image release line 22.04 reaches standard support end-of-life on 2027-06-01
22+
Git history is not available; Offing scanned the files on disk.
23+
24+
Next: offing forecast
25+
Next: offing init --hooks
26+
27+
=== examples/gallery/python ===
28+
Weather: clear
29+
Forecast: 2026-10-25 to 2027-10-25
30+
Lifecycle findings: 1; upcoming deadlines: 0; no data: 0.
31+
HIGH Python 3.9 and older are end-of-life (.python-version:1)
32+
Git history is not available; Offing scanned the files on disk.
33+
34+
Next: offing forecast
35+
Next: offing init --hooks

0 commit comments

Comments
 (0)