Skip to content

fix(bootstrap): print every phase's warnings and detect Windows absolute --ai-dir - #317

Merged
stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-307
Sep 20, 2026
Merged

stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-307

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Closes #307

Two independent one-file fixes in packages/cli/src/commands/bootstrap.ts.

1. Phases 6 and 7 swallowed their warnings

Every phase did warnings += xResult.step.warnings.length, but only some printed the text under --format text. Phase 6 (populate) and phase 7 (doctor) never did, so a warning raised there reached a plain charter bootstrap user only as a number in Bootstrap complete. N warnings. — the wording existed solely under --format json.

That is not cosmetic. #304 found the same silence in phase 2, where the invisible text had been advising a destructive bootstrap --force (#305), unnoticed precisely because it never printed.

The issue asked for the hoist rather than two more copies of the print loop, and the hoist is what this does. Recording a phase and showing it are now a single operation:

function completePhase(
  result: BootstrapResult,
  options: CLIOptions,
  step: StepResult,
  render?: () => readonly string[],
): number

completePhase appends the step to result.steps, calls render to draw the phase's own section, then prints as Warning: <text> every warning render did not report having already drawn, immediately before the section's trailing blank line. De-duplication is exact string matching against what render returns, and no type enforces that claim, so each section claims only strings it actually printed (see round 2 below). It is the only code path into result.steps — grep result.steps.push returns one hit, inside the helper — so a phase cannot reach the JSON payload without its warnings reaching the screen. A phase 8 cannot reintroduce the gap by omission.

render is omitted for a phase that draws no section at all, which is how --mode lean keeps skipping the headers for phases 4-6.

Existing output is preserved

Phases that word their warnings in their own format return them from render and are unchanged:

Phase Own wording Returned as already-drawn
1 detect not-a-git-repo notice wrapped over three lines that warning + detection.warnings
4 migrate dry-run list printed as <w>, no Warning: prefix all of step.warnings
5 install Failed: line plus Hint:/Retry manually: as <w> all of step.warnings

A captured full text run before and after the change differs by exactly the two newly printed warnings and nothing else (the populate one wraps over three physical lines, so the diff shows four added lines). The summary tally is unchanged: the standalone warnings++ that compensated for counting the git warning before it was pushed is now redundant and removed.

Two further warnings that were recorded and never printed now surface, which is the same bug and deliberate: phase 1's Detection failed: (its catch path synthesises detection.warnings as [], and the body loop only ever printed that array) and phase 4's Migration failed:.

2. absoluteAiDirArg missed Windows paths on POSIX

The stale---ai-dir check from #298 gated on path.isAbsolute, which is the POSIX implementation on a POSIX host and returns false for C:\Users\... and \\server\share\.... A .mcp.json authored on native Windows is read on a POSIX host every time it reaches CI, a container or a colleague's Linux checkout — the same cross-platform class as the WSL /mnt/c/... path originally reported — and it passed in silence.

The value is now tested under path.win32 as well as the host's flavour. I used path.win32.isAbsolute rather than hand-rolled regexes: it is documented Node behaviour covering both requested forms and removes the escaping question from the source entirely. Verified empirically on this host:

value path.posix.isAbsolute path.win32.isAbsolute warns
C:\Users\a\.ai false true yes
C:/Users/a/.ai false true yes
\\server\share\.ai false true yes
\project\.ai false true yes
C:project\.ai false false no
.ai false false no
/home/x/.ai true true yes (unchanged)

\project\.ai is a superset of the issue's ask — rooted but driveless. It is machine-specific for the same reason, so it is flagged, and the JSDoc says so. Drive-relative C:project\.ai is absolute under neither flavour and stays silent. The tracked-ness gate from #298 is untouched: an untracked .mcp.json remains the documented machine-local escape hatch.

Tests

19 added. Measured, not reasoned: the final test set run against unmodified main gives Tests 11 failed | 31 passed (42); on this branch, 42 passed (42). Of those 11, five are genuine bug detectors and six are the new completePhase contract tests, which fail on main only because the function does not exist there (completePhase is not a function) — they are guards on new code, not detectors.

Genuine bug detectors (the 5 that fail on main):

  • prints the doctor phase warning in text output — phase 7
  • prints the populate phase warnings in text output — phase 6
  • warns about a drive-letter --ai-dir with backslashes
  • warns about a drive-letter --ai-dir with forward slashes
  • warns about a UNC --ai-dir

Guards (pass on main; they catch an over-eager fix, not the bug):

  • setup's pins an absolute --ai-dir warning prints exactly once — catches double-printing by the hoist
  • the not-a-git-repo notice does not gain a raw one-line duplicate alongside its three wrapped lines
  • lean mode gains no headers for phases 4-6
  • drive-relative C:project\.ai and repo-relative .ai stay silent
  • an untracked .mcp.json with a Windows path stays silent
  • the Windows fixtures' own bytes are asserted (String.raw, plus charCodeAt checks that the UNC fixture starts with exactly two backslashes and the drive-relative one has no separator), so a test cannot pass on a string that is not actually the path it claims to be

The phase-6 detector asserts populateWarnings.length > 0 before checking the text, on purpose: runPopulatePhase warns in this environment because its bare require('./adf-populate') does not resolve under vite-node. That lever is environmental, and I checked what it means for a real user: in the built CLI the require resolves, populate succeeds Populated 1 module(s) and the run reports 0 warnings. Production charter bootstrap gains no Populate failed line from this PR. The precondition assertion means that if the vite-node lever ever disappears the test fails loudly rather than passing vacuously.

I also wrote and then deleted a test that compared the printed warning count against the recorded count. It passed against buggy main — it necessarily compares a JSON run with a second text run over the files the first one wrote, so the second run's extra warnings made the >= trivially true. It proved nothing, so it is not in the diff.

Verified against the built CLI, not only the test harness

packages/cli/dist/index.js silently no-ops in this checkout (pre-existing, unrelated), so after pnpm build I ran bootstrapCommand from the built dist/commands/bootstrap.js directly. Outside a git repository, where doctor genuinely warns:

[7/7] Running health check...
  [warn] Git repository
  [ok] config.json
  [ok] Patterns loaded
  [ok] ADF manifest
  Warning: Some health checks returned warnings.

Bootstrap complete. 2 warnings.

Before this change that run printed the same 2 warnings. tally with only one of them visible. Inside a git repository the same build prints 0 warnings and a clean phase 6. Nothing from dist/ is staged.

Checks

pnpm test 943/943 (baseline 931 + 12). pnpm run typecheck clean. Pre-commit tsc --noEmit + ADF evidence gate passed; --no-verify not used.


Round 2 — closing two latent traps

Neither was a defect; both are the class of trap this PR exists to eliminate.

Phase 5 no longer claims more than it drew

completePhase de-duplicates by exact string match against the array render returns, and nothing type-checks that claim. Phase 5 returned installResult.step.warnings wholesale while drawing only the Failed:, Hint: and Retry shapes. Accurate today — runInstallPhase records exactly those three, and details.error is the same msg — but a fourth warning added later would have been swallowed with no test failing. It now accumulates the strings it actually printed and claims only those, matching what phase 4 already did. The JSDoc now states the trust relationship, since no type carries it.

Verified by construction, not by reasoning. With phase 5 reverted to the wholesale claim the new end-to-end guard still passes (today's claim is accurate, so it is a future guard, not a detector of current code); with the section additionally stopped from drawing Hint/Retry it fails with install warning is invisible in text output: Retry manually: npm install.

Phase 6's test no longer rests only on a resolver quirk

completePhase is now exported and tested directly — the repo already exports internals this way (filePathToKeywords, buildSuggestReport). Six unit tests pin the contract: an unclaimed warning prints; a claimed one does not reprint; a partial claim leaves the rest to the helper (the phase 5 trap); a phase drawing no section still surfaces warnings; a silent one prints nothing; --format json records the step and draws nothing.

On the suggested vi.mock: I probed it and it does not work here. Both vi.mock('../commands/adf-populate', ...) and vi.mock('./adf-populate', ...) leave the recorded warning as Cannot find module './adf-populate' rather than the mock's error — runPopulatePhase reaches the module through a bare Node require, which resolves outside vitest's module graph. So the end-to-end phase 6 test keeps its explicit precondition, now documenting the quirk and telling a future maintainer to delete the test if it ever trips, because the contract tests cover that path deliberately. Production is unaffected either way: the built CLI resolves the module and records no warning.

JSDoc trimmed

Dropped the #304/#307 history paragraph (it restated the CHANGELOG) and the "Returns the number of warnings…" line (it restated the signature). Kept the render contract.

Checks

pnpm test 950/950, typecheck clean. Built-CLI output across the same non-git fixture is byte-identical to the previously reviewed build apart from the temp directory name, so round 2 changed no user-visible output.

🤖 Generated with Claude Code

…ute --ai-dir (closes #307)

Two independent defects in commands/bootstrap.ts.

1. Phases 6 (populate) and 7 (doctor) counted their warnings into
`Bootstrap complete. N warnings.` but never printed the text, so a plain
`charter bootstrap` reported a number with nothing on screen to read. The
wording was reachable only under --format json. #304 fixed exactly this in
phase 2, where the invisible text had been advising a destructive
`bootstrap --force` (#305) -- unnoticed because it never printed.

Copying that print loop into two more places would fix today's bug and leave
the trap armed for a phase 8, so recording a phase and showing it are now one
operation. Every phase passes through completePhase(), which appends the step
to the result, draws the phase's section, and prints as `Warning: <text>`
whatever the section did not already word itself. It is the only code path
into result.steps, so a phase cannot land in the JSON payload without its
warnings landing on screen.

Phases that word their own warnings return them and are unchanged: phase 1's
three-line wrapped not-a-git-repo notice, phase 4's dry-run list printed
without the `Warning:` prefix, and phase 5's Failed:/Hint:/Retry manually:
lines. A before/after capture of a full text run differs by exactly the two
newly printed warnings and nothing else; the tally is unchanged, because the
separate `warnings++` that compensated for counting the git warning before it
was pushed is now redundant and gone.

Two more previously recorded, never printed warnings now surface: phase 1's
`Detection failed:` (its catch path synthesises detection.warnings as empty,
so only the body loop's source was printed) and phase 4's `Migration failed:`.

2. absoluteAiDirArg gated on path.isAbsolute, which is the POSIX
implementation on a POSIX host and returns false for `C:\Users\...` and
`\\server\share\...`. A .mcp.json authored on native Windows is read on a
POSIX host every time it reaches CI, a container or a colleague's checkout --
the same cross-platform case as the WSL path in #298 -- and the stale-path
warning stayed silent. The value is now also tested under path.win32, which
covers drive-letter and UNC roots without a hand-rolled regex to escape wrong.
`\project\.ai` is absolute under path.win32 too and is flagged for the same
machine-specific reason; drive-relative `C:project\.ai` is not, and stays
unflagged, as does the repo-relative `.ai` bootstrap writes. The tracked-ness
gate from #298 is untouched.

Tests: 12 added. Measured against unmodified main, 5 fail and 30 pass; after
the fix 35/35. The 5 are the genuine detectors -- the doctor and populate
warnings reaching text output, and drive-letter (backslash and forward slash)
and UNC --ai-dir values being flagged. The rest are guards that already passed
on main and would catch an over-eager fix: setup's stale --ai-dir warning
printed exactly once, the not-a-git-repo notice not gaining a raw one-line
duplicate, lean mode not growing sections for phases it skips, drive-relative
and repo-relative values staying silent, and an untracked .mcp.json staying
silent. One further guard asserts the Windows fixtures' own byte content, so a
test cannot pass on a single-backslash UNC string that is not a UNC path.

Closes #307

@stackbilt-admin stackbilt-admin left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVED

Verified empirically on this host, not read-only. Red/green reproduced by swapping in
c88747f:packages/cli/src/commands/bootstrap.ts (scratchpad backup, restored; git diff clean):
main → 5 failed / 30 passed, exactly the five named (phase-7 doctor text, phase-6 populate text,
drive-letter backslash, drive-letter forward-slash, UNC); branch → 35 passed. Full CLI suite on
the branch: 333 passed / 31 files. The honestly-labelled split holds — no guard test fails on main.

  1. [NIT] The hoist delivers "cannot reintroduce the gap" against omission, but not against
    over-claiming.
    packages/cli/src/commands/bootstrap.ts:99 is the only write to result.steps
    (single steps.push, inside completePhase), every one of the seven phases goes through it,
    nothing constructs a BootstrapResult or mutates steps elsewhere (result.steps is otherwise
    only read at :365, :366, :508), and there is no early return between the first phase and the
    summary. I also confirmed no step.warnings is populated after its completePhase call — the
    only post-hoc push is :161 (not-in-git-repo), which precedes the call at :164; the orphan and
    manifest-self-check blocks at :221-269 print directly but touch no recorded step. So a phase
    cannot reach the JSON payload without printing, and a phase 8 that simply forgets to print is
    structurally impossible. The residual hole is the other direction: de-duplication is
    alreadyRendered.includes(warning) at :105, i.e. exact string equality with an array the render
    callback is trusted to report truthfully. :323 (phase 5) returns installResult.step.warnings
    wholesale, while the loop above it only draws warnings starting with Hint:/Retry; the
    Install failed: <msg> entry is claimed by the differently-worded Failed: <details.error> line.
    That claim is accurate today — runInstallPhase:1181-1186 records exactly those three shapes and
    details.error is the same msg — but a fourth warning added to that phase later would be
    silently swallowed with no test failing. Returning only the strings actually drawn (the
    install-failed one plus the filtered Hint/Retry) would close it. Phase 4's :287 return is safe by
    contrast: it returns the same array the loop directly above printed. Phase 1's :178 adds the
    NOT_IN_GIT_REPO_WARNING constant — and because the constant is the literal pushed at :161,
    string equality holds; the whitespace-drift risk is real in principle but there is no site where a
    render hand-rolls a copy of a warning string.
    Also noted, in the helper's favour: the if (render || printedWarning) guard at :109 means a
    render-less phase with warnings would print them orphaned rather than swallow them — fail-loud is
    the right default. Unreachable today (both lean-mode stub steps hardcode warnings: []).

  2. [NIT] Formatting is byte-identical to main except the intended new line — verified, not asserted.
    I ran the built CLI (dist, tsc) against three fixtures on main and on the branch and diffed
    (tempdir names normalised): non-git text run → identical; --mode lean → identical (no headers,
    no blank-line drift); --format json → identical (the JSON payload and the N warnings. tally are
    untouched). The only delta anywhere is a single added line in the doctor run:
    + Warning: Some health checks returned warnings. — with the summary still reading
    Bootstrap complete. 2 warnings. on both sides, which is precisely #307: main counted two and
    printed one. Exit code unchanged (0). Phase 1's wrapped three-line notice is unchanged in that real-output diff. Phase 5's
    Failed:/Hint:/Retry manually: shape and phase 4's dry-run list are unchanged by inspection of
    the source (:301-324, :278-290) — not by the fixture runs, which all passed --skip-install and
    had no migratable configs, so neither branch was exercised in real output.

  3. [NIT] Net +34 lines: the helper earns it; ~9 lines of the JSDoc do not. The goal was a control-flow
    invariant, not a DRY win, so judging it on line count is the wrong axis — but the split matters for
    maintenance. :76-91 paragraph 1 (the render return contract: what you return is what gets
    suppressed) is load-bearing — it is the only place the trust relationship that finding 1 turns on is
    written down, and no type enforces it. Paragraph 2 (the #304/#307 history) restates the CHANGELOG
    entry nearly verbatim, and :91's "Returns the number of warnings… for the summary tally" restates
    the signature. Keep paragraph 1; the rest is padding. Not worth a round trip.

  4. [NIT] Part 2's widening to \project\.ai is correct — ruled on, with end-to-end evidence.
    Beyond the unit matrix, I ran the real built CLI against a git-tracked .mcp.json for seven values
    (no --yes, so the force path at :824 does not short-circuit the check). Warned, with the path
    echoed verbatim: /home/someone-else/project/.ai, C:\Users\…, C:/Users/…, \\build-server\share\…,
    \project\.ai. Silent: C:project\.ai (drive-relative — falls through to the generic "already defines
    mcpServers.charter" message, which is the correct different warning) and .ai (identical to desired,
    returns before any warning). A driveless rooted \project\.ai cannot be a legitimate committed value:
    on POSIX it is a relative filename containing backslashes, on Windows it resolves against the current
    drive — machine-specific for exactly the reason the check exists. The widening is safe on top of that
    because the gate is unchanged and conservative: it fires only when .mcp.json is tracked
    (:831), it is advisory, and it does not change the exit code. packages/cli/src/commands/bootstrap.ts:752.
    One wording check: the remedy text still reads correctly for a Windows value — it names the exact
    replacement ".ai" and the .gitignore/git rm --cached escape hatch, neither of which is
    path-flavour-specific.

  5. [NIT] The deleted count-comparison test: reasoning is sound and the test is genuinely absent.
    gh pr diff 317 contains no toBeGreaterThanOrEqual, no >=, and no warning-count assertion. The
    stated defect is real: runBothFormats (bootstrap.test.ts:634) necessarily runs JSON first and text
    second over the files the first run created, so the second run picks up extra "already exists;
    skipping" / "has custom content" warnings from runAdfInitPhase that the first run could not have
    recorded — a printed >= recorded comparison is then trivially satisfied and passes against buggy
    main. Deleting it was right. Worth noting that the retained populate test at :665 uses the same
    two-run helper without inheriting the flaw, because it asserts per-string membership of the
    JSON-recorded populate warnings in the text log rather than comparing counts, and that particular
    warning is identical across both runs.

  6. [NIT] Phase-6 test lever: established exactly, and it is an artifact — but a tolerable one.
    The implementer's truncated claim is correct but was never pinned down; here it is. runPopulatePhase
    calls require('./adf-populate') at packages/cli/src/commands/bootstrap.ts:1237. Under vitest the
    module identity is the TypeScript source, so Node's CJS resolver looks for
    packages/cli/src/commands/adf-populate.{js,json,node} and finds nothing. I probed it directly
    (isolated vitest run outside the repo, importing the branch source): the recorded warning is literally
    Populate failed (non-fatal): Cannot find module './adf-populate'\nRequire stack:\n- …/src/commands/bootstrap.ts.
    Two things this is not: it is not require being undefined (I checked — require resolves fine under
    this vitest/vite version), and it is not a production condition. Running the built CLI, steps[populate]
    is {"status":"pass","warnings":[]} — dist/commands/bootstrap.js resolves ./adf-populate.js
    normally. So production is genuinely unaffected, as claimed.
    Ruling: the warning is environmental, but the code path under test — completePhase printing a
    phase-6 warning it did not draw itself — is production code exercised for real, and that is where the
    bug was. Accepted as a regression guard; it is not evidence that phase 6 warns in the field (in
    practice it takes a genuine adfPopulateCommand throw, e.g. an fs or parse failure). The
    expect(populateWarnings.length).toBeGreaterThan(0) precondition at :671 is the right instinct and
    makes the dependence fail loudly rather than vacuously. The live hazard it leaves: converting that
    require to a static import — an obvious future cleanup — would make phase 6 stop warning under vitest and break this test for a
    reason unrelated to #307. vi.mock('./adf-populate', () => { throw new Error('boom'); }) would make
    the intent explicit and the test independent of the resolver quirk.

Working tree. git status --porcelain at the end shows only untracked files and git diff /
git diff --cached are empty — no tracked modification, nothing staged, nothing committed or pushed.
Four untracked paths are present: .ai/context.adf, .ai/context.snapshot.json, .ai/frontend.adf,
copilot-instructions.md. The latter two are beyond the expected set but predate this review session —
all four were already listed in the session-start snapshot before I touched anything — so I left them
alone rather than deleting another agent's files. Everything I created (the main-version swap, the CLI
fixtures, the vitest probe and its symlinked node_modules) lived in the session scratchpad and has been
removed or restored; the source swap was restored by cp from the scratchpad backup and verified with
git diff --quiet. The only thing I wrote inside the repo is packages/cli/dist/, which is gitignored
(.gitignore:2) and was rebuilt from the branch source as the last step.

Review follow-up on #307. The hoist already makes omission impossible -- one
steps.push, all seven phases through it. This closes the other half of the
contract, which nothing type-checks: completePhase de-duplicates by exact string
match against the array `render` returns, so a render that claims a warning it
never printed swallows it.

Phase 5 returned installResult.step.warnings wholesale while drawing only the
`Failed:`, `Hint:` and `Retry` shapes. That is accurate today -- runInstallPhase
records exactly those three and details.error is the same msg -- but a fourth
warning added to that phase later would have been silently swallowed with no
test failing. It now accumulates the strings it actually printed and claims only
those, matching what phase 4 already does.

The JSDoc drops the #304/#307 history paragraph, which restated the CHANGELOG,
and the "Returns the number of warnings" line, which restated the signature. It
keeps the render contract and now states the trust relationship the de-dup turns
on, since no type enforces it.

completePhase is exported so the contract can be tested directly; the repo
already exports internals this way (filePathToKeywords, buildSuggestReport).
Six unit tests pin it: an unclaimed warning prints, a claimed one does not
reprint, a partial claim leaves the rest to the helper (the phase 5 trap), a
phase with no section still surfaces warnings, a silent one prints nothing, and
--format json records the step while drawing nothing.

Added one end-to-end guard on the real phase 5: every warning it records must be
readable somewhere in its section. Verified by construction rather than by
reasoning -- with phase 5 reverted to the wholesale claim it still passes, because
today that claim is accurate, and with the section additionally stopped from
drawing Hint/Retry it fails with "install warning is invisible in text output:
Retry manually: npm install". It is a guard against a future over-claim, not a
detector of current code.

The reviewer suggested vi.mock for the phase 6 require. Probed both spellings --
vi.mock('../commands/adf-populate') and vi.mock('./adf-populate') -- and neither
intercepts it: runPopulatePhase reaches the module through a bare Node require,
which resolves outside vitest's module graph, so the recorded warning is still
the resolver error rather than the mock's. The phase 6 end-to-end test therefore
keeps its explicit precondition, now documenting the quirk and telling a future
maintainer to delete the test if it ever trips, since the contract tests cover
that path deliberately.

Tests 950/950, typecheck clean. Built-CLI output byte-identical to the previously
reviewed build across the same fixture.
@stackbilt-admin
stackbilt-admin merged commit ba616de into main Sep 20, 2026
5 checks passed
@stackbilt-admin
stackbilt-admin deleted the auto/bugfix/issue-307 branch September 20, 2026 15:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bootstrap: phases 6/7 collect warnings without printing them; absoluteAiDirArg misses Windows paths on POSIX

1 participant