Repository navigation
fix(bootstrap): print every phase's warnings and detect Windows absolute --ai-dir - #317
Conversation
…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
left a comment
There was a problem hiding this comment.
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.
-
[NIT] The hoist delivers "cannot reintroduce the gap" against omission, but not against
over-claiming.packages/cli/src/commands/bootstrap.ts:99is the only write toresult.steps
(singlesteps.push, insidecompletePhase), every one of the seven phases goes through it,
nothing constructs aBootstrapResultor mutatesstepselsewhere (result.stepsis otherwise
only read at:365,:366,:508), and there is no early return between the first phase and the
summary. I also confirmed nostep.warningsis populated after itscompletePhasecall — 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-269print 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 therender
callback is trusted to report truthfully.:323(phase 5) returnsinstallResult.step.warnings
wholesale, while the loop above it only draws warnings starting withHint:/Retry; the
Install failed: <msg>entry is claimed by the differently-wordedFailed: <details.error>line.
That claim is accurate today —runInstallPhase:1181-1186records exactly those three shapes and
details.erroris the samemsg— 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:287return is safe by
contrast: it returns the same array the loop directly above printed. Phase 1's:178adds the
NOT_IN_GIT_REPO_WARNINGconstant — 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: theif (render || printedWarning)guard at:109means 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 hardcodewarnings: []). -
[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 theN 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-installand
had no migratable configs, so neither branch was exercised in real output. -
[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-91paragraph 1 (therenderreturn 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. -
[NIT] Part 2's widening to
\project\.aiis correct — ruled on, with end-to-end evidence.
Beyond the unit matrix, I ran the real built CLI against a git-tracked.mcp.jsonfor seven values
(no--yes, so theforcepath at:824does 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\.aicannot 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.jsonis 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 --cachedescape hatch, neither of which is
path-flavour-specific. -
[NIT] The deleted count-comparison test: reasoning is sound and the test is genuinely absent.
gh pr diff 317contains notoBeGreaterThanOrEqual, 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 fromrunAdfInitPhasethat the first run could not have
recorded — aprinted >= recordedcomparison is then trivially satisfied and passes against buggy
main. Deleting it was right. Worth noting that the retained populate test at:665uses 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. -
[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
callsrequire('./adf-populate')atpackages/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 notrequirebeing undefined (I checked —requireresolves 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.jsresolves./adf-populate.js
normally. So production is genuinely unaffected, as claimed.
Ruling: the warning is environmental, but the code path under test —completePhaseprinting 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 genuineadfPopulateCommandthrow, e.g. an fs or parse failure). The
expect(populateWarnings.length).toBeGreaterThan(0)precondition at:671is the right instinct and
makes the dependence fail loudly rather than vacuously. The live hazard it leaves: converting that
requireto a staticimport— 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.
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 plaincharter bootstrapuser only as a number inBootstrap 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:
completePhaseappends the step toresult.steps, callsrenderto draw the phase's own section, then prints asWarning: <text>every warningrenderdid not report having already drawn, immediately before the section's trailing blank line. De-duplication is exact string matching against whatrenderreturns, 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 intoresult.steps—grep result.steps.pushreturns 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.renderis omitted for a phase that draws no section at all, which is how--mode leankeeps skipping the headers for phases 4-6.Existing output is preserved
Phases that word their warnings in their own format return them from
renderand are unchanged:detection.warnings<w>, noWarning:prefixstep.warningsFailed:line plusHint:/Retry manually:as<w>step.warningsA 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 synthesisesdetection.warningsas[], and the body loop only ever printed that array) and phase 4'sMigration failed:.2.
absoluteAiDirArgmissed Windows paths on POSIXThe stale-
--ai-dircheck from #298 gated onpath.isAbsolute, which is the POSIX implementation on a POSIX host and returnsfalseforC:\Users\...and\\server\share\.... A.mcp.jsonauthored 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.win32as well as the host's flavour. I usedpath.win32.isAbsoluterather 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:path.posix.isAbsolutepath.win32.isAbsoluteC:\Users\a\.aiC:/Users/a/.ai\\server\share\.ai\project\.aiC:project\.ai.ai/home/x/.ai\project\.aiis 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-relativeC:project\.aiis absolute under neither flavour and stays silent. The tracked-ness gate from #298 is untouched: an untracked.mcp.jsonremains the documented machine-local escape hatch.Tests
19 added. Measured, not reasoned: the final test set run against unmodified
maingivesTests 11 failed | 31 passed (42); on this branch,42 passed (42). Of those 11, five are genuine bug detectors and six are the newcompletePhasecontract 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 7prints the populate phase warnings in text output— phase 6warns about a drive-letter --ai-dir with backslasheswarns about a drive-letter --ai-dir with forward slasheswarns about a UNC --ai-dirGuards (pass on main; they catch an over-eager fix, not the bug):
pins an absolute --ai-dirwarning prints exactly once — catches double-printing by the hoistC:project\.aiand repo-relative.aistay silent.mcp.jsonwith a Windows path stays silentString.raw, pluscharCodeAtchecks 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 beThe phase-6 detector asserts
populateWarnings.length > 0before checking the text, on purpose:runPopulatePhasewarns in this environment because its barerequire('./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 succeedsPopulated 1 module(s)and the run reports0 warnings. Productioncharter bootstrapgains noPopulate failedline 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.jssilently no-ops in this checkout (pre-existing, unrelated), so afterpnpm buildI ranbootstrapCommandfrom the builtdist/commands/bootstrap.jsdirectly. Outside a git repository, wheredoctorgenuinely warns:Before this change that run printed the same
2 warnings.tally with only one of them visible. Inside a git repository the same build prints0 warningsand a clean phase 6. Nothing fromdist/is staged.Checks
pnpm test943/943 (baseline 931 + 12).pnpm run typecheckclean. Pre-committsc --noEmit+ ADF evidence gate passed;--no-verifynot 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
completePhasede-duplicates by exact string match against the arrayrenderreturns, and nothing type-checks that claim. Phase 5 returnedinstallResult.step.warningswholesale while drawing only theFailed:,Hint:andRetryshapes. Accurate today —runInstallPhaserecords exactly those three, anddetails.erroris the samemsg— 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
completePhaseis 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 jsonrecords the step and draws nothing.On the suggested
vi.mock: I probed it and it does not work here. Bothvi.mock('../commands/adf-populate', ...)andvi.mock('./adf-populate', ...)leave the recorded warning asCannot find module './adf-populate'rather than the mock's error —runPopulatePhasereaches the module through a bare Noderequire, 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
rendercontract.Checks
pnpm test950/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