Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): record which step a project open reached (PRD-7473) (#3963)

Andrew Mikofalvyd1eda6a5a0b1
diff --git a/.changeset/open-project-funnel-milestones.md b/.changeset/open-project-funnel-milestones.md
new file mode 100644
index 000000000..9af0bfef9
--- /dev/null
+++ b/.changeset/open-project-funnel-milestones.md
@@ -0,0 +1,13 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+A bug report from a desktop freeze while opening a folder now names the step the open had reached.
+
+Opening a folder runs a long admission funnel: working out what the picked folder actually is, confirming an ancestor project, the first-open consent dialog and its content probe, git and content scaffolding, the editor and AI-tool writes, and finally the window itself. Until now that whole stretch reported one line as it started and one line once the window existed, and nothing in between. Every diagnostic along the way was a `console.warn`, which the packaged app discards. A session that stopped anywhere inside the funnel therefore produced a report indistinguishable from one that stopped anywhere else, which is why several reports of a freeze right after picking a folder could establish that the app had stopped and not where.
+
+The funnel now reports one line per decision it makes and per step that can run long, on both the first-open and existing-project paths: entering the admission resolution, the folder-size probe and the git-root lookup inside it, what the pick resolved to and whether it was promoted to an ancestor folder or a git root, each dialog being raised and the answer coming back, the waits for the Navigator to load and for git and content scaffolding, the artifact writes, and entering the window creation rather than only finishing it. A report now points at one step instead of the whole funnel. Creating a new project resolves the new folder's location through a separate admission pass before this funnel is reached, and that pass is not covered; the open that follows it runs this funnel and reports the steps that apply to it.
+
+The size probe that decides whether an oversized ancestor needs confirmation also reports its own failure through the same log. That failsafe quietly changes which branch the open takes, and it previously said so only on a sink the shipped app throws away.
+
+One line per step per open. The new lines carry folder names, enumerated states, counts and booleans rather than file contents. The probe failure is the exception, and deliberately so: it reports the error itself, whose message carries the path the probe could not read, because knowing which failure flipped the branch is the reason that line was promoted off the discarded sink in the first place.
diff --git a/packages/desktop/src/main/folder-admission.ts b/packages/desktop/src/main/folder-admission.ts
index b184f80c3..45837b5fb 100644
--- a/packages/desktop/src/main/folder-admission.ts
+++ b/packages/desktop/src/main/folder-admission.ts
@@ -10,7 +10,8 @@
* or (c) is a fresh standalone folder.
*
* `homeDir` and `gitTopLevel` are injectable so tests don't depend on the real
- * process environment or shell out to git.
+ * process environment or shell out to git. `openProject` also injects
+ * `gitTopLevel`, wrapping the exported default to bracket it with a log line.
*/
import { execFile } from 'node:child_process';
@@ -161,10 +162,12 @@ export interface DiscoverProjectOptions {
* never promotes to a git root at-or-above home). Tests inject a fixed
* value to keep assertions stable. */
homeDir?: string;
- /** Resolves the git working-tree root for a given cwd. Defaults to shelling
- * out to `git rev-parse --show-toplevel`; tests inject a deterministic
- * stub. Returns `null` when the cwd is not inside a git working tree (or
- * when `git` itself is unavailable). */
+ /** Resolves the git working-tree root for a given cwd. Defaults to
+ * `defaultGitTopLevel`, which shells out to `git rev-parse --show-toplevel`;
+ * tests inject a deterministic stub, and `openProject` injects a wrapper
+ * around the exported default so the subprocess is bracketed by a log line.
+ * Returns `null` when the cwd is not inside a git working tree (or when
+ * `git` itself is unavailable). */
gitTopLevel?: (cwd: string) => Promise<string | null>;
/**
* Required. Consulted only when the ancestor walk would strictly promote —
@@ -409,7 +412,13 @@ function isPickedPathLinkedWorktreeRoot(pickedPath: string): boolean {
}
}
-async function defaultGitTopLevel(cwd: string): Promise<string | null> {
+/**
+ * The `gitTopLevel` default. Exported so a caller can wrap it rather than
+ * reimplement it: `openProject` does exactly that to log around the call,
+ * which is otherwise the one unbounded step in `discoverProject` with no
+ * timeout and no trace.
+ */
+export async function defaultGitTopLevel(cwd: string): Promise<string | null> {
try {
const { stdout } = await execFileAsync('git', ['rev-parse', '--show-toplevel'], { cwd });
const trimmed = stdout.trim();
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index c3ad03206..afef5cef8 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -270,7 +270,7 @@ import {
runDriverBootSmoke,
} from './driver-boot-smoke.ts';
import { EMBED_HOST_PATTERNS, rewriteEmbedRequestHeaders } from './embed-referer.ts';
-import { discoverProject, validateFolderPick } from './folder-admission.ts';
+import { defaultGitTopLevel, discoverProject, validateFolderPick } from './folder-admission.ts';
import { ensureGitAvailable } from './git-preflight-handler.ts';
import { readCanonicalGitHubRemoteUrl } from './git-remote.ts';
import { classifyInstallShape } from './install-shape.ts';
@@ -2321,7 +2321,7 @@ async function openProject(
) {
getLogger('project').info(
{
- projectName: basename(projectPath),
+ pickedName: basename(projectPath),
entryPoint,
hasDeepLinkTarget: !!pendingDeepLinkTarget,
hasPendingBranch: !!pendingBranch,
@@ -2336,6 +2336,10 @@ async function openProject(
// Admission funnel. Resolve the pick BEFORE any window/utility spawn so we
// know whether to ancestor-promote, silent-onboard, dialog, or refuse.
const validation = validateFolderPick(projectPath);
+ // Open-bracket: discoverProject is one await spanning several unbounded fs
+ // and subprocess steps, so without a mark here a stall inside it is
+ // indistinguishable from a stall anywhere else in the funnel.
+ getLogger('project').info({ pickedName: basename(projectPath) }, 'resolving project admission');
const discovery = await discoverProject(projectPath, {
// Probe consulted only when the ancestor walk strictly promotes — gates
// silent fork against an ancestor too large to boot in 15s (the dragon-wiki
@@ -2343,16 +2347,77 @@ async function openProject(
// utility against `~/Documents` and timed out). Failsafe to "show the
// dialog" on any throw so a probe failure can't reintroduce silent fork.
dirSizeProbe: async (dir) => {
+ getLogger('project').info(
+ { projectName: basename(dir), pickedName: basename(projectPath) },
+ 'probing ancestor size',
+ );
try {
const exceedsCap = await walkExceedsCap(dir, BOOT_BUDGET_FILE_CAP);
return { exceedsCap };
} catch (err) {
- console.warn('[openProject] dirSizeProbe failed, failsafe to exceedsCap:true', err);
+ // Pino, not console: this failsafe silently forces the confirmation
+ // dialog, so the branch would flip with no surviving record of why.
+ getLogger('project').warn(
+ { err },
+ 'project admission size probe failed, treating as over cap',
+ );
return { exceedsCap: true };
}
},
+ // The other arm of the same await, and the unbounded one: `git rev-parse`
+ // runs without a timeout, so a locked index or a network-mounted `.git`
+ // hangs here. Reached only when the ancestor walk promoted nothing.
+ // create-new's own pre-scaffold `discoverProject` call is deliberately not
+ // wrapped; the open that follows it lands in this funnel.
+ gitTopLevel: async (cwd) => {
+ // Not `projectName`: `cwd` is the resolved pick, and on this arm the
+ // project dir is whatever the git root turns out to be, which is not
+ // known until the call returns. `pickedName` rides along because neither
+ // the `projectName` const nor `discovery` exists yet at this point in the
+ // function, so the pick is the only name in scope here, and a symlinked
+ // pick makes the two basenames differ.
+ getLogger('project').info(
+ { pickedName: basename(projectPath), resolvedPickedName: basename(cwd) },
+ 'resolving git root',
+ );
+ return defaultGitTopLevel(cwd);
+ },
});
+ // Payloads stay basenames and enums, matching the entry log above.
+ getLogger('project').info(
+ discovery.kind === 'rejected'
+ ? {
+ // `rejected` carries no `projectDir`, so the pick is the only name
+ // this arm can correlate on.
+ pickedName: basename(projectPath),
+ discoveryKind: discovery.kind,
+ reason: discovery.reason,
+ }
+ : {
+ // Not the `projectName` const below: this line precedes the `rejected`
+ // early return that narrows `discovery`, so the const does not exist yet.
+ projectName: basename(discovery.projectDir),
+ // Ungated, unlike `resolvedPickedName` below: on a symlinked direct
+ // open that gate drops out and `projectName` is the realpath
+ // basename, while the entry logs carry the raw pick. On a managed
+ // direct hit neither bridging milestone fires, because the ancestor
+ // walk returns before the git-root lookup is reached, so this is the
+ // only line that can carry both.
+ pickedName: basename(projectPath),
+ discoveryKind: discovery.kind,
+ // The pair is what separates an ancestor / git-root promote from a
+ // direct open.
+ ...(discovery.projectDir === discovery.pickedPath
+ ? {}
+ : { resolvedPickedName: basename(discovery.pickedPath) }),
+ ...(discovery.kind === 'fresh'
+ ? { gitState: discovery.gitState, gitRootPromoted: discovery.gitRootPromoted }
+ : { ancestorPromoted: discovery.ancestorPromoted }),
+ },
+ 'project admission resolved',
+ );
+
if (discovery.kind === 'rejected') {
dialog.showErrorBox(
'Cannot open this folder',
@@ -2370,6 +2435,7 @@ async function openProject(
const warningsCount = validation.warnings.length;
const resolvedProjectDir = discovery.projectDir;
+ const projectName = basename(resolvedProjectDir);
void checkAndRepairProjectMcpOnProjectOpen({
projectDir: resolvedProjectDir,
executablePath: app.getPath('exe'),
@@ -2410,21 +2476,28 @@ async function openProject(
// existing managed-promote silent flow. This is the only path that can
// reach this branch (cursor !== realPicked), so ancestorPromoted is
// guaranteed true.
- const ancestorName = basename(discovery.projectDir);
- const pickedName = basename(discovery.pickedPath);
+ const resolvedPickedName = basename(discovery.pickedPath);
// Async dialog matches the codebase convention (every other dialog in
// packages/desktop/src/main/ uses await dialog.showMessageBox); sync would
// freeze IPC, the auto-updater pipeline, and the cc1-broadcast debouncer
// until the user clicks. Button order [Cancel, Open <ancestor>] with
// cancelId:0 / defaultId:0: Enter and Escape both land on the safe path.
+ getLogger('project').info(
+ { projectName, resolvedPickedName },
+ 'project admission confirmation requested',
+ );
const { response } = await dialog.showMessageBox({
type: 'question',
- buttons: ['Cancel', `Open ${ancestorName}`],
+ buttons: ['Cancel', `Open ${projectName}`],
cancelId: 0,
defaultId: 0,
title: 'Open existing project?',
- message: `OpenKnowledge wants to open the existing project at ${discovery.projectDir} (because it contains an .ok/ config). The folder you picked, ${pickedName}, is inside that project. Open ${ancestorName}?`,
+ message: `OpenKnowledge wants to open the existing project at ${discovery.projectDir} (because it contains an .ok/ config). The folder you picked, ${resolvedPickedName}, is inside that project. Open ${projectName}?`,
});
+ getLogger('project').info(
+ { projectName, confirmed: response !== 0 },
+ 'project admission confirmation answered',
+ );
if (response === 0) {
recordOnboardingFlow({
flowKind: 'managed-promote-cancelled',
@@ -2487,6 +2560,7 @@ async function openProject(
const navigatorWebContents = (navigator as unknown as { webContents: Electron.WebContents })
.webContents;
if (navigatorWebContents.isLoading()) {
+ getLogger('project').info({ projectName }, 'awaiting navigator load');
// Promise.race the load against the renderer being destroyed —
// a closed Navigator window or a crashed renderer mid-load would
// otherwise leave openProject stuck on a Promise that never
@@ -2525,6 +2599,12 @@ async function openProject(
gitRootPromoted: discovery.gitRootPromoted,
warnings: validation.warnings.map((w) => ({ kind: w.kind })),
};
+ // The dialog's own content probe walks the picked tree synchronously on the
+ // main thread, so this pair brackets the funnel's least bounded step.
+ getLogger('project').info(
+ { projectName, gitState: discovery.gitState },
+ 'onboarding consent requested',
+ );
const decision = await requestUserConsent(
{
// Sink facade, not the raw ipcMain: the flow's one-shot renderer-ready
@@ -2535,6 +2615,10 @@ async function openProject(
},
showPayload,
);
+ getLogger('project').info(
+ { projectName, outcome: decision.outcome },
+ 'onboarding consent answered',
+ );
if (decision.outcome === 'cancel') {
// Return to Navigator with no fs changes, no Recents add.
recordOnboardingFlow({
@@ -2562,12 +2646,21 @@ async function openProject(
request.initGit &&
(discovery.gitState === 'absent' || discovery.gitState === 'shell-only')
) {
+ getLogger('project').info(
+ { projectName, gitState: discovery.gitState },
+ 'ensuring project git',
+ );
await ensureProjectGit(discovery.projectDir);
didEnsureGit = true;
+ // No gitState: `discovery.gitState` is the pre-init value and is never
+ // recomputed, so echoing it here would pair "ensured" with "absent".
+ getLogger('project').info({ projectName }, 'ensured project git');
}
+ getLogger('project').info({ projectName, contentDirChanged }, 'initializing project content');
await initContent(discovery.projectDir, {
contentDir: request.contentDir !== '.' ? request.contentDir : undefined,
});
+ getLogger('project').info({ projectName, contentDirChanged }, 'initialized project content');
if (request.additionalIgnores.trim().length > 0) {
appendOkIgnoreSync(discovery.projectDir, request.additionalIgnores);
}
@@ -2622,6 +2715,15 @@ async function openProject(
pickedPath: discovery.pickedPath,
};
}
+ getLogger('project').info(
+ {
+ projectName,
+ aiIntegrationsFailedCount,
+ sharing: request.sharing,
+ toastKind: toastPayload?.kind,
+ },
+ 'project artifacts written',
+ );
}
// Project-skill reclaim — gated to committed managed opens. Reaching here
@@ -2635,6 +2737,10 @@ async function openProject(
// double-write, and no seeding a folder the consent dialog just configured a
// different way.
if (discovery.kind === 'managed' || discovery.kind === 'managed-requires-confirmation') {
+ // A managed open skips the whole fresh branch above, so without this the
+ // only marks on that path are admission and the window itself — and the
+ // gitignore ensure below is synchronous.
+ getLogger('project').info({ projectName }, 'reclaiming project skills');
void reclaimProjectSkillsOnProjectOpen({
projectDir: resolvedProjectDir,
executablePath: app.getPath('exe'),
@@ -2712,6 +2818,9 @@ async function openProject(
failedCount: aiIntegrationsFailedCount,
});
+ // Paired with the window-created line below, which only lands once the fork
+ // resolves — a stall inside the utility spawn would otherwise be silent.
+ getLogger('project').info({ projectName, flowKind, didEnsureGit }, 'creating project window');
const ctx = await wm.createProjectWindow({
projectPath: resolvedProjectDir,
pendingDeepLinkTarget,
@@ -2728,7 +2837,7 @@ async function openProject(
});
getLogger('project').info(
{
- projectName: basename(resolvedProjectDir),
+ projectName,
apiOrigin: ctx.apiOrigin,
flowKind,
didEnsureGit,
diff --git a/packages/desktop/tests/integration/open-project-milestones-wiring.test.ts b/packages/desktop/tests/integration/open-project-milestones-wiring.test.ts
new file mode 100644
index 000000000..41f5c50ef
--- /dev/null
+++ b/packages/desktop/tests/integration/open-project-milestones-wiring.test.ts
@@ -0,0 +1,220 @@
+/**
+ * Bypass-pin — `openProject`'s admission funnel must still emit a milestone
+ * per branch decision and per expensive step.
+ *
+ * The bug class is "a long stretch of the funnel emits no diagnostic line, so
+ * a hang or a silent death anywhere inside it produces a byte-identical
+ * bundle." Every intermediate diagnostic in that span is a `console.warn`,
+ * which the packaged main process discards, so the milestones are the only
+ * record that survives to a user-attached bundle.
+ *
+ * Runtime coverage cannot reach this: `index.ts` is a ~9k-line module that
+ * binds real Electron at module scope and runs top-level side effects, so no
+ * test in the package imports it. Same posture and rationale as the
+ * bypass-pins in `server-exit-wiring.test.ts` and `dock-visibility.test.ts`,
+ * which guard the spawn closure in the same file.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const indexTsPath = resolve(fileURLToPath(new URL('../../src/main/index.ts', import.meta.url)));
+const indexSource = readFileSync(indexTsPath, 'utf-8');
+
+/**
+ * Lines of `openProject`'s body. The function is top-level in a
+ * Biome-formatted file, so the first column-0 `}` after its signature is its
+ * close. A truncated slice fails the presence assertions loudly rather than
+ * passing vacuously, which is what makes the anchor safe to rely on.
+ */
+function openProjectBody(): { lines: string[]; start: number } {
+ const lines = indexSource.split('\n');
+ const start = lines.findIndex((l) => l.startsWith('async function openProject('));
+ if (start === -1) throw new Error('openProject not found in index.ts');
+ const end = lines.findIndex((l, i) => i > start && l === '}');
+ if (end === -1) throw new Error('openProject close brace not found');
+ return { lines: lines.slice(start, end + 1), start };
+}
+
+/**
+ * Milestones in the order the funnel reaches them. Source order is a valid
+ * proxy for execution order because the branches are textually exclusive and
+ * laid out in funnel order: the confirmation branch precedes the fresh-consent
+ * branch, and both precede the window fork.
+ *
+ * Two of them hold for a different reason. `probing ancestor size` and
+ * `resolving git root` are emitted from the `dirSizeProbe` and `gitTopLevel`
+ * callbacks, whose DEFINITIONS sit inline in the `await discoverProject`
+ * call between the two milestones that bracket it. They are invoked from
+ * `folder-admission.ts` during that same await, so source order remains a
+ * valid execution-order proxy -- but only while those closures stay inline.
+ * Extracting either to a module-level helper is a breaking change for this
+ * guard: runtime behavior would be identical, yet the message would leave
+ * `openProject`'s body slice and redden both the presence check and the
+ * exactly-once count below.
+ */
+const FUNNEL_MILESTONES = [
+ 'opening project',
+ 'resolving project admission',
+ 'probing ancestor size',
+ 'resolving git root',
+ 'project admission resolved',
+ 'project admission confirmation requested',
+ 'project admission confirmation answered',
+ 'awaiting navigator load',
+ 'onboarding consent requested',
+ 'onboarding consent answered',
+ 'ensuring project git',
+ 'ensured project git',
+ 'initializing project content',
+ 'initialized project content',
+ 'project artifacts written',
+ 'reclaiming project skills',
+ 'creating project window',
+ 'project window created',
+] as const;
+
+/**
+ * Largest run of consecutive CODE lines allowed without a funnel milestone.
+ *
+ * A coarse smoke alarm, not the load-bearing assertion — presence, order and
+ * ownership are. Line count only proxies for "unbounded work is unbracketed",
+ * and a few lines of new `await` inside a run still slip under it. Comment and
+ * blank lines are excluded so the margin means code, and prose churn cannot
+ * redden it.
+ *
+ * The rule, not just the endpoints: the cap is the current worst run rounded
+ * up to roughly 1.2x, so a single added block trips it. That is 62 code lines
+ * today, hence 75. Re-derive it whenever the metric or the milestone set
+ * changes, or the guard silently loosens while reading as if it tightened:
+ * excluding comment and blank lines drops roughly 18 lines from the worst run
+ * on its own, so a cap carried over unchanged widens the margin instead of
+ * holding it. For scale: 283 code lines before the milestones existed, one
+ * uninterrupted stretch from the entry log to the window-created log. The
+ * worst run today spans the managed-open skill reclaim and the
+ * `recordOnboardingFlow` call that follows it.
+ */
+const MAX_SILENT_RUN = 75;
+
+describe('openProject admission funnel milestones (bypass-pin)', () => {
+ const { lines: body, start: bodyStart } = openProjectBody();
+
+ test.each(FUNNEL_MILESTONES)('emits the %s milestone', (message) => {
+ expect(body.join('\n')).toContain(`'${message}'`);
+ });
+
+ test('milestones appear in funnel order', () => {
+ const text = body.join('\n');
+ const positions = FUNNEL_MILESTONES.map((m) => text.indexOf(`'${m}'`));
+ const outOfOrder = FUNNEL_MILESTONES.filter((_m, i) => {
+ const previous = positions[i - 1];
+ const current = positions[i];
+ return i > 0 && previous !== undefined && current !== undefined && current < previous;
+ });
+ expect(outOfOrder).toEqual([]);
+ });
+
+ test('every milestone is emitted by the project pino logger, not a console sink', () => {
+ for (const message of FUNNEL_MILESTONES) {
+ const at = body.findIndex((l) => l.includes(`'${message}'`));
+ expect({ message, present: at !== -1 }).toEqual({ message, present: true });
+
+ // Walk back to the call this message is an argument of, capturing the
+ // METHOD as well as the subsystem. Two downgrades read as instrumented
+ // here while emitting nothing in the build the bundles come from, and
+ // both must redden: moving a milestone to console.warn (the packaged
+ // main process discards that sink) and dropping it below the logger's
+ // default level, since resolveLogLevel returns 'info' outside tests.
+ let owner: string | null = null;
+ let ownerAt = at;
+ for (let i = at; i >= 0 && i > at - 40; i--) {
+ const line = body[i] ?? '';
+ const call = line.match(/getLogger\('([^']+)'\)\.(\w+)\(/);
+ if (call) {
+ owner = `${call[1]}.${call[2]}`;
+ ownerAt = i;
+ break;
+ }
+ if (/\bconsole\.(warn|log|error)\(/.test(line)) {
+ owner = 'console';
+ ownerAt = i;
+ break;
+ }
+ }
+ expect({ message, owner }).toEqual({ message, owner: 'project.info' });
+
+ // Every milestone must carry a correlating name. `openProject` has no
+ // single-flight guard, so two interleaved opens (a rapid Recents
+ // double-click, a deep link racing boot restore) otherwise produce lines
+ // attributable to neither. Nothing else here reads the payload, so a
+ // milestone simplified to a bare message would pass every other check.
+ // Code lines only: a comment inside the call that happens to name a key
+ // would otherwise satisfy this while the real payload carried nothing.
+ const payloadLines = body
+ .slice(ownerAt, at + 1)
+ .filter((l) => !/^\s*(?:\/\/|\*|\/\*)/.test(l));
+ // A ternary payload is TWO payloads, and testing them joined lets one
+ // arm's identifier vouch for the other: that is how the `rejected` arm
+ // of `project admission resolved` carried no name at all while this
+ // check stayed green. Split only at brace depth 0, which is what
+ // separates the payload-selecting ternary from the spread ternaries
+ // inside a payload, whose arms are legitimately nameless.
+ const arms: string[][] = [[]];
+ let depth = 0;
+ for (const line of payloadLines) {
+ if (depth === 0 && /^\s*[?:]\s/.test(line)) arms.push([]);
+ arms[arms.length - 1]?.push(line);
+ depth += (line.match(/\{/g)?.length ?? 0) - (line.match(/\}/g)?.length ?? 0);
+ }
+ // Split happened => arms[0] is the call head and the condition, not a payload.
+ const payloadArms = arms.length > 1 ? arms.slice(1) : arms;
+ // The concept, not three literal spellings: a milestone correlates if it
+ // names the resolved project or either form of the pick.
+ const unnamedArms = payloadArms
+ .filter((arm) => !/\bprojectName\b|\b(?:resolved)?[Pp]ickedName\b/.test(arm.join('\n')))
+ // The arm's own text, not a count: a bare `1` says the funnel regressed
+ // without saying which payload, which is the same misdirection the
+ // silent-run message below exists to avoid. Bounded because a long
+ // payload would bury the message it is attached to; the leading keys
+ // are what identify the arm, and they survive the cut.
+ .map((arm) => arm.join(' ').replace(/\s+/g, ' ').trim().slice(0, 80));
+ expect({ message, unnamedArms }).toEqual({ message, unnamedArms: [] });
+ }
+ });
+
+ test(`no run of more than ${MAX_SILENT_RUN} code lines is free of a milestone`, () => {
+ // Code lines only: a milestone-free stretch of comment prose is not the
+ // regression this guards, and counting it makes doc edits fail the gate.
+ // The body index rides along, because every index below is into the
+ // FILTERED array and the failure message has to name a line a maintainer
+ // can actually open.
+ const code = body
+ .map((line, bodyIndex) => ({ line, bodyIndex }))
+ .filter(({ line }) => line.trim() !== '' && !/^\s*(?:\/\/|\*|\/\*)/.test(line));
+ const emittingLines: number[] = [];
+ code.forEach(({ line }, i) => {
+ if (FUNNEL_MILESTONES.some((m) => line.includes(`'${m}'`))) emittingLines.push(i);
+ });
+ // Each milestone must occur exactly once, or the run maths below is
+ // measuring something other than the funnel (a duplicate, or a milestone
+ // whose emitting call site is gone).
+ expect(emittingLines.length).toBe(FUNNEL_MILESTONES.length);
+
+ // Boundaries count: entry-to-first and last-to-close are silent runs too.
+ const marks = [0, ...emittingLines, code.length - 1];
+ const runs = marks.slice(1).map((at, i) => ({ lines: at - (marks[i] ?? 0), endsAt: at }));
+ const worst = runs.reduce((a, b) => (b.lines > a.lines ? b : a));
+
+ // The message argument reports the offending stretch on failure — a bare
+ // numeric diff would say the funnel regressed without saying where.
+ // Reported as an index.ts line, not a body offset: the whole point is to
+ // spare a maintainer the hunt inside a 9k-line file.
+ const startsAt = bodyStart + (code[worst.endsAt - worst.lines]?.bodyIndex ?? 0) + 1;
+ expect(
+ worst.lines,
+ `worst milestone-free run is ${worst.lines} code lines, starting around index.ts:${startsAt}`,
+ ).toBeLessThanOrEqual(MAX_SILENT_RUN);
+ });
+});