* test(260903-m7p): expose configured-entrypoint validation gap * enhance(260903-m7p): validate configured entrypoints before success * test(260903-m7p): require pre-success entrypoint validation * enhance(260903-m7p): gate install success on entrypoints * test(260903-m7p): cover configured entrypoints across runtimes * enhance(260903-m7p): cover emitted runtime entrypoints * fix(260903-m7p): sandbox HOME in finishInstall test and fix changeset pr number - finishInstall(...'cline'...) calls writeNonClaudeDefaults(runtime) in-process before the new configured-entrypoint assertion throws. Without a HOME + config-location-env sandbox that write resolved through the ambient environment and landed in the developer's live ~/.gsd (confirmed absent on origin/next baseline, present only on this branch — full-suite HERMETICITY WARNING). Sandbox HOME/USERPROFILE and scrub config-location env for the duration of the test, matching the existing in-process finishInstall/ install() pattern in tests/install.test.cjs (#2665). - .changeset/quick-wasps-sing.md: pr: 0 is a never-backfilled placeholder (CONTRIBUTING.md) that fails changeset-lint's invalid_pr check; set to the fork PR number until the upstream PR number is known. * fix(260903-m7p): repair cross-platform and pre-existing shape fallout - tests/configured-entrypoint-validation.test.cjs: the win32 branch of ensureCodexHooksJsonSessionStart writes a .cmd shim under <codexRoot>/hooks/; create that dir in the test (the real installer only calls this once hooks/gsd-check-update.js already exists) and assert the platform-common entrypoint shape instead of a fixed non-Windows array, since win32 legitimately emits two entries (cmd shim + script). - tests/install.test.cjs: finishInstall's shared settings-json return now carries configuredEntrypoints/rollbackInstallerMigrations for every runtime on that path (trae included, not just Claude/Cursor/Windsurf); update the trae install() exact-shape assertion to match. * fix(260903-m7p): keep .sh interpreter tracking consistent with unresolved bash configuredEntrypointsForHook's shell branch dropped interpreterCandidates entirely when resolveBashExecutable returned null, unlike the sibling portableHooks runner entry a few lines below (which correctly falls back to the literal 'bash' token). Found via agy adversarial review; verified unreachable through the current call graph (buildHookCommand's own resolveBashRunner==null gate already short-circuits before recordConfiguredHookCommand runs), so this is a defensive consistency fix, not a live-bug patch — kept for the next caller that does not share that gate. * chore(260903-m7p): backfill changeset pr number to the opened upstream PR .changeset/quick-wasps-sing.md carried the fork PR number (16) as a placeholder until the upstream PR existed; open-gsd/gsd-core#4249 is now open, so record its real number per CONTRIBUTING.md's changeset pr-field convention. * fix(#4154): track already-registered hooks for entrypoint validation on update applySettingsJsonHooks registers each guard hook only if absent, so a hook already present from a prior install keeps its stale on-disk command. The new entrypoint tracker always records the freshly-computed command for it, which never matches what is actually persisted, so the exact-string filter in finishInstall silently dropped it from validation — the Blocker case this feature exists to catch (an already-installed entrypoint going stale between installs) was exactly the case it never validated. Match on the managed script's basename instead, which the persisted command carries either way, so an already-registered hook stays in the validated set. Regression test forces this path by mutating a freshly-installed hook's persisted command before a second install. * fix(#4154): distinguish an unreadable script from a missing one validateConfiguredEntrypoints folded an EACCES statSync failure into the same 'missing' reason as ENOENT, misreporting a real permission problem as an absent file. Check the error code and report 'unreadable' instead. * docs(#4154): document entrypoint validation's rollback and PATH scope CONTEXT.md's Runtime Hooks Surface Module / Installer Module entries had no mention of ConfiguredEntrypoint/validateConfiguredEntrypoints, despite bin/install.js x CONTEXT.md being this repo's strongest co-change pairing. The update-gsd.md how-to overstated what a validation failure undoes: for Codex/Cursor/Windsurf/Kimi, their own writer already persisted hooks.json/ config.toml inside install() before the aggregate validation call runs, so there is no rollback path for that write regardless of "where available" phrasing. Also note that interpreter resolution checks the installer's own PATH, not necessarily the PATH a hook fires under later (#2979 launchers). * chore(#4154): point changeset pr field at the fork PR while CI runs there Mirrors the branch's own prior backfill commit: pr: matches whichever PR number changeset-lint is currently validating against (fork PR #16 during the fork-first CI/review loop), flipped back to the upstream PR number right before the final push to open-gsd/gsd-core. * fix(#4249): address adversarial-review findings in entrypoint validation An internal adversarial review (agy/gemini-3.8-flash-high) of the whole PR found several real gaps beyond the human reviewer's Blocker, verified against source before fixing: - Codex's install() result bound rollbackInstallerMigrations to the narrow installer-migrations-only rollback instead of restoreCodexSnapshot (#3245), the full pre-install snapshot/restore Codex already owns for exactly this case — a validation failure discovered outside install() reverted nothing of the config.toml/hooks.json that call had already written. - The register-only-if-absent basename match from the prior fix used a bare substring, which an unrelated user command mentioning the same filename could false-positive into GSD's validated set — anchored on the `/hooks/<basename>` path segment instead. - nodeCandidates checked raw process.execPath (always true — we're running in that process) instead of normalizeNodePath's stable version-manager alias, the same one buildNodeRunnerChainToken bakes as its first choice — a false green regardless of whether that alias itself still resolves. - An entry with no interpreterCandidates (Cline's PreToolUse hook, or a Windows-Claude .sh hook invoked without a bash runner) runs via its own shebang; validateConfiguredEntrypoints checked only file-type, never the execute bit. Cline's writer also never reported an entrypoint at all. - Duplicate (configPath, scriptPath) entries (e.g. Kimi's context-monitor hook registered across several events) were validated once per duplicate. Each fix is covered by a new or extended test; the Codex one required inlining runCodexInstall's env sandboxing so the rollback closure — which re-resolves the $HOME-relative skills root live — runs before the sandbox is torn down, matching how installAllRuntimes' real aggregate gate calls it. * docs(#4249): document the round-2 entrypoint-validation fixes Runtime Hooks Surface Module and Installer Module entries now name ConfiguredEntrypoint's not-executable reason, the normalizeNodePath alignment, Cline's tracked hook, and which install() result the finishInstall/installAllRuntimes rollback path actually reverts per runtime (Codex's full snapshot vs. the others' narrow migrations-only rollback). * chore(#4249): point changeset pr field at the upstream PR now that fork CI is green * fix(#4249): address agy adversarial-review findings - validateConfiguredEntrypoints: statSync alone never detects a chmod-000 script (it only needs parent-dir search permission), so an interpreter-invoked entry with an unreadable script passed validation. Add an explicit R_OK check for the interpreterCandidates branch only — the candidate-less/shebang branch already has its own X_OK gate. - docs/how-to/update-gsd.md: the blanket "does not revert" claim was false for Codex, which reverts config.toml/hooks.json via its full pre-install snapshot; qualify it per runtime. - tests/codex-config.test.cjs: the #4249 rollback regression test asserted skills/ and VERSION were reverted but never asserted config.toml/hooks.json were too, despite the test's own stated intent. - CONTEXT.md: qualify which interpreterCandidates entries get normalizeNodePath'd (Node hooks only, not .sh/bash) and note Codex's Windows .cmd shim as a third candidate-less case that relies on extension dispatch, not a shebang. * fix(#4249): validate Cline's PATH-dependent interpreter, not just its execute bit Cline's hook is a hybrid: it self-executes via '#!/usr/bin/env node', so it needs the execute bit (like any shebang-invoked entry), but its interpreter is looked up on PATH by 'env' at hook-fire time (unlike every other GSD JS hook, which bakes an absolute node path specifically to avoid that dependency). The candidate-less/interpreterCandidates fork treated these as mutually exclusive, so Cline's entry silently skipped interpreter resolution entirely — a completely missing 'node' on PATH would still validate successfully. Add an orthogonal selfExecutable flag so both checks run for entries that need them. (CodeRabbit finding on the fork rehearsal PR.) * fix(#4249): address second-round adversarial review findings (opus + agy) - validateConfiguredEntrypoints: R_OK now runs for every scriptOk entry, not just interpreterCandidates ones — a self-executable shebang script is still opened and read by its kernel-invoked interpreter, so X_OK alone never proved it was readable. - selfExecutable is now the sole, explicit source of truth for the execute-bit check (every producer that needs it sets the flag) instead of being partly inferred from an absent interpreterCandidates, which Cline's hybrid entry also carries. - The execute-bit check now skips explicitly on win32 (matching resolveExecutableBinary's own carve-out) instead of relying on Node's accessSync(X_OK)-as-F_OK no-op, which only protects a real Windows machine and not a test that simulates win32 on a POSIX runner. - bin/install.js: fixed a stale comment claiming no runtime's install()-time writes have a rollback path — Codex's does (restoreCodexSnapshot) — and added the omitted Cline to both that comment and CONTEXT.md's equivalent lists. - CONTEXT.md: fixed the Cline description left stale by the previous commit's selfExecutable addition, and rewrote the validation-mechanism paragraph for clarity (writing-for-agents pass). - docs/how-to/update-gsd.md: split an overloaded 4-clause sentence. - Removed a fault-injection integration test that could not reliably exercise the real installAllRuntimes -> finalize -> rollback wiring without fighting the installer's own pre-registration existence guards; the constituent pieces remain covered individually. * fix(#4249): pin platform in X_OK-testing entries so they're deterministic cross-CI-runner X_OK is a POSIX-only concept, skipped entirely when an entry's platform is win32 (matching production). Two test entries omitted platform, defaulting to process.platform — on an actual windows-latest CI runner that silently skipped the very check they were meant to exercise, turning 'not-executable' into a false pass. Pin platform: 'linux' so these are deterministic regardless of which OS runs the suite. * fix(#4249): classify EPERM the same as EACCES in statSync error handling Windows raises EPERM (not EACCES) for a parent directory that couldn't be traversed into — was falling through to 'missing', misreporting a genuine permission problem as a nonexistent path. * docs(#4249): address final CodeRabbit doc-completeness findings - CONTEXT.md: install()'s documented result shape omitted configuredEntrypoints; the ConfiguredEntrypoint shape omitted selfExecutable. - docs/how-to/update-gsd.md: the failure-mode sentence omitted unreadable and lacks-execute-permission, which the installer also rejects. * fix(#4249): stop double-validating every configured entrypoint on install/update installAllRuntimes' finalize() already runs assertConfiguredEntrypoints once over the aggregate set; finishInstall then re-ran the identical check per runtime in the printSummaries loop right after, so every entrypoint paid its statSync/accessSync/interpreter-resolution cost twice on every install and update. Add entrypointsAlreadyValidated to skip the redundant pass specifically on that path, while leaving the check intact for any caller that invokes finishInstall directly. * chore(#4154): point changeset pr field at rehearsal fork PR while CI runs there * perf(#4249): memoize interpreter candidate resolution across entrypoints resolveExecutableBinary walked PATH once per (entry, candidate) pair; a typical install has a dozen-plus entries sharing the same few candidate lists (process.execPath for JS hooks, bash for shell hooks). Cache by (platform, candidate) so each distinct pair resolves once per validation call instead of once per entry. * chore(#4249): point changeset pr field at the rebased rehearsal fork PR * fix(#4249): drop entrypoint tracking from the now-dead Codex event writer #2586 (landed on next after this branch forked) removed install.js's CODEX_EXTENDED_HOOK_EVENTS registration loop, so ensureCodexHooksJsonEvent no longer runs during install or update. The ConfiguredEntrypoint records this branch added inside it were therefore unreachable and untested. Restore the function to its upstream shape; the entrypoints it used to report were never collected by any caller. * refactor(#4249): drop the revalidation bypass flag and the candidate cache Both were this PR's own micro-optimisations over a set of roughly a dozen entries. `entrypointsAlreadyValidated` let a caller turn the finishInstall gate off to save one statSync/accessSync pass; `resolvedCandidateCache` memoised resolveExecutableBinary across entries that are already deduped by (configPath, scriptPath). Neither is measurable, and the flag was the only way to reach finishInstall with validation disabled. finishInstall now always validates what it is given. * chore(#4249): point the changeset pr field back at the upstream PR * refactor(#4249): track settings.json entrypoints without the hooksSurface gate The install-surface writer only tracked configured entrypoints when the runtime's descriptor also declared `hooksSurface: 'settings-json'`. Nothing asserts that axis agrees with `installSurface`, so a descriptor that broke the coupling would silently pass `configuredEntrypoints: undefined` and drop that runtime out of the validation this PR adds — reintroducing the exact 'reports Done! over a broken entrypoint' failure #4154 exists to close. Remove the dependence rather than test it: everything recorded on this path lands in settings.json by construction, and the registered-command filter already discards entries no persisted hook references. * chore(#4249): put the changeset body in the documented two-part format CONTRIBUTING.md and .changeset/README.md both show `**<bold change>** — <symptom-led explanation>.`; the fragment was a single unbolded sentence. * chore(#4249): point the changeset pr field at the rehearsal fork PR while CI runs there * fix(#4249): restore the whole manifest-tracked GSD file set on Codex rollback #3245's snapshot covers config.toml, hooks.json, skills/gsd-*, agents/gsd-* and gsd-core/VERSION. The install overwrites every other GSD-owned file too — hooks/, gsd-core/CHANGELOG.md, scripts/, gsd-core/.gsd-runtime, the manifest itself — before the entrypoint-validation gate runs, so a validation failure left the new payload sitting on top of the restored old config. Snapshot the file set the PREVIOUS install's gsd-file-manifest.json claims, before runInstallerMigrations so the bytes are the true pre-install state, and restore it from both Codex rollback closures ahead of the per-surface restores. Files only the failed install introduced are removed, read from the manifest now on disk. The manifest is already the authoritative record of what GSD owns, so no second hand-written list can drift out of sync, and user-owned files are never snapshotted or removed. Every path is confined through resolveInstallRelativePath, so a hand-edited manifest cannot turn rollback into an arbitrary-path write. Non-Codex runtimes are unaffected: the snapshot is gated on the same tomlConfigInstall + non-minimal condition as #3245's. * fix(#4249): keep the managed-file snapshot honest in minimal mode and on a bad manifest Two follow-on defects in the previous commit's snapshot: - The capture was gated on `!isMinimalMode`, copied from #3245. A core/ --minimal Codex install still writes gsd-core/, hooks/, scripts/ and the manifest, and restoreCodexSnapshot is reachable in that mode (#2695), so the snapshot came back empty while the rollback still ran — and its removal pass would have deleted every file the new manifest lists. Gate on tomlConfigInstall alone, matching where the rollback actually reaches. - An unreadable or unparseable prior manifest was caught alongside ENOENT and treated as a fresh install. That is the same empty-snapshot state, so a failed update over a real install with a corrupt manifest could delete its prior payload. Track whether the pre-install GSD-owned set is KNOWN: ENOENT means known-empty; any other read error or a parse failure means unknown, and the restore closure returns without touching anything, degrading to #3245's narrower rollback. Deliberately not fatal — a corrupt manifest has to stay repairable by reinstalling over it. Both paths are covered by red-checked regression tests. * fix(#4249): snapshot Codex skills, agents and VERSION in minimal mode too commit removed from the manifest snapshot. restoreCodexSnapshot is reachable for a core/--minimal install (#2695), and its pass-2 sweeps remove every gsd-* skill dir and gsd-* agent file the snapshot does not claim — so with an empty minimal-mode snapshot a rollback deleted the whole skills/agents surface with nothing to restore it from. Codex resolves skills to $HOME/.agents/skills via the ADR-1239 skills-kind home override, so this is also the reason manifest `skills/` keys do not resolve under configDir: that surface belongs to this snapshot, not to the manifest-driven one. Gate on tomlConfigInstall alone. _codexPreConfigRollback stays null in minimal mode — doing nothing on an early failure is the non-destructive side. Covered by a red-checked regression test that plants bytes in an alternate-home skill file, reinstalls under the core profile marker, and asserts the rollback restores it. * fix(#4249): never remove on rollback unless a prior manifest proves what predates the install Three defects in the manifest-driven Codex rollback, all in its removal half: - ENOENT marked the snapshot usable, arming the removal pass on a FIRST install. GSD may have overwritten a user's file at a manifest-tracked path there, and no prior manifest records the difference — so rollback deleted it where before it merely left it overwritten. Absent, unreadable and malformed manifests now all leave the prior set UNKNOWN and skip removal entirely. - Membership was tested against the map of files whose pre-install read SUCCEEDED, so a tracked file that existed but was unreadable read as introduced-by-this-install and was removed. Track the prior manifest's paths in their own Set and test against that. - The unreachable "delete the manifest when there was no prior one" branch is gone: usable now implies a parsed prior manifest. Also adds the end-to-end test the aggregate gate was missing — the four Codex rollback tests drove the closure directly, proving the restore but not the wiring. installAllRuntimes(['codex','cline']) under an emptied PATH makes Cline's `env node` entry fail validation for real, and asserts Codex's payload comes back. Test preamble (HOME/USERPROFILE sandbox + config-env scrub) is now one helper instead of six copies. Both new tests are red-checked. * test(#4249): use unlinkSync, not rmSync, to drop the manifest in a test lint:ci's raw-fs.rmSync rule points tests at helpers.cleanup for its Windows-EBUSY retry budget. That budget is for directory trees; this removes a single file, which unlinkSync says more precisely and the rule does not flag. * chore(#4249): point the changeset pr field back at the upstream PR * fix(#4249): use an unambiguous dedup key and surface partial-restore failures trek-e's 2026-09-08 adversarial pass flagged two findings in the new entrypoint-validation/rollback code: - assertConfiguredEntrypoints' dedup key already used a raw NUL separator (introduced in ceebb65f2d), but git/Read render NUL as a space, so the key looked like a plain-space join to every reviewer that read the diff. Replace it with JSON.stringify([configPath, scriptPath]) so the separator is visible and unambiguous. - restoreManagedFileSnapshot's per-file restore catch block claimed to 'surface the original error' but only swallowed it, matching (and widening) the pre-existing #3245 restoreCodexSnapshot pattern. Add an actual console.warn using the existing best-effort-warning convention, scoped to just this PR's new function. * fix(#4249): treat a files-less prior manifest as unknown, not known-empty agy's gemini-3.8-flash-high adversarial pass (round 5) found and I reproduced empirically: a structurally-valid manifest missing the files key (e.g. {"version":1}) parses without throwing, so Object.keys(undefined || {}) silently read as 'zero files predate this install' instead of the UNKNOWN state the malformed-manifest guard exists to produce. Rollback's removal pass then deleted every GSD-owned file the failed install's own manifest listed, including ones that predated it — the exact data loss the #4249 CodeRabbit malformed-manifest fix was supposed to prevent, reachable through a JSON.parse success instead of a failure. Route the shapeless case into the same catch-all UNKNOWN path via an explicit shape check. Regression test reproduces the deletion before the fix and confirms the file survives after it. Also extend restoreManagedFileSnapshot's removal-pass rmSync and final manifest-rewrite catches with the same real console.warn trek-e's round-4 review asked for on the per-file restore catch — same rollback function, same operator-facing-signal gap. * docs(#4249): correct which runtimes actually leave a written config on rollback agy's completeness audit (round 5, holistic pass) caught this new paragraph claiming 'for every other runtime, the configuration file(s) already written during that update are left in place' — false for Claude Code and other settings.json-based runtimes, whose write never happens on failure (assertConfiguredEntrypoints runs before finishInstall's writeSettings). Only Cursor/Windsurf/Kimi/Cline actually match that description, since they persist their config file inside install() ahead of the gate. Split the one sentence into the three actual outcomes; matches the PR body's own accurate Before/After wording, which this doc addition had drifted from. * fix(#4249): clean up doc/comment mismatches and dead fields from opus review Opus critical-code-reviewer + ponytail-review pass on the final diff: - assertConfiguredEntrypoints carried finishInstall's old docblock ("Apply statusline config, then print completion message") from before this function was inserted between comment and callee. finishInstall already has its own accurate #4249 comment, so the stale docblock is removed rather than moved. - checked: number on ConfiguredEntrypointValidationResult and error.configuredEntrypointValidation on the thrown error: the first had zero consumers anywhere in the repo, including its own defining file, and is removed. The second matches an existing repo convention (bin/install.js's installerMigrationRollbackFailures, #4249 predates this PR) of attaching structured diagnostic context to a re-thrown Error even before a consumer exists, so it's kept. - finishInstall's own assertConfiguredEntrypoints call is a redundant backstop on the real production path (installAllRuntimes's aggregate call already validates the superset first), but its comment read as though this call alone provided the before-the-write guarantee. Clarified rather than removed — it's the only gate for a caller that invokes finishInstall directly. * chore(#4249): split the manifest-driven rollback engine out into #4544 Issue #4154 asked the installer to consume a validation failure "through the existing rollback mechanism, without a second transaction mechanism". The manifest-driven rollback widening added during review (capture every path the prior gsd-file-manifest.json claims, restore those bytes, remove what only the failed install introduced) is that second mechanism on a plain reading. It is a real fix for a #3245-era gap, but an independent one, so it moves to its own bug report and PR. Removed here: - bin/install.js: the pre-install managed-file capture block and restoreManagedFileSnapshot, plus its call sites in _codexPreConfigRollback and restoreCodexSnapshot (99 lines). - tests/configured-entrypoint-validation.test.cjs: the five tests that exercise the manifest engine. - CONTEXT.md and docs/how-to/update-gsd.md: the sentences describing the widened restore. update-gsd.md again documents the #3245 surfaces only. Kept, because it is #4154's own scope: - the entrypoint-validation gate itself; - Codex's install() result binding rollbackInstallerMigrations to restoreCodexSnapshot (config.toml, hooks.json, skills/gsd-*, agents/gsd-*, gsd-core/VERSION); - the !isMinimalMode gate removal on that snapshot. Binding the closure to the result made it reachable for a core/--minimal install, where its pass-2 sweeps delete every gsd-* skill dir and agent file the snapshot does not claim; an empty minimal-mode snapshot therefore deleted the whole surface with nothing to restore. The surviving aggregate-failure test now asserts on config.toml, a surface the #3245 snapshot owns, instead of gsd-core/CHANGELOG.md, which only the manifest engine restored. Refs #4544 * test(#4249): cover configured entrypoints through the packed install path #4154's scope lists install smoke coverage alongside the installer gate — "assert representative configured entrypoints resolve for supported runtime profiles". The gate itself (assertConfiguredEntrypoints / validateConfiguredEntrypoints) is unit-covered by in-process install() calls; nothing proved the property survives npm pack -> npm install -g -> install.js. Add Cycle 4 to runSmoke. For each of claude and codex — the two distinct config surfaces GSD writes launch paths into (settings.json, and hooks.json + config.toml) — run the tarball-installed installer into a throwaway HOME, then re-read that runtime's own written config and return the new ENTRYPOINT_UNRESOLVED code when a script path it names does not resolve to a file. install-smoke.yml already asserts .code == "ok" on the CLI, so the check becomes a release gate on every matrix host without workflow changes. The scan re-derives paths from the written config instead of reusing the installer's own entrypoint list, and test I shows why that matters: a registration the installer never touched during a run is invisible to the in-process gate, so the install exits 0 and only reading the config back off disk catches the dangling launch path. * ci(#4249): pack a publish-shaped tarball in the install smoke lane `npm pack` runs prepack/prepare (build:lib); only prepublishOnly runs build:hooks. hooks/dist is gitignored, so the tarball install-smoke.yml packs after `npm ci` carries no hook scripts at all — the lane has been smoking a package that differs from the published one in exactly the artifacts the lifecycle smoke is supposed to launch. That went unnoticed because the lane's init runs `--local`, which registers no statusline and therefore registers no hook whose target is missing. A `--global` install on the same tarball exits 1 on #4249's own gate (`gsd-statusline.js (missing)`), which is what the new configured-entrypoint cycle performs, so without this step the cycle would report INIT_FAILED instead of checking anything. Build hooks before packing so the smoked tarball matches prepublishOnly. The CLI now reports 16 configured entrypoints for claude and 1 for codex instead of zero. * fix(#4249): scope Codex's full snapshot restore to entrypoint failures Binding Codex's result to `restoreCodexSnapshot` made ANY finalize-stage exception un-install a Codex install that had already succeeded and already printed its own "Done!" summary — `rollbackFinalizedInstallerMigrations` wraps the whole `finalize()` body, not just the aggregate `assertConfiguredEntrypoints` call. Nothing documents that. `docs/installer-migrations.md#phase-4-installupdate-integration` scopes finalize-stage rollback to installer *migrations* ("the executor uses the journal to restore modified paths"), and this PR's own operator-facing paragraph in `docs/how-to/update-gsd.md` scopes the Codex config.toml/hooks.json/skills/ agents/VERSION revert to entrypoint-validation failures specifically ("If a script is missing, unreadable, ... For Codex, this reverts ..."). The wide behaviour is also incoherent as a transaction abort: the same doc says Cursor, Windsurf, Kimi and Cline keep the config they wrote inside install(). Concretely: `installAllRuntimes(['codex', 'kilo'])` where Kilo's finishInstall hits EACCES writing kilo.json rolled Codex's config.toml back to its pre-install bytes — on an update, silently downgrading a working Codex install to the previous version while the user had just been told it was Done. Select the rollback by error kind instead. `assertConfiguredEntrypoints` already tags its error with `configuredEntrypointValidation`, so the full snapshot restore runs for that error (and anything downstream of it, including finishInstall's per-runtime backstop) and the installer-migrations-only closure runs for everything else. The codex result now also exposes that narrow closure as `rollbackInstallerMigrationsOnly`; `rollbackInstallerMigrations` keeps meaning the full restore, so the direct-call contract asserted by tests/codex-config.test.cjs is unchanged. Adds a regression test that installs codex+kilo together, injects EACCES on the Kilo permission write by monkeypatching node:fs (restored in a finally — never chmod 0o000, which root bypasses in CI), and asserts Codex's config.toml keeps the bytes the successful install wrote. Verified red against the pre-fix unconditional path. Cline cannot host this test: its plan is writesSharedSettings:false + finishPermissionWriter:null, so its finishInstall performs no write and has no non-entrypoint failure path. Kilo's configureKiloPermissions runs unconditionally (unlike OpenCode's, it is not GSD_TEST_MODE-gated) and ends in an unguarded fs.writeFileSync. * docs(#4249): sync CONTEXT.md's rollback description with the round-6 narrowing CONTEXT.md still described Codex's rollback as an unconditional bind to restoreCodexSnapshot after ff13adc00 scoped it to entrypoint- validation failures via rollbackInstallerMigrationsOnly and the configuredEntrypointValidation error tag. Caught during the round-6 PR body pass. * fix(#4249): stop rollbackInstallerMigrations meaning its own opposite Codex's install() result bound `rollbackInstallerMigrations` to restoreCodexSnapshot (the FULL pre-install snapshot restore) and put the actual installer-migrations-only closure behind `rollbackInstallerMigrationsOnly` — so for one runtime the unsuffixed name meant the opposite of what it says, and CONTEXT.md had to concede as much in prose. Invert it: `rollbackInstallerMigrations` is the narrow closure for every runtime, matching both its name and the meaning it already has on next, and the snapshot restore gets its own Codex-only field, `rollbackPreInstallSnapshot`. The selection in rollbackFinalizedInstallerMigrations collapses to one line and no longer needs a fallback chain. Also in this commit, all against the same rollback path: - Correct the rollbackFinalizedInstallerMigrations comment. It read as if the round-6 narrowing prevented any sibling-triggered revert of a Codex install the user has already seen "Done!" for. It does not, and is not meant to: `wide` is true for ANY entrypoint-validation error from ANY runtime, because the aggregate gate is all-or-nothing — an invalid Cline entrypoint reverts Codex's snapshot, which tests/configured-entrypoint-validation.test.cjs's 'an aggregate entrypoint validation failure rolls the Codex install back (#4249)' asserts directly. The discriminator is the error's KIND, not which runtime owns the failing path. Comment and CONTEXT.md now say that. - Name the runtime in the "Configured entrypoint validation failed" error. ConfiguredEntrypointInvalid already carries `runtime`; the message threw it away, leaving an operator of a multi-runtime install unable to tell whose entrypoint broke — which matters precisely because the failure can revert a runtime that was itself fine. - Set `configuredEntrypoints: []` explicitly on the copilot-instructions early return. Every other branch states the key; this one relied on installAllRuntimes' `(result.configuredEntrypoints || [])` defence. `[]` is correct, not a workaround: every Copilot hook is an inline printf one-liner (GSD_COPILOT_*_HOOK_BASH/PWSH), so there is no GSD-managed script or interpreter to resolve. No behaviour change beyond the error-message text. * docs(#4249): narrow the smoke scan's config-surface claim to what it checks RUNTIME_CONFIG_FILES claimed every GSD-managed executable a runtime is told to launch is registered in one of settings.json / hooks.json / config.toml, and that nothing else in a config dir is runtime configuration. Both halves are false as stated. Cline registers its hook at .clinerules/hooks/PreToolUse — a subdirectory, and not one of those names (writeClineArtifacts, src/runtime-hooks-surface.cts). Kimi's native [[hooks]] config.toml lives under resolveKimiHooksTomlDir() (~/.kimi), a directory separate from Kimi's own GSD configDir — the same gap installer-migration 007 already documents as structurally unreachable. The scan is in fact correct for what it runs against: entrypointRuntimes defaults to claude + codex, whose launch paths do all live in those three top-level files. Restate the docstring at that scope, name the two known out-of-scope surfaces, and warn that adding either runtime to entrypointRuntimes without teaching scanConfiguredEntrypoints about its surface yields a scan that finds zero entrypoints and proves nothing. The entrypointRuntimes default comment carried the same overgeneralization ("every other runtime reuses one of them") and is corrected with it. Documentation only; no code change. * fix(#4249): complete configuredEntrypoints/rollback shape on unparseable settings.local.json An internal adversarial review (agy/gemini-3.8-flash-medium, round 8) found that install()'s settings-json early return for an unparseable settings.local.json omitted configuredEntrypoints and rollbackInstallerMigrations from its result, unlike every other branch. rollbackFinalizedInstallerMigrations reads result.rollbackInstallerMigrations unconditionally, so this branch silently dropped its own installer-migration rollback on a later finalize-stage failure. Completed the return shape: configuredEntrypoints: [] (matching Copilot's equally-early no-entrypoints-yet return) and rollbackInstallerMigrations (already in closure scope). Red-then-green regression test added. * test(#4249): ensure hooks/dist before packing in release-tarball-smoke.install.test.cjs Same internal adversarial review (round 8): this suite's before() packed the tarball directly, without the ensureHooksDist() guard every sibling install-test suite (install.test.cjs, install-minimal-hooks.test.cjs, mcp-catalog-parity.install.test.cjs) already uses. On a clean tree, or run in isolation ahead of a suite that builds hooks/dist itself, this suite's pack would ship a tarball with no hook scripts and fail closed on SMOKE.INIT_FAILED instead of testing anything. * fix(#4249): refresh stale test-timings weight for the codex-config split next's own consolidation split (#4139/#4540) moved tests/codex-config.test.cjs's heavy install()-pipeline blocks into tests/codex-config-hooks.test.cjs, but the CI shard packer's weight table (tests/test-timings.json) was never updated: codex-config.test.cjs still carried its pre-split weight (127783ms, ~18x the suite mean), and codex-config-hooks.test.cjs — which now holds the #3245 block this PR extends with its own #4249 install()-pipeline test — had no entry at all, so the packer would silently underestimate it at the table's median weight (roughly a 9x underestimate against its real cost). trek-e's most recent review flagged a Windows shard timeout in-flight on codex-config.test.cjs, plausibly aggravated by this PR's own addition to that file before the rebase moved it. Re-measured both files locally (node --test --test-reporter=tap, max of 3 runs, matching the table's own max-across-streams methodology) and patched just these two entries — not a full regeneration, which would need real multi-lane CI data this session doesn't have access to. * fix(#4249): register configured-entrypoint-validation tests in the conformance-tier lists next's platform-conformance-tier classifier (#4591/#4598) landed after this branch's last rebase, so tests/configured-entrypoint-validation.test.cjs and tests/codex-config-hooks.test.cjs were never classified, failing lint:ci's gen-platform-conformance-tier --check and both the Linux and macOS conformance suites. * fix(#4249): drop codex-config.test.cjs from the #4733 pinned isolated-set expectation next's #4733 (landed after this branch's last rebase) replaced the static ISOLATED_HEAVY_FILES set with a threshold derived live from tests/test-timings.json, and pins the current derived result in EXPECTED_ISOLATED_UNIT_FILES for regression coverage. That pinned list still named codex-config.test.cjs, whose own weight this PR already dropped from 127783ms to 189ms (after splitting its heavy install()-pipeline blocks into codex-config-hooks.test.cjs) — well under #4733's derived 120000ms bar. The live-computed set correctly no longer includes it; the pinned expectation is updated to match. * fix(#4249): name the rollback consequence in the entrypoint-validation error, and prove Cline's file survives it trek-e's review flagged two Major gaps: the thrown error read identically regardless of which of three real outcomes a runtime hit (nothing persisted / snapshot reverted / config left broken on disk), and no test proved the disclosed "left on disk, unreverted" case for Cursor/Windsurf/ Kimi/Cline — only Codex's revert path was ever asserted. assertConfiguredEntrypoints now tags each invalid entry with its actual consequence, mirrored from docs/how-to/update-gsd.md's existing rollback-matrix disclosure. A new test drives the same aggregate failure through Cline (whose own entrypoint is the one that fails) and asserts its hook file is still on disk afterward. * fix(#4249): close 4 gaps antigravity's adversarial review found in the entrypoint-validation PR One review pass (gemini-3.8-flash-high via the antigravity review lane) against this PR's full diff against next, findings independently verified against source before fixing: - Copilot's install() return object was the only one of 6 runtime branches missing rollbackInstallerMigrations — reachable now that this PR's own aggregate gate runs rollback across every result on any runtime's entrypoint failure, not just Copilot's own. - buildHookCommand's unresolved-bash early return skipped track() entirely, so a win32 install with no Git Bash silently produced an unregistered .sh hook instead of the 'unresolved-interpreter' validation failure configuredEntrypointsForHook's own comment said it would. - release-tarball-smoke.cjs reported a Cycle 4 install failure under SMOKE.INIT_FAILED (Cycle 1's code) instead of the already-existing SMOKE.INSTALL_FAILED. - SCRIPT_PATH_RE excluded whitespace to avoid swallowing a shell command's trailing args, which also truncated any configDir containing a space (e.g. a real "/Users/John Doe/.claude"), silently zeroing the scan. Anchored the match on the already-known configDir prefix instead of a generic absolute-path guess: removes the ambiguity outright rather than patching the character class, and stays a raw-text scan on purpose (it catches a writer that emits a path without registering it — a JSON.parse of the expected schema would miss exactly that case). One suggested finding (test-timings.json "missing" the new test file) was verified false — that table only holds measured CI timings, populated after a file's first real run — and one Ponytail suggestion (a JSON.stringify dedup key) was rejected as it would reintroduce a real, if narrow, key-collision risk for no benefit. * fix(#4249): fix fork CI red from a stale changeset pr field and an unquoted docs/ comment changeset-lint requires pr: to match the PR it runs on (16 on the fork, not the eventual upstream number) — rehearsal-branch convention already established earlier in this PR's history. lint-docs-guard-registration's quote-pairing heuristic doesn't require the docs/ path itself to be quoted — it flags a file once ANY quote-delimited span containing "docs/" appears anywhere in it, alongside any real fs read call. A comment ending "...update-gsd.md's rollback-matrix paragraph" supplied the closing quote character (the possessive apostrophe) the heuristic paired with an unrelated single-quoted string earlier in the file. Reworded to avoid the unquoted apostrophe next to the path. * chore(#4249): point the changeset pr field back at the upstream PR Fork rehearsal (PR #16) is green; the real target for this changeset is upstream PR #4249. --------- Co-authored-by: Test <test@test.com> Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
904 lines
43 KiB
JavaScript
904 lines
43 KiB
JavaScript
// allow-test-rule: integration-test-input
|
||
// The script under test (scripts/release-tarball-smoke.cjs) is the system
|
||
// under test. We exercise it via its exported pure function, not by reading
|
||
// source text. The tarball fixture is produced by npm pack in before().
|
||
|
||
'use strict';
|
||
|
||
process.env.GSD_TEST_MODE = '1';
|
||
|
||
const { describe, test, before, after } = require('node:test');
|
||
const assert = require('node:assert/strict');
|
||
const fs = require('node:fs');
|
||
const os = require('node:os');
|
||
const path = require('node:path');
|
||
const crypto = require('node:crypto');
|
||
const { spawnSync } = require('node:child_process');
|
||
|
||
const { cleanup, createTempDir, runNpm, isolatedNpmEnv } = require('./helpers.cjs');
|
||
const { ensureHooksDist } = require('./helpers/hooks-dist.cjs');
|
||
const { SMOKE, runSmoke, entrypointFixtureHome, CHILD_TIMEOUT_MS, configuredEntrypointsIn } = require('../scripts/release-tarball-smoke.cjs');
|
||
|
||
const smokeMsg = (label, result) =>
|
||
`${label}: code=${result.code} details=${JSON.stringify(result.details)}`;
|
||
|
||
const PKG_PATH = path.join(__dirname, '..', 'package.json');
|
||
const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf-8'));
|
||
|
||
function installedPackageRoot(prefix) {
|
||
const parts = pkg.name.split('/');
|
||
const posix = path.join(prefix, 'lib', 'node_modules', ...parts);
|
||
const windows = path.join(prefix, 'node_modules', ...parts);
|
||
return fs.existsSync(posix) ? posix : windows;
|
||
}
|
||
|
||
function hashTree(root) {
|
||
const result = new Map();
|
||
const visit = (dir) => {
|
||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
const absolute = path.join(dir, entry.name);
|
||
if (entry.isDirectory()) visit(absolute);
|
||
else if (entry.isFile()) {
|
||
result.set(
|
||
path.relative(root, absolute).replace(/\\/g, '/'),
|
||
crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex'),
|
||
);
|
||
}
|
||
}
|
||
};
|
||
visit(root);
|
||
return result;
|
||
}
|
||
|
||
// ─── runSmoke install timeout must clear a slow-host cold install (#2335) ────
|
||
// Regression: runSmoke()'s internal `npm install -g` used CHILD_TIMEOUT_MS,
|
||
// which was 120 s on non-Windows while before()'s pack+install used 600 s. A
|
||
// cold-cache install of the 1499-file tarball takes 3–6 min on a slow bench, so
|
||
// the per-test installs (B/C/D/E) fired SIGTERM at 120 s and returned a spurious
|
||
// INSTALL_FAILED (`spawnSync npm ETIMEDOUT`, empty stdout/stderr) on cartographer
|
||
// while passing on faster holodeck — a host-dependent false failure, not a flake.
|
||
// The ceiling is now a single exported constant shared by both surfaces; this
|
||
// pins it at/above the documented 600 s slow-host floor on EVERY platform, so a
|
||
// reintroduced 120 s (or a Windows-only 600 s) fails here instead of on a bench.
|
||
describe('release-tarball-smoke: install timeout ceiling', () => {
|
||
test('CHILD_TIMEOUT_MS clears the 600 s slow-host cold-install floor', () => {
|
||
assert.ok(
|
||
Number.isInteger(CHILD_TIMEOUT_MS) && CHILD_TIMEOUT_MS >= 600_000,
|
||
`CHILD_TIMEOUT_MS must be >= 600000ms for cartographer-class hosts; got ${CHILD_TIMEOUT_MS}`,
|
||
);
|
||
});
|
||
|
||
test('the ceiling is platform-uniform — no host slower than the CI matrix is left under-provisioned', () => {
|
||
// The slow-host reality (cold disk, constrained CPU) is not OS-specific, so
|
||
// the constant must not be gated behind `process.platform`. A single numeric
|
||
// constant satisfies this by construction; this guards against a future
|
||
// reintroduction of a per-platform ternary that under-provisions Linux/macOS.
|
||
assert.equal(typeof CHILD_TIMEOUT_MS, 'number');
|
||
assert.ok(CHILD_TIMEOUT_MS >= 600_000);
|
||
});
|
||
});
|
||
|
||
describe('release-tarball-smoke', () => {
|
||
// Shared fixture state: pack the tarball once, install it once, reuse for all tests.
|
||
let packDir;
|
||
let installPrefix;
|
||
let tarballPath;
|
||
// fixtureDir for lifecycle / init tests; created once in before(), cleaned in after().
|
||
let fixtureDir;
|
||
|
||
before(async () => {
|
||
// hooks/dist is gitignored and only produced by `npm run build:hooks`; the
|
||
// pack below must ship it or Cycle 4's entrypoint scan runs against a
|
||
// tarball with no hook scripts at all (SMOKE.INIT_FAILED on a clean tree).
|
||
ensureHooksDist();
|
||
|
||
// Pack once into a temp dir.
|
||
packDir = createTempDir('gsd-smoke-pack-');
|
||
installPrefix = createTempDir('gsd-smoke-prefix-');
|
||
fixtureDir = createTempDir('gsd-smoke-fixture-');
|
||
|
||
// npm pack + npm install -g on a large tarball (1499 files, ~10 MB) can take
|
||
// 3–6 minutes on slow Docker hosts (cold disk, constrained CPU). The runNpm
|
||
// default timeout of 180 s is sufficient on fast machines but insufficient on
|
||
// cartographer-class hosts. Share the smoke script's CHILD_TIMEOUT_MS ceiling
|
||
// so before() (pack+install) and runSmoke()'s per-test installs cannot diverge
|
||
// — divergence was the #2335-run defect: before() had 600 s, runSmoke had 120 s
|
||
// on Linux, so the per-test installs alone timed out on cartographer.
|
||
const SLOW_HOST_TIMEOUT = CHILD_TIMEOUT_MS;
|
||
|
||
const packOutput = runNpm(
|
||
['pack', '--pack-destination', packDir],
|
||
{ cwd: path.join(__dirname, '..'), timeout: SLOW_HOST_TIMEOUT },
|
||
);
|
||
|
||
// npm pack prints the filename as the last line of stdout.
|
||
const lines = packOutput.split(/\r?\n/).filter(Boolean);
|
||
const tgzName = lines[lines.length - 1];
|
||
tarballPath = path.join(packDir, tgzName);
|
||
if (!fs.existsSync(tarballPath)) {
|
||
const found = fs.readdirSync(packDir).find((f) => f.endsWith('.tgz'));
|
||
if (!found) throw new Error(`npm pack produced no .tgz in ${packDir}; output: ${packOutput}`);
|
||
tarballPath = path.join(packDir, found);
|
||
}
|
||
|
||
// Install once into installPrefix. All tests share this install.
|
||
runNpm(['install', '-g', '--prefix', installPrefix, tarballPath], { timeout: SLOW_HOST_TIMEOUT });
|
||
});
|
||
|
||
after(() => {
|
||
cleanup(packDir);
|
||
cleanup(installPrefix);
|
||
cleanup(fixtureDir);
|
||
});
|
||
|
||
// ── Test A — happy path ────────────────────────────────────────────────────
|
||
test('A: happy path — installed version matches package.json', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.OK, smokeMsg('A', result));
|
||
assert.equal(result.details.version, pkg.version, smokeMsg('A', result));
|
||
});
|
||
|
||
// ── Test B — version mismatch detected ────────────────────────────────────
|
||
test('B: version mismatch detected — returns VERSION_MISMATCH', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: '99.99.99',
|
||
fixtureDir,
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.VERSION_MISMATCH, smokeMsg('B', result));
|
||
});
|
||
|
||
// ── Test C — happy lifecycle ───────────────────────────────────────────────
|
||
// Verifies that the installed package has all expected command .md files and
|
||
// that each command resolves a workflow .md file that also exists.
|
||
// Also verifies that `gsd-core --local --claude` (init) succeeds in
|
||
// the fixtureDir and creates the expected .claude/ directories.
|
||
test('C: happy lifecycle — command + workflow files resolve OK', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
lifecycleCommands: ['init', 'discuss-phase', 'plan-phase'],
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.OK, smokeMsg('C', result));
|
||
|
||
// Each non-init command must be in lifecycleResolved with both paths populated
|
||
const resolved = result.details.lifecycleResolved;
|
||
assert.ok(Array.isArray(resolved));
|
||
|
||
for (const entry of resolved) {
|
||
assert.ok(
|
||
typeof entry.commandPath === 'string' && entry.commandPath.length > 0,
|
||
`expected commandPath for ${entry.command}`,
|
||
);
|
||
assert.ok(
|
||
fs.existsSync(entry.commandPath) && fs.statSync(entry.commandPath).isFile(),
|
||
`commandPath must be an existing file: ${entry.commandPath}`,
|
||
);
|
||
assert.ok(
|
||
typeof entry.workflowPath === 'string' && entry.workflowPath.length > 0,
|
||
`expected workflowPath for ${entry.command}`,
|
||
);
|
||
assert.ok(
|
||
fs.existsSync(entry.workflowPath) && fs.statSync(entry.workflowPath).isFile(),
|
||
`workflowPath must be an existing file: ${entry.workflowPath}`,
|
||
);
|
||
}
|
||
});
|
||
|
||
// ── Test D — missing command detected ─────────────────────────────────────
|
||
// Passes a nonexistent command name; expects the smoke to detect the missing
|
||
// command .md file and return COMMAND_FILE_MISSING with the right details.
|
||
test('D: missing command detected — returns COMMAND_FILE_MISSING', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
lifecycleCommands: ['init', 'nonexistent-phase-xyz'],
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.COMMAND_FILE_MISSING, smokeMsg('D', result));
|
||
assert.equal(result.details.command, 'nonexistent-phase-xyz', smokeMsg('D', result));
|
||
assert.ok(typeof result.details.path === 'string' && result.details.path.length > 0, smokeMsg('D', result));
|
||
});
|
||
|
||
// ── Test E — workflow-body checks run (informational) ─────────────────────
|
||
// Asserts that the workflow-body scanning machinery ran (structural assertion).
|
||
// Does NOT assert colonLeakCount is zero — when those issues are fixed, this
|
||
// test continues to pass unchanged.
|
||
test('E: workflow-body checks run — scan counts are present integers', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
lifecycleCommands: [],
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
// Structural: the scan ran and populated the counters
|
||
assert.ok(
|
||
Number.isInteger(result.details.workflowsScanned) && result.details.workflowsScanned >= 1,
|
||
smokeMsg('E', result),
|
||
);
|
||
assert.ok(
|
||
Number.isInteger(result.details.colonLeakCount),
|
||
smokeMsg('E', result),
|
||
);
|
||
});
|
||
|
||
test('F: packed package carries the complete canonical Runtime Surface corpus', () => {
|
||
const packageRoot = installedPackageRoot(installPrefix);
|
||
assert.deepStrictEqual(
|
||
hashTree(path.join(packageRoot, 'commands', 'gsd')),
|
||
hashTree(path.join(__dirname, '..', 'commands', 'gsd')),
|
||
);
|
||
assert.deepStrictEqual(
|
||
hashTree(path.join(packageRoot, 'agents')),
|
||
hashTree(path.join(__dirname, '..', 'agents')),
|
||
);
|
||
});
|
||
|
||
test('G: deployed Codex and Claude modules materially change a surface after package source is unreachable', (t) => {
|
||
const runtimeRoot = createTempDir('gsd-smoke-offline-runtime-');
|
||
const packageRoot = installedPackageRoot(installPrefix);
|
||
const hiddenPackageRoot = `${packageRoot}.offline-${process.pid}`;
|
||
t.after(() => {
|
||
if (fs.existsSync(hiddenPackageRoot) && !fs.existsSync(packageRoot)) fs.renameSync(hiddenPackageRoot, packageRoot);
|
||
cleanup(runtimeRoot);
|
||
});
|
||
const installs = [];
|
||
for (const runtime of ['codex', 'claude']) {
|
||
const configDir = path.join(runtimeRoot, `.${runtime}`);
|
||
const result = spawnSync(process.execPath, [
|
||
path.join(packageRoot, 'bin', 'install.js'),
|
||
`--${runtime}`,
|
||
'--global',
|
||
'--config-dir',
|
||
configDir,
|
||
], {
|
||
cwd: runtimeRoot,
|
||
env: {
|
||
...process.env,
|
||
...isolatedNpmEnv(),
|
||
HOME: runtimeRoot,
|
||
USERPROFILE: runtimeRoot,
|
||
GSD_TEST_MODE: '',
|
||
NO_UPDATE_NOTIFIER: '1',
|
||
npm_config_update_notifier: 'false',
|
||
},
|
||
encoding: 'utf8',
|
||
timeout: CHILD_TIMEOUT_MS,
|
||
});
|
||
assert.equal(result.status, 0, `${runtime} packed install failed:\n${result.stdout}\n${result.stderr}`);
|
||
installs.push({ runtime, configDir });
|
||
}
|
||
|
||
// Synthetic untouched 1.12-style deployed tree: converted outputs and a
|
||
// hash manifest exist, but the raw corpus/marker do not. It must not use
|
||
// those outputs as source when the executing package disappears.
|
||
const legacyConfigDir = path.join(runtimeRoot, '.legacy-codex');
|
||
fs.cpSync(installs.find((entry) => entry.runtime === 'codex').configDir, legacyConfigDir, { recursive: true });
|
||
cleanup(path.join(legacyConfigDir, 'gsd-core', 'commands'));
|
||
cleanup(path.join(legacyConfigDir, 'gsd-core', 'agents'));
|
||
const legacyMarker = path.join(legacyConfigDir, '.gsd-source');
|
||
if (fs.existsSync(legacyMarker)) fs.unlinkSync(legacyMarker);
|
||
|
||
// S04: upgrade a synthetic source-less legacy tree while the fixed
|
||
// package is available. Preserve its exact committed selection and an
|
||
// unrelated file, converge artifacts to that selection, and later prove
|
||
// an offline expansion works from the provisioned corpus alone.
|
||
const upgradedHome = path.join(runtimeRoot, 'legacy-codex-upgrade-home');
|
||
const upgradeCwd = path.join(runtimeRoot, 'legacy-codex-upgrade-worktree');
|
||
const upgradedConfigDir = path.join(upgradedHome, '.codex');
|
||
fs.mkdirSync(upgradeCwd, { recursive: true });
|
||
fs.cpSync(installs.find((entry) => entry.runtime === 'codex').configDir, upgradedConfigDir, { recursive: true });
|
||
fs.cpSync(path.join(runtimeRoot, '.agents', 'skills'), path.join(upgradedHome, '.agents', 'skills'), { recursive: true });
|
||
fs.mkdirSync(path.join(upgradedHome, '.agents', 'skills', 'user-owned-skill'), { recursive: true });
|
||
fs.writeFileSync(path.join(upgradedHome, '.agents', 'skills', 'user-owned-skill', 'SKILL.md'), '# preserve me\n');
|
||
cleanup(path.join(upgradedConfigDir, 'gsd-core', 'commands'));
|
||
cleanup(path.join(upgradedConfigDir, 'gsd-core', 'agents'));
|
||
const upgradedMarker = path.join(upgradedConfigDir, '.gsd-source');
|
||
if (fs.existsSync(upgradedMarker)) fs.unlinkSync(upgradedMarker);
|
||
const selectedState = JSON.stringify({ baseProfile: 'core', disabledClusters: [], explicitAdds: [], explicitRemoves: [] }, null, 2) + '\n';
|
||
const priorGates = JSON.stringify({ workflow: { code_review: false, research: true } }, null, 2) + '\n';
|
||
fs.writeFileSync(path.join(upgradedConfigDir, '.gsd-surface.json'), selectedState);
|
||
fs.writeFileSync(path.join(upgradedConfigDir, 'user-owned.txt'), 'preserve me\n');
|
||
fs.mkdirSync(path.join(upgradeCwd, '.planning'), { recursive: true });
|
||
fs.writeFileSync(path.join(upgradeCwd, '.planning', 'config.json'), priorGates);
|
||
const upgradeResult = spawnSync(process.execPath, [
|
||
path.join(packageRoot, 'bin', 'install.js'),
|
||
'--codex',
|
||
'--global',
|
||
'--config-dir',
|
||
upgradedConfigDir,
|
||
], {
|
||
cwd: upgradeCwd,
|
||
env: {
|
||
...process.env,
|
||
...isolatedNpmEnv(),
|
||
HOME: upgradedHome,
|
||
USERPROFILE: upgradedHome,
|
||
GSD_TEST_MODE: '',
|
||
NO_UPDATE_NOTIFIER: '1',
|
||
npm_config_update_notifier: 'false',
|
||
},
|
||
encoding: 'utf8',
|
||
timeout: CHILD_TIMEOUT_MS,
|
||
});
|
||
assert.equal(upgradeResult.status, 0, `legacy upgrade failed:\n${upgradeResult.stdout}\n${upgradeResult.stderr}`);
|
||
assert.equal(fs.readFileSync(path.join(upgradedConfigDir, '.gsd-surface.json'), 'utf8'), selectedState);
|
||
assert.equal(fs.readFileSync(path.join(upgradedConfigDir, 'user-owned.txt'), 'utf8'), 'preserve me\n');
|
||
assert.equal(fs.readFileSync(path.join(upgradeCwd, '.planning', 'config.json'), 'utf8'), priorGates);
|
||
assert.deepStrictEqual(
|
||
hashTree(path.join(upgradedConfigDir, 'gsd-core', 'commands', 'gsd')),
|
||
hashTree(path.join(packageRoot, 'commands', 'gsd')),
|
||
);
|
||
assert.deepStrictEqual(
|
||
hashTree(path.join(upgradedConfigDir, 'gsd-core', 'agents')),
|
||
hashTree(path.join(packageRoot, 'agents')),
|
||
);
|
||
const upgradedSkillRoot = path.join(upgradedHome, '.agents', 'skills');
|
||
const upgradedSkillCount = fs.readdirSync(upgradedSkillRoot).filter((name) => name.startsWith('gsd-')).length;
|
||
assert.ok(upgradedSkillCount > 0 && upgradedSkillCount < 71, `upgrade must converge the selected core surface, got ${upgradedSkillCount}`);
|
||
assert.equal(fs.readFileSync(path.join(upgradedSkillRoot, 'user-owned-skill', 'SKILL.md'), 'utf8'), '# preserve me\n');
|
||
|
||
fs.renameSync(packageRoot, hiddenPackageRoot);
|
||
|
||
const upgradedOfflineScript = [
|
||
"const fs=require('node:fs'),path=require('node:path');",
|
||
`const configDir=${JSON.stringify(upgradedConfigDir)};`,
|
||
"const lib=path.join(configDir,'gsd-core','bin','lib');",
|
||
"const surface=require(path.join(lib,'surface.cjs'));",
|
||
"const layoutModule=require(path.join(lib,'runtime-artifact-layout.cjs'));",
|
||
"const profiles=require(path.join(lib,'install-profiles.cjs'));",
|
||
"const clusters=require(path.join(lib,'clusters.cjs'));",
|
||
"const manifest=profiles.loadSkillsManifest(path.join(configDir,'gsd-core','commands','gsd'));",
|
||
"const layout=layoutModule.resolveRuntimeArtifactLayout('codex',configDir,'global');",
|
||
"const skillKind=layout.kinds.find(kind=>kind.kind==='skills');",
|
||
"const skillRoot=path.join(skillKind.home||configDir,skillKind.destSubpath);",
|
||
"const before=fs.readdirSync(skillRoot).filter(n=>n.startsWith('gsd-')).length;",
|
||
"surface.applySurface(configDir,layout,manifest,clusters.CLUSTERS,undefined,{surfaceState:{baseProfile:'full',disabledClusters:[],explicitAdds:[],explicitRemoves:[]}});",
|
||
"const after=fs.readdirSync(skillRoot).filter(n=>n.startsWith('gsd-')).length;",
|
||
"if(!(after>before))throw new Error(`offline upgraded expansion failed: ${before} -> ${after}`);",
|
||
].join('');
|
||
const upgradedOfflineResult = spawnSync(process.execPath, ['-e', upgradedOfflineScript], {
|
||
cwd: runtimeRoot,
|
||
env: { ...process.env, HOME: upgradedHome, USERPROFILE: upgradedHome, GSD_TEST_MODE: '' },
|
||
encoding: 'utf8',
|
||
timeout: CHILD_TIMEOUT_MS,
|
||
});
|
||
assert.equal(upgradedOfflineResult.status, 0, `upgraded offline surface failed:\n${upgradedOfflineResult.stdout}\n${upgradedOfflineResult.stderr}`);
|
||
|
||
const legacyChildScript = [
|
||
"const fs=require('node:fs'),path=require('node:path');",
|
||
`const configDir=${JSON.stringify(legacyConfigDir)};`,
|
||
"const lib=path.join(configDir,'gsd-core','bin','lib');",
|
||
"const surface=require(path.join(lib,'surface.cjs'));",
|
||
"const layoutModule=require(path.join(lib,'runtime-artifact-layout.cjs'));",
|
||
"const profiles=require(path.join(lib,'install-profiles.cjs'));",
|
||
"const clusters=require(path.join(lib,'clusters.cjs'));",
|
||
"const surfacePath=path.join(configDir,'.gsd-surface.json');",
|
||
"const agentPath=path.join(configDir,'agents','gsd-planner.md');",
|
||
"const beforeSurface=fs.existsSync(surfacePath)?fs.readFileSync(surfacePath):null;",
|
||
"const beforeAgent=fs.readFileSync(agentPath);",
|
||
"const layout=layoutModule.resolveRuntimeArtifactLayout('codex',configDir,'global');",
|
||
"let error=null;try{surface.applySurface(configDir,layout,new Map(),clusters.CLUSTERS,undefined,{surfaceState:{baseProfile:'core',disabledClusters:[],explicitAdds:[],explicitRemoves:[]}})}catch(value){error=value}",
|
||
"if(!error||!/install or upgrade gsd-core/.test(error.message))throw new Error(`expected actionable source failure, got ${error&&error.message}`);",
|
||
"const afterSurface=fs.existsSync(surfacePath)?fs.readFileSync(surfacePath):null;",
|
||
"if(!Buffer.isBuffer(beforeAgent)||!beforeAgent.equals(fs.readFileSync(agentPath)))throw new Error('legacy output changed');",
|
||
"if(beforeSurface===null?afterSurface!==null:!beforeSurface.equals(afterSurface))throw new Error('legacy surface state changed');",
|
||
].join('');
|
||
const legacyResult = spawnSync(process.execPath, ['-e', legacyChildScript], {
|
||
cwd: runtimeRoot,
|
||
env: { ...process.env, HOME: runtimeRoot, USERPROFILE: runtimeRoot, GSD_TEST_MODE: '' },
|
||
encoding: 'utf8',
|
||
timeout: CHILD_TIMEOUT_MS,
|
||
});
|
||
assert.equal(legacyResult.status, 0, `legacy source-less refusal failed:\n${legacyResult.stdout}\n${legacyResult.stderr}`);
|
||
|
||
for (const { runtime, configDir } of installs) {
|
||
const childScript = [
|
||
"const path=require('node:path');",
|
||
`const configDir=${JSON.stringify(configDir)};`,
|
||
`const runtime=${JSON.stringify(runtime)};`,
|
||
"const lib=path.join(configDir,'gsd-core','bin','lib');",
|
||
"const surface=require(path.join(lib,'surface.cjs'));",
|
||
"const layoutModule=require(path.join(lib,'runtime-artifact-layout.cjs'));",
|
||
"const profiles=require(path.join(lib,'install-profiles.cjs'));",
|
||
"const clusters=require(path.join(lib,'clusters.cjs'));",
|
||
"const corpus=path.join(configDir,'gsd-core','commands','gsd');",
|
||
"const manifest=profiles.loadSkillsManifest(corpus);",
|
||
"const layout=layoutModule.resolveRuntimeArtifactLayout(runtime,configDir,'global');",
|
||
"const before=layout.kinds.map(k=>{const root=path.join(k.home||configDir,k.destSubpath);try{return require('node:fs').readdirSync(root).length}catch{return 0}}).reduce((a,b)=>a+b,0);",
|
||
"const state={baseProfile:'core',disabledClusters:[],explicitAdds:[],explicitRemoves:[]};",
|
||
"surface.applySurface(configDir,layout,manifest,clusters.CLUSTERS,undefined,{surfaceState:state});",
|
||
"const after=layout.kinds.map(k=>{const root=path.join(k.home||configDir,k.destSubpath);try{return require('node:fs').readdirSync(root).length}catch{return 0}}).reduce((a,b)=>a+b,0);",
|
||
"if(!(after>0&&after<before))throw new Error(`surface did not materially shrink: ${before} -> ${after}`);",
|
||
"process.stdout.write(JSON.stringify({before,after}));",
|
||
].join('');
|
||
const result = spawnSync(process.execPath, ['-e', childScript], {
|
||
cwd: runtimeRoot,
|
||
env: { ...process.env, HOME: runtimeRoot, USERPROFILE: runtimeRoot, GSD_TEST_MODE: '' },
|
||
encoding: 'utf8',
|
||
timeout: CHILD_TIMEOUT_MS,
|
||
});
|
||
assert.equal(result.status, 0, `${runtime} offline materialization failed:\n${result.stdout}\n${result.stderr}`);
|
||
const counts = JSON.parse(result.stdout);
|
||
assert.ok(counts.after > 0 && counts.after < counts.before);
|
||
}
|
||
});
|
||
|
||
// ── H: configured entrypoints resolve for supported runtime profiles ──────
|
||
//
|
||
// #4154's scope bullet: the installer's in-process assertConfiguredEntrypoints
|
||
// gate is unit-covered in tests/configured-entrypoint-validation.test.cjs.
|
||
// This asserts the same property survives the packaged path — install the
|
||
// real tarball, run its installer for a runtime, and re-read that runtime's
|
||
// own config back off disk.
|
||
test('H: packed install leaves every configured entrypoint resolvable', () => {
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
// The lifecycle-command and workflow-body cycles are covered by A/C/E;
|
||
// skipping them here keeps this test to the entrypoint cycle.
|
||
lifecycleCommands: [],
|
||
entrypointRuntimes: ['claude', 'codex'],
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.OK, smokeMsg('H', result));
|
||
assert.deepEqual(
|
||
result.details.entrypointProfiles.map((profile) => profile.runtime),
|
||
['claude', 'codex'],
|
||
smokeMsg('H', result),
|
||
);
|
||
for (const profile of result.details.entrypointProfiles) {
|
||
// Structural: a profile whose scan found nothing would satisfy the
|
||
// "no unresolved entrypoints" verdict vacuously.
|
||
assert.ok(
|
||
profile.entrypointsChecked > 0,
|
||
`${profile.runtime} configured no entrypoints: ${smokeMsg('H', result)}`,
|
||
);
|
||
}
|
||
});
|
||
|
||
// ── I: an unresolvable configured entrypoint fails the packed install ─────
|
||
//
|
||
// Red proof for ENTRYPOINT_UNRESOLVED, end to end through the packed tarball,
|
||
// and the reason this smoke check is not redundant with the installer's own
|
||
// gate: the fixture pre-registers a hook no install will ever write, the
|
||
// packed installer merges its own entries around it and exits 0 — its
|
||
// in-process assertConfiguredEntrypoints only validates paths the config
|
||
// writers registered with it during that run, so a registration it never
|
||
// touched is invisible to it — and reading settings.json back off disk is
|
||
// what catches the dangling launch path.
|
||
test('I: a registered hook that no install writes fails the smoke', (t) => {
|
||
const runtimeHome = entrypointFixtureHome(fixtureDir, 'claude');
|
||
// fixtureDir is shared with A/C/E/H, which install into this same home.
|
||
t.after(() => cleanup(runtimeHome));
|
||
|
||
const configDir = path.join(runtimeHome, '.claude');
|
||
const ghostHook = path.join(configDir, 'hooks', 'gsd-ghost-hook.js');
|
||
fs.mkdirSync(configDir, { recursive: true });
|
||
fs.writeFileSync(path.join(configDir, 'settings.json'), JSON.stringify({
|
||
hooks: {
|
||
PreToolUse: [
|
||
{ matcher: 'Bash', hooks: [{ type: 'command', command: `node "${ghostHook}"` }] },
|
||
],
|
||
},
|
||
}, null, 2));
|
||
|
||
const result = runSmoke({
|
||
tarballPath,
|
||
installPrefix,
|
||
expectedVersion: pkg.version,
|
||
fixtureDir,
|
||
lifecycleCommands: [],
|
||
entrypointRuntimes: ['claude'],
|
||
npmEnv: isolatedNpmEnv(),
|
||
});
|
||
|
||
assert.equal(result.code, SMOKE.ENTRYPOINT_UNRESOLVED, smokeMsg('I', result));
|
||
assert.equal(result.details.runtime, 'claude', smokeMsg('I', result));
|
||
assert.deepEqual(
|
||
result.details.unresolved,
|
||
[{ configPath: path.join(configDir, 'settings.json'), scriptPath: ghostHook }],
|
||
smokeMsg('I', result),
|
||
);
|
||
});
|
||
|
||
// ── J: configuredEntrypointsIn tolerates whitespace in configDir ──────────
|
||
//
|
||
// #4249 (antigravity review): the prior SCRIPT_PATH_RE excluded `\s` from
|
||
// the path match to avoid swallowing a shell command's trailing args, which
|
||
// also truncated any legitimate path containing a space — e.g. a real
|
||
// `/Users/John Doe/.claude` home — so the scan silently returned zero
|
||
// checked paths there. A direct unit test on the exported pure function:
|
||
// no packed install needed to prove this property.
|
||
test('J: configuredEntrypointsIn resolves a script path even when configDir contains a space', () => {
|
||
const configDir = path.join(os.tmpdir(), 'John Doe', '.claude');
|
||
const scriptPath = path.join(configDir, 'hooks', 'gsd-write-guard.js');
|
||
const text = JSON.stringify({
|
||
hooks: {
|
||
PreToolUse: [
|
||
{ matcher: 'Bash', hooks: [{ type: 'command', command: `node "${scriptPath}"` }] },
|
||
],
|
||
},
|
||
});
|
||
|
||
assert.deepEqual(configuredEntrypointsIn(text, configDir), [path.resolve(scriptPath)]);
|
||
});
|
||
|
||
// ── K: configuredEntrypointsIn does not swallow a preceding interpreter path ──
|
||
//
|
||
// #4249 (antigravity review): anchoring on the literal configDir prefix (a
|
||
// fix for J) must not regress the original "don't swallow the rest of a
|
||
// shell command" property — a command string that concatenates an
|
||
// interpreter path ahead of the real script path must resolve to the
|
||
// script path alone, not a combined interpreter+script string.
|
||
test('K: configuredEntrypointsIn does not include a preceding interpreter path', () => {
|
||
const configDir = path.join(os.tmpdir(), '.claude');
|
||
const scriptPath = path.join(configDir, 'hooks', 'gsd-write-guard.js');
|
||
const text = `"command": "/usr/local/bin/node ${scriptPath} --flag"`;
|
||
|
||
assert.deepEqual(configuredEntrypointsIn(text, configDir), [path.resolve(scriptPath)]);
|
||
});
|
||
});
|
||
|
||
|
||
// ────────────────────────────────────────────────────────────────────────
|
||
// Folded from tests/bug-131-release-tarball-smoke-explicit-home.test.cjs — consolidation epic #1969 (B6 #1975)
|
||
// ────────────────────────────────────────────────────────────────────────
|
||
{
|
||
const { describe: __foldDescribe } = require('node:test');
|
||
__foldDescribe("folded:bug-131-release-tarball-smoke-explicit-home (consolidation epic #1969 B6 #1975)", () => {
|
||
// allow-test-rule: integration-test-input (see #131)
|
||
// Regression test for #131: runNpm() must not fail when HOME points at an
|
||
// unwritable directory. The before() hook in release-tarball-smoke.install.test.cjs
|
||
// calls runNpm(['pack', ...]) and runNpm(['install', '-g', ...]) — if those inherit
|
||
// an unwritable HOME from the environment (common in constrained Docker hosts),
|
||
// the entire hook fails and all 6 subtests are cancelled.
|
||
//
|
||
// Fix: runNpm() must inject an explicit HOME, npm_config_cache, and
|
||
// npm_config_userconfig that point into a temp directory it owns, so that npm
|
||
// never reads from or writes to the caller's HOME.
|
||
//
|
||
// Test 3 (added in the second fix pass) verifies that isolatedNpmEnv() — the
|
||
// companion export that lets runSmoke() apply the same isolation — also redirects
|
||
// HOME away from the caller's HOME. Without this, subtests A-F of
|
||
// release-tarball-smoke.install.test.cjs still fail because runSmoke() calls
|
||
// spawnSync('npm', ...) internally and was not covered by the runNpm() fix.
|
||
|
||
'use strict';
|
||
|
||
const { describe, test } = require('node:test');
|
||
const assert = require('node:assert/strict');
|
||
const fs = require('node:fs');
|
||
const os = require('node:os');
|
||
const path = require('node:path');
|
||
const { execFileSync } = require('node:child_process');
|
||
|
||
// The helpers under test.
|
||
const { isolatedNpmEnv, cleanup } = require('./helpers.cjs');
|
||
|
||
// Bounds the `node -e` npm-harness spawn pattern shared by the three
|
||
// execFileSync(process.execPath, ['-e', script], ...) sites in this file,
|
||
// each of which requires helpers.cjs and calls runNpm(...).
|
||
const NPM_HARNESS_SPAWN_TIMEOUT_MS = 30_000;
|
||
|
||
// Resolve a filesystem path to its canonical (symlink-free) form even if the
|
||
// leaf does not exist yet (e.g. ~/.npm before npm has written its cache).
|
||
// Walks up to the nearest existing ancestor, resolves that, then re-appends
|
||
// the trailing segments. This handles macOS /var → /private/var symlinks for
|
||
// paths created under os.tmpdir() where the leaf directory may not exist yet.
|
||
function safeRealpath(p) {
|
||
try {
|
||
return fs.realpathSync(p);
|
||
} catch (_) {
|
||
// Leaf does not exist — resolve the nearest existing ancestor then
|
||
// reconstruct the original suffix so the result is still canonical.
|
||
const segments = [];
|
||
let cur = p;
|
||
for (;;) {
|
||
const parent = path.dirname(cur);
|
||
if (parent === cur) {
|
||
// Reached filesystem root — return original path unchanged.
|
||
return p;
|
||
}
|
||
segments.unshift(path.basename(cur));
|
||
cur = parent;
|
||
try {
|
||
return path.join(fs.realpathSync(cur), ...segments);
|
||
} catch (__) {
|
||
// Keep walking up.
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
describe('bug-131: runNpm isolates HOME from the caller environment', () => {
|
||
// ── Test 1 — runNpm works with an unwritable HOME ────────────────────────
|
||
// Spawn a child Node process that sets HOME to an unwritable directory, then
|
||
// invokes runNpm(['cache', 'verify']). `npm --version` performs zero
|
||
// filesystem I/O against HOME/.npm or HOME/.npmrc on modern npm, and even
|
||
// `npm config get cache` only *resolves* the cache path as a string without
|
||
// touching disk — both stay green even without HOME isolation, making the
|
||
// assertion vacuous. `npm cache verify` genuinely creates/reads/writes the
|
||
// cache directory under HOME (mkdir _cacache, write logs), so without the
|
||
// fix it fails with ENOTDIR against the unwritable HOME, and with the fix
|
||
// runNpm's injected isolated HOME lets it succeed. (Proven empirically: with
|
||
// this exact probe, neutralising runNpm()'s isolation flips this test from
|
||
// green to red, whereas `npm config get cache` stayed green either way.)
|
||
test('runNpm succeeds even when process HOME is unwritable', () => {
|
||
// Simulate an unwritable HOME with a mechanism that holds for every uid,
|
||
// including root (as gsd-test Docker benches run). chmod 0o500 is
|
||
// insufficient because root bypasses mode bits entirely, silently making
|
||
// this assertion vacuous under root — see CLAUDE.md section 4. Instead,
|
||
// make the PARENT of "HOME" a regular file rather than a directory: any
|
||
// attempt to create or write an entry under a non-directory parent fails
|
||
// with ENOTDIR at the filesystem/VFS level, a property that has nothing
|
||
// to do with permission bits and therefore cannot be bypassed by root.
|
||
const poisonedHomeBlocker = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-bug131-poison-'));
|
||
const blockerFile = path.join(poisonedHomeBlocker, 'blocker');
|
||
fs.writeFileSync(blockerFile, ''); // regular file, not a directory
|
||
const poisonedHome = path.join(blockerFile, 'home'); // parent is a file → ENOTDIR
|
||
try {
|
||
|
||
// We exercise the real runNpm() path by running a tiny inline Node script
|
||
// that requires helpers.cjs and calls runNpm(['cache', 'verify']) with
|
||
// HOME set to the unwritable dir. The script exits 0 on success, non-zero
|
||
// on throw.
|
||
const script = `
|
||
process.env.HOME = ${JSON.stringify(poisonedHome)};
|
||
process.env.USERPROFILE = ${JSON.stringify(poisonedHome)};
|
||
const { runNpm } = require(${JSON.stringify(path.join(__dirname, 'helpers.cjs'))});
|
||
try {
|
||
const out = runNpm(['cache', 'verify']);
|
||
if (!out || out.trim() === '') process.exit(2); // vacuous success guard
|
||
process.stdout.write(out);
|
||
process.exit(0);
|
||
} catch (e) {
|
||
process.stderr.write(e.message + '\\n');
|
||
process.exit(1);
|
||
}
|
||
`;
|
||
|
||
let stdout = '';
|
||
let stderr = '';
|
||
let exitCode = 0;
|
||
try {
|
||
stdout = execFileSync(process.execPath, ['-e', script], {
|
||
encoding: 'utf-8',
|
||
timeout: NPM_HARNESS_SPAWN_TIMEOUT_MS,
|
||
});
|
||
} catch (err) {
|
||
stdout = err.stdout || '';
|
||
stderr = err.stderr || '';
|
||
exitCode = err.status ?? 1;
|
||
}
|
||
|
||
assert.equal(
|
||
exitCode,
|
||
0,
|
||
`runNpm should succeed with an unwritable HOME but exited ${exitCode}. stderr: ${stderr}`,
|
||
);
|
||
// npm cache verify reports what it found/fixed in the cache directory.
|
||
assert.match(
|
||
stdout,
|
||
/cache verified|content verified/i,
|
||
`expected npm cache verify output, got: ${stdout}`,
|
||
);
|
||
} finally {
|
||
// poisonedHome itself was never created (its parent is a file), so only
|
||
// the directory holding the blocker file needs cleanup.
|
||
cleanup(poisonedHomeBlocker);
|
||
}
|
||
});
|
||
|
||
// ── Test 2 — runNpm does not leak a caller-supplied HOME into npm ────────
|
||
// Even if the caller exports HOME=/some/real/path, the injected HOME must be
|
||
// a different (temp) path so npm writes never touch the caller's $HOME.
|
||
test('runNpm injects a HOME distinct from process.env.HOME', () => {
|
||
// Capture what HOME runNpm actually passes to npm by asking npm to print
|
||
// the value it sees for the $HOME env var. We do this via `npm config get
|
||
// cache` which reveals the cache path — if it's under process.env.HOME,
|
||
// the fix is absent; if it's under a tmp dir, the fix is present.
|
||
|
||
const script = `
|
||
const { runNpm } = require(${JSON.stringify(path.join(__dirname, 'helpers.cjs'))});
|
||
try {
|
||
// npm config get cache prints the effective cache directory.
|
||
const out = runNpm(['config', 'get', 'cache']);
|
||
process.stdout.write(out.trim());
|
||
process.exit(0);
|
||
} catch (e) {
|
||
process.stderr.write(e.message + '\\n');
|
||
process.exit(1);
|
||
}
|
||
`;
|
||
|
||
let stdout = '';
|
||
let stderr = '';
|
||
let exitCode = 0;
|
||
try {
|
||
stdout = execFileSync(process.execPath, ['-e', script], {
|
||
encoding: 'utf-8',
|
||
timeout: NPM_HARNESS_SPAWN_TIMEOUT_MS,
|
||
});
|
||
} catch (err) {
|
||
stdout = err.stdout || '';
|
||
stderr = err.stderr || '';
|
||
exitCode = err.status ?? 1;
|
||
}
|
||
|
||
assert.equal(
|
||
exitCode,
|
||
0,
|
||
`runNpm config get cache failed with exit ${exitCode}. stderr: ${stderr}`,
|
||
);
|
||
|
||
const effectiveCacheDir = stdout.trim();
|
||
|
||
// The effective npm cache must NOT be inside the calling process's HOME.
|
||
// If it is, the fix was not applied and the Docker regression can still occur.
|
||
const callerHome = os.homedir();
|
||
assert.ok(
|
||
!effectiveCacheDir.startsWith(callerHome),
|
||
`npm cache dir ${effectiveCacheDir} is still under caller HOME ${callerHome} — fix not applied`,
|
||
);
|
||
|
||
// It must be somewhere under the system tmp dir, confirming isolation.
|
||
// Use safeRealpath on both sides so that macOS /var→/private/var symlinks
|
||
// do not cause a false mismatch when os.tmpdir() and the resolved cache
|
||
// path differ only in symlink expansion. The cache sub-directory (.npm) may
|
||
// not exist yet; safeRealpath walks up to the nearest existing ancestor.
|
||
const sysTmp = safeRealpath(os.tmpdir());
|
||
const realCacheDir = safeRealpath(effectiveCacheDir);
|
||
assert.ok(
|
||
realCacheDir.startsWith(sysTmp),
|
||
`npm cache dir ${realCacheDir} should be under tmpdir ${sysTmp}`,
|
||
);
|
||
});
|
||
|
||
// ── Test 3 — isolatedNpmEnv() redirects HOME away from the caller's HOME ──
|
||
// runSmoke() calls spawnSync('npm', ...) with npmEnv from isolatedNpmEnv().
|
||
// If isolatedNpmEnv() didn't redirect HOME, subtests A-F would still fail on
|
||
// Docker hosts with an unwritable HOME (the original bug #131 root cause,
|
||
// manifesting via the sibling runSmoke() path). (#131)
|
||
test('isolatedNpmEnv() HOME is distinct from the caller HOME and lives under tmpdir', () => {
|
||
const env = isolatedNpmEnv();
|
||
|
||
// Must expose a HOME key.
|
||
assert.ok(
|
||
typeof env.HOME === 'string' && env.HOME.length > 0,
|
||
'isolatedNpmEnv() must set HOME',
|
||
);
|
||
|
||
// Must not be the caller's HOME.
|
||
const callerHome = os.homedir();
|
||
assert.notEqual(
|
||
env.HOME,
|
||
callerHome,
|
||
`isolatedNpmEnv() HOME must differ from caller HOME ${callerHome}`,
|
||
);
|
||
|
||
// Must live under the system tmpdir, confirming it is an isolated temp directory.
|
||
// Use safeRealpath on both sides so that macOS /var→/private/var symlinks
|
||
// do not cause a false mismatch.
|
||
const sysTmp = safeRealpath(os.tmpdir());
|
||
const realHome = safeRealpath(env.HOME);
|
||
assert.ok(
|
||
realHome.startsWith(sysTmp),
|
||
`isolatedNpmEnv() HOME ${realHome} should be under tmpdir ${sysTmp}`,
|
||
);
|
||
|
||
// npm_config_cache and npm_config_userconfig must also be set and under the isolated HOME.
|
||
assert.ok(
|
||
typeof env.npm_config_cache === 'string' && env.npm_config_cache.startsWith(env.HOME),
|
||
`npm_config_cache ${env.npm_config_cache} should be under isolated HOME ${env.HOME}`,
|
||
);
|
||
assert.ok(
|
||
typeof env.npm_config_userconfig === 'string' && env.npm_config_userconfig.startsWith(env.HOME),
|
||
`npm_config_userconfig ${env.npm_config_userconfig} should be under isolated HOME ${env.HOME}`,
|
||
);
|
||
assert.equal(
|
||
env.npm_config_loglevel,
|
||
'error',
|
||
'isolatedNpmEnv() should suppress npm notice/warn chatter in test gates',
|
||
);
|
||
assert.equal(
|
||
env.npm_config_update_notifier,
|
||
'false',
|
||
'isolatedNpmEnv() should disable npm update-notifier notices in test gates',
|
||
);
|
||
assert.equal(
|
||
env.NO_UPDATE_NOTIFIER,
|
||
'1',
|
||
'isolatedNpmEnv() should disable npm update-notifier notices for npm versions that honor NO_UPDATE_NOTIFIER',
|
||
);
|
||
});
|
||
|
||
// ── Test 4 — runNpm's 180000ms bound survives an explicit `timeout: undefined` ──
|
||
// (#3148 wave 4) runNpm() used to spread `...defaults` (which carries
|
||
// `timeout: 180000`) and then `...otherOptions` AFTER it, so a caller
|
||
// passing an own `timeout: undefined` key (not an omission) silently won
|
||
// the spread and erased the bound, leaving the underlying execFileSync call
|
||
// unbounded. The fix destructures `timeout` off `options` with a default
|
||
// and passes it explicitly after both spreads, so an own `undefined` key
|
||
// resolves to the default instead of erasing it.
|
||
//
|
||
// Proof is behavioral, not textual: a fresh child process monkeypatches
|
||
// `child_process.execFileSync` to capture the options object it actually
|
||
// receives — before `helpers.cjs` is required in that child, so its
|
||
// top-level `const { execFileSync } = require('child_process')` picks up
|
||
// the patched function — then calls `runNpm(['--version'], { timeout:
|
||
// undefined })` and reports back the captured `timeout` value. Reverting
|
||
// the destructure-with-default fix (restoring the plain `{ ...defaults,
|
||
// ...otherOptions, env: mergedEnv }` spread order) makes this test fail:
|
||
// the captured `timeout` becomes `undefined` instead of `180000`.
|
||
test('runNpm resolves an explicit `timeout: undefined` to the 180000ms bound, not unbounded', () => {
|
||
const script = `
|
||
const cp = require('node:child_process');
|
||
const seen = [];
|
||
cp.execFileSync = (cmd, args, options) => {
|
||
seen.push(options);
|
||
return '9.9.9';
|
||
};
|
||
const { runNpm } = require(${JSON.stringify(path.join(__dirname, 'helpers.cjs'))});
|
||
// An own \`timeout: undefined\` key — not an omitted key — is the exact
|
||
// hazard: a caller-controlled property that must not erase the bound.
|
||
runNpm(['--version'], { timeout: undefined });
|
||
process.stdout.write(JSON.stringify({ timeout: seen[0] && seen[0].timeout }));
|
||
`;
|
||
|
||
let stdout = '';
|
||
let stderr = '';
|
||
let exitCode = 0;
|
||
try {
|
||
stdout = execFileSync(process.execPath, ['-e', script], {
|
||
encoding: 'utf-8',
|
||
timeout: NPM_HARNESS_SPAWN_TIMEOUT_MS,
|
||
});
|
||
} catch (err) {
|
||
stdout = err.stdout || '';
|
||
stderr = err.stderr || '';
|
||
exitCode = err.status ?? 1;
|
||
}
|
||
|
||
assert.equal(
|
||
exitCode,
|
||
0,
|
||
`runNpm timeout-capture probe failed with exit ${exitCode}. stderr: ${stderr}`,
|
||
);
|
||
|
||
const captured = JSON.parse(stdout.trim());
|
||
assert.equal(
|
||
captured.timeout,
|
||
180000,
|
||
`runNpm must resolve an explicit timeout: undefined to the 180000ms bound; ` +
|
||
`captured options.timeout was ${JSON.stringify(captured.timeout)} — an unset bound ` +
|
||
`is not a bound (DEFECT.UNBOUNDED-SUBPROCESS)`,
|
||
);
|
||
});
|
||
});
|
||
});
|
||
}
|