* 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>
This commit is contained in:
committed by
GitHub
parent
49f313d611
commit
ad1477d659
5
.changeset/quick-wasps-sing.md
Normal file
5
.changeset/quick-wasps-sing.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
type: Changed
|
||||
pr: 4249
|
||||
---
|
||||
**`gsd install` and `/gsd-update` now verify every GSD-managed runtime entrypoint before reporting success** — a hook script or its interpreter that is missing, unreadable, or not executable now fails the install with the offending paths named, instead of printing `Done!` over a configuration whose hooks can never fire.
|
||||
8
.github/workflows/install-smoke.yml
vendored
8
.github/workflows/install-smoke.yml
vendored
@@ -144,6 +144,14 @@ jobs:
|
||||
if: steps.skip.outputs.skip != 'true'
|
||||
run: npm ci
|
||||
|
||||
# `npm pack` runs prepack/prepare (build:lib) but NOT prepublishOnly, so
|
||||
# a packed tarball is missing hooks/dist — the very launch targets the
|
||||
# published package ships and the lifecycle smoke is meant to exercise.
|
||||
# Build them here so the smoked tarball is publish-shaped (#4154).
|
||||
- name: Build hooks (prepublishOnly parity)
|
||||
if: steps.skip.outputs.skip != 'true'
|
||||
run: npm run build:hooks
|
||||
|
||||
- name: Pack root tarball
|
||||
if: steps.skip.outputs.skip != 'true'
|
||||
id: pack
|
||||
|
||||
File diff suppressed because one or more lines are too long
220
bin/install.js
220
bin/install.js
@@ -10850,6 +10850,7 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
|
||||
// Track installation failures
|
||||
const failures = [];
|
||||
const configuredEntrypoints = [];
|
||||
let installerMigrationResult = null;
|
||||
const rollbackInstallerMigrations = () => {
|
||||
if (!installerMigrationResult || typeof installerMigrationResult.rollback !== 'function') return;
|
||||
@@ -10932,12 +10933,17 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
// destroyed by a wholesale delete whose snapshot lacked it.
|
||||
let codexManagedSnapshotCaptured = false;
|
||||
// null = the gate never ran; true/false = the gate ran and hooks/ (did|did
|
||||
// not) exist as a directory pre-install. Three states are load-bearing: a
|
||||
// not) exist as a directory pre-install. Two states are load-bearing: a
|
||||
// clean first install records false, so its rollback removes the staged
|
||||
// hooks/ tree entirely; minimal mode records null, so rollback does nothing.
|
||||
// hooks/ tree entirely; a non-Codex runtime records null, so rollback does
|
||||
// nothing.
|
||||
let codexPreInstallHooksDirPreExisted = null;
|
||||
let codexPreInstallHooksCaptureIncomplete = false;
|
||||
if (_hostBehaviors(runtime).tomlConfigInstall && !isMinimalMode(_effectiveInstallMode)) {
|
||||
// #4249 CR: not gated on install mode. restoreCodexSnapshot is reachable for
|
||||
// a core/--minimal install too (#2695), and its pass-2 sweeps remove every
|
||||
// gsd-* skill dir / agent file the snapshot does not claim — so an empty
|
||||
// minimal-mode snapshot deleted the whole surface with nothing to restore.
|
||||
if (_hostBehaviors(runtime).tomlConfigInstall) {
|
||||
codexManagedSnapshotCaptured = true;
|
||||
const _preSkillsDir = _resolveSkillsRootDir(runtime, targetDir, _installScopeId);
|
||||
if (fs.existsSync(_preSkillsDir)) {
|
||||
@@ -12824,6 +12830,7 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
absoluteRunner: codexNodeRunner,
|
||||
platform: process.platform,
|
||||
});
|
||||
configuredEntrypoints.push(...(hookWrite.configuredEntrypoints || []));
|
||||
if (hookWrite.wrote) {
|
||||
console.log(` ${green}✓${reset} Configured Codex hooks (SessionStart via hooks.json)`);
|
||||
} else {
|
||||
@@ -12903,7 +12910,21 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
}
|
||||
|
||||
persistActiveProfileMarker();
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
// #4249: expose restoreCodexSnapshot (#3245) as a SECOND, separately named
|
||||
// rollback rather than rebinding `rollbackInstallerMigrations` to it. A
|
||||
// configured-entrypoint validation failure discovered later (outside this
|
||||
// function, after Codex's own hooks.json/config.toml write already
|
||||
// succeeded) previously had only the installer-migrations closure to call,
|
||||
// leaving the just-written config.toml/hooks.json broken on disk despite
|
||||
// Codex already owning a full pre-install snapshot/restore for exactly this.
|
||||
//
|
||||
// Every runtime's `rollbackInstallerMigrations` therefore still means what
|
||||
// it says — the installer-migrations-only closure, which is what a
|
||||
// finalize-stage failure that is NOT an entrypoint-validation failure gets
|
||||
// (the Phase 4 contract). `rollbackPreInstallSnapshot` is Codex-only and is
|
||||
// chosen only for entrypoint-validation failures. See the selection in
|
||||
// installAllRuntimes' rollbackFinalizedInstallerMigrations.
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints, rollbackInstallerMigrations, rollbackPreInstallSnapshot: restoreCodexSnapshot };
|
||||
}
|
||||
|
||||
if (plan.installSurface === 'copilot-instructions') {
|
||||
@@ -12933,7 +12954,18 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
writeCopilotHookConfig(targetDir);
|
||||
console.log(` ${green}✓${reset} Configured Copilot lifecycle hook (sessionStart)`);
|
||||
persistActiveProfileMarker();
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
// #4249: `[]`, not omitted — every Copilot hook is an inline `printf`
|
||||
// one-liner (GSD_COPILOT_*_HOOK_BASH/PWSH in src/runtime-hooks-surface.cts),
|
||||
// so this runtime genuinely launches no GSD-managed script and has no
|
||||
// interpreter to resolve. Stated explicitly like every other branch rather
|
||||
// than leaning on installAllRuntimes' `|| []` defence.
|
||||
// #4249 (antigravity review): `rollbackInstallerMigrations` was missing here
|
||||
// — every other branch returns it. This PR's own aggregate entrypoint gate
|
||||
// is what makes the gap reachable: an unrelated runtime's invalid entrypoint
|
||||
// now triggers rollbackFinalizedInstallerMigrations for every result in the
|
||||
// batch, and a Copilot result with no rollback function silently skips
|
||||
// reverting Copilot's own installer migrations.
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints: [], rollbackInstallerMigrations };
|
||||
}
|
||||
|
||||
if (plan.installSurface === 'cursor-hooks-json') {
|
||||
@@ -12956,7 +12988,7 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
// The re-run is retained for parity with the settings.json install path.
|
||||
writeManifest(targetDir, runtime, { mode: _effectiveInstallMode, scope: _installScopeId });
|
||||
persistActiveProfileMarker();
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints: cursorHookResult.configuredEntrypoints, rollbackInstallerMigrations };
|
||||
}
|
||||
|
||||
if (plan.installSurface === 'profile-marker-only') {
|
||||
@@ -13012,6 +13044,7 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
const kimiHookOpts = { portableHooks: hasPortableHooks, runtime };
|
||||
const kimiHooksTomlPath = path.join(kimiHooksRoot, 'config.toml');
|
||||
const kimiHooksResult = writeKimiHooksToml(kimiHooksTomlPath, kimiHooksRoot, { hookOpts: kimiHookOpts });
|
||||
configuredEntrypoints.push(...kimiHooksResult.configuredEntrypoints);
|
||||
if (kimiHooksResult.changed) {
|
||||
console.log(` ${green}✓${reset} Configured ${kimiHooksResult.entryCount} GSD hook(s) in ${kimiHooksTomlPath}`);
|
||||
}
|
||||
@@ -13068,6 +13101,7 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
const windsurfHookResult = writeWindsurfHooksJson(targetDir, src, {
|
||||
platform: process.platform,
|
||||
});
|
||||
configuredEntrypoints.push(...windsurfHookResult.configuredEntrypoints);
|
||||
if (windsurfHookResult.changed) {
|
||||
console.log(` ${green}✓${reset} Configured Windsurf lifecycle hooks (pre_write_code, pre_run_command)`);
|
||||
} else {
|
||||
@@ -13083,19 +13117,19 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
}
|
||||
|
||||
persistActiveProfileMarker();
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints, rollbackInstallerMigrations };
|
||||
}
|
||||
|
||||
if (plan.installSurface === 'cline-rules') {
|
||||
// Cline uses the `.clinerules/` directory form (issue #787): GSD rules live
|
||||
// at .clinerules/gsd.md and a PreToolUse lifecycle hook at
|
||||
// .clinerules/hooks/PreToolUse. Global installs also get ~/.agents/AGENTS.md.
|
||||
writeClineArtifacts(targetDir, isGlobal);
|
||||
const clineArtifacts = writeClineArtifacts(targetDir, isGlobal);
|
||||
// Re-run the manifest pass: these artifacts are written *after* the earlier
|
||||
// writeManifest() call, so a second pass is needed to hash-track them.
|
||||
writeManifest(targetDir, runtime, { mode: _effectiveInstallMode, scope: _installScopeId });
|
||||
persistActiveProfileMarker();
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints: clineArtifacts.configuredEntrypoints, rollbackInstallerMigrations };
|
||||
}
|
||||
|
||||
// Configure statusline and hooks in settings.json (or settings.local.json for local Claude installs).
|
||||
@@ -13220,8 +13254,11 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
persistActiveProfileMarker();
|
||||
// Callers index this result by `runtime` (installAllRuntimes' statusline
|
||||
// lookup), so every early exit must return the full shape — a bare return
|
||||
// crashes the install rather than skipping one file.
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir };
|
||||
// crashes the install rather than skipping one file. That includes
|
||||
// configuredEntrypoints/rollbackInstallerMigrations: rollbackFinalizedInstallerMigrations
|
||||
// reads result.rollbackInstallerMigrations unconditionally, and an omitted
|
||||
// field there silently skips this runtime's rollback on a finalize-stage failure.
|
||||
return { settingsPath: null, settings: null, statuslineCommand: null, updateBannerCommand: null, runtime, configDir: targetDir, configuredEntrypoints: [], rollbackInstallerMigrations };
|
||||
}
|
||||
const settings = validateHookFields(cleanupOrphanedHooks(rawSettings));
|
||||
// #3002 CR / #3662: rewrite legacy `node .../gsd-*.js` command strings (pre-
|
||||
@@ -13243,7 +13280,19 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
// runtime's hostBehaviors instead of a hardcoded `runtime === 'antigravity'`
|
||||
// check inside projectLocalHookPrefix.
|
||||
const localPrefix = projectLocalHookPrefix({ runtime, dirName, hookPathStyle: _hostBehaviors(runtime).hookPathStyle });
|
||||
const hookOpts = { portableHooks: hasPortableHooks, runtime };
|
||||
const settingsEntrypoints = [];
|
||||
const hookOpts = {
|
||||
portableHooks: hasPortableHooks,
|
||||
runtime,
|
||||
configPath: settingsPath,
|
||||
// #4249: track unconditionally. Gating on `plan.hooksSurface ===
|
||||
// 'settings-json'` made tracking depend on an unasserted
|
||||
// installSurface/hooksSurface coupling — a descriptor that broke it would
|
||||
// silently drop this runtime out of validation. Everything recorded here
|
||||
// lands in settings.json by construction, and the registered-command
|
||||
// filter below already discards entries no hook actually references.
|
||||
configuredEntrypoints: settingsEntrypoints,
|
||||
};
|
||||
// #2979: local-install hook commands also use a runner GUI/minimal-PATH
|
||||
// runtimes can resolve. Bare `node` fails when the host launches the
|
||||
// runtime with a stripped PATH (Finder/Antigravity/etc) — #3662 replaces
|
||||
@@ -13257,19 +13306,19 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
// `node` command that recreates the #2979 failure.
|
||||
const localCmd = (hookFile) => localNodeRunner === null
|
||||
? null
|
||||
: projectShellCommandText({
|
||||
: hooksSurface.recordConfiguredHookCommand(projectShellCommandText({
|
||||
runnerToken: localNodeRunner,
|
||||
argTokens: [`${localPrefix}/hooks/${hookFile}`],
|
||||
runtime,
|
||||
platform: process.platform,
|
||||
});
|
||||
const localShellCmd = (hookFile) => buildLocalShellHookCommand({
|
||||
}), targetDir, hookFile, hookOpts);
|
||||
const localShellCmd = (hookFile) => hooksSurface.recordConfiguredHookCommand(buildLocalShellHookCommand({
|
||||
localPrefix,
|
||||
hookFile,
|
||||
bashRunner: localBashRunner,
|
||||
runtime,
|
||||
platform: process.platform,
|
||||
});
|
||||
}), targetDir, hookFile, hookOpts);
|
||||
const statuslineCommand = isGlobal
|
||||
? buildHookCommand(targetDir, 'gsd-statusline.js', hookOpts)
|
||||
: localCmd('gsd-statusline.js');
|
||||
@@ -13339,6 +13388,31 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
? buildHookCommand(targetDir, 'gsd-update-banner.js', hookOpts)
|
||||
: localCmd('gsd-update-banner.js'));
|
||||
|
||||
const registeredHookCommands = Object.values(settings.hooks || {})
|
||||
.flatMap(groups => Array.isArray(groups) ? groups : [])
|
||||
.flatMap(group => Array.isArray(group && group.hooks) ? group.hooks : [])
|
||||
.map(hook => hook && hook.command)
|
||||
.filter(command => typeof command === 'string');
|
||||
// #4249: match by the managed script's `/hooks/<basename>` path segment, not
|
||||
// by exact command-string equality. The blocking-guard hooks above register
|
||||
// only-if-absent, so a hook already present from a prior install keeps its
|
||||
// OLD command untouched — but `track()` always records the FRESHLY computed
|
||||
// command for it, which never equals what's actually persisted. Matching on
|
||||
// the segment (present in the persisted command either way, since every
|
||||
// entry.scriptPath is <configDir>/hooks/<name> by construction) keeps an
|
||||
// already-registered, still-active hook in the validated set instead of
|
||||
// silently dropping it (#4154 Blocker) — anchored on `/hooks/` rather than a
|
||||
// bare basename so an unrelated user command that merely mentions the same
|
||||
// filename can't false-positive into GSD's validated set.
|
||||
configuredEntrypoints.push(
|
||||
...settingsEntrypoints.filter(entry => {
|
||||
const hooksSegment = '/hooks/' + path.basename(entry.scriptPath);
|
||||
return registeredHookCommands.some(command => command.includes(hooksSegment));
|
||||
}),
|
||||
);
|
||||
const statuslineEntrypoints = settingsEntrypoints.filter(entry => entry.command === statuslineCommand);
|
||||
const updateBannerEntrypoints = settingsEntrypoints.filter(entry => entry.command === updateBannerCommand);
|
||||
|
||||
// #683: Set worktree.baseRef:"head" in settings.local.json for local Claude installs.
|
||||
// Both fresh and upgrade paths apply only when worktrees are enabled for the project.
|
||||
// Never applies to global installs, non-Claude runtimes, or when the user already
|
||||
@@ -13407,15 +13481,65 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
|
||||
settings,
|
||||
statuslineCommand,
|
||||
updateBannerCommand,
|
||||
statuslineEntrypoints,
|
||||
updateBannerEntrypoints,
|
||||
runtime,
|
||||
configDir: targetDir,
|
||||
rollbackInstallerMigrations,
|
||||
configuredEntrypoints,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply statusline config, then print completion message
|
||||
*/
|
||||
// #4249 (review, Major): rollback consequence differs by runtime surface —
|
||||
// see docs/how-to/update-gsd.md's rollback-matrix paragraph, which this
|
||||
// mirrors. Codex reverts (pre-install snapshot restore); Cursor/Windsurf/
|
||||
// Kimi/Kimi Code/Cline already wrote their config file inside install(),
|
||||
// ahead of this gate, with no revert path, so it is left on disk broken;
|
||||
// every other (settings.json-based) runtime writes strictly after this gate,
|
||||
// so a failure here means nothing new was persisted for it.
|
||||
const ENTRYPOINT_LEFT_UNREVERTED_RUNTIMES = new Set(['cursor', 'windsurf', 'kimi', 'kimi-code', 'cline']);
|
||||
function describeEntrypointConsequence(invalidRuntime) {
|
||||
if (invalidRuntime === 'codex') return 'reverted: its pre-install snapshot was restored';
|
||||
if (ENTRYPOINT_LEFT_UNREVERTED_RUNTIMES.has(invalidRuntime)) return 'NOT reverted: its config file is already written and was left on disk — fix the reported path and rerun install';
|
||||
return 'not persisted: this runtime writes its config after this check';
|
||||
}
|
||||
|
||||
function assertConfiguredEntrypoints(entries) {
|
||||
// #4249: some writers push the same (configPath, scriptPath) pair more than
|
||||
// once (e.g. Kimi's context-monitor hook registered under several events,
|
||||
// or the portable resolver script shared by every portable JS hook) — keep
|
||||
// one so a broken entry is reported once, not once per duplicate.
|
||||
const seen = new Set();
|
||||
const deduped = (entries || []).filter((entry) => {
|
||||
const key = JSON.stringify([entry.configPath, entry.scriptPath]);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
const validation = hooksSurface.validateConfiguredEntrypoints(deduped);
|
||||
if (validation.ok) return;
|
||||
|
||||
const error = new Error(
|
||||
// #4249: lead each entry with its runtime, and name the actual consequence
|
||||
// for that runtime (review, Major) — the aggregate gate is all-or-nothing
|
||||
// across every runtime being installed, and a failure here can revert a
|
||||
// runtime whose own entrypoints were fine (see
|
||||
// rollbackFinalizedInstallerMigrations) while leaving another runtime's
|
||||
// already-written config broken on disk with no revert at all, so an
|
||||
// operator reading only this message must be able to tell WHOSE
|
||||
// entrypoint broke and WHAT that means for their config, not just that
|
||||
// something did.
|
||||
`Configured entrypoint validation failed: ${validation.invalid.map(({ runtime: invalidRuntime, role, path: invalidPath, reason }) => `${invalidRuntime} ${role} ${invalidPath} (${reason}) [${describeEntrypointConsequence(invalidRuntime)}]`).join(', ')}`,
|
||||
);
|
||||
error.configuredEntrypointValidation = validation;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// #4249: `bannerOpts.configuredEntrypoints` is the ONLY source assertConfiguredEntrypoints
|
||||
// checks below — a caller that omits it (or calls finishInstall directly instead of
|
||||
// through installAllRuntimes) gets zero entrypoint validation, silently. installAllRuntimes
|
||||
// always passes the full set (per-runtime entries plus statusline/updateBanner); any other
|
||||
// caller must do the same for this gate to mean anything.
|
||||
function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallStatusline, runtime = DEFAULT_RUNTIME, isGlobal = true, configDir = null, bannerOpts = {}) {
|
||||
// #2093: isKilo dropped — the Kilo permissions-writer call below is gated
|
||||
// on plan.finishPermissionWriter === 'kilo' (descriptor-driven), not this flag.
|
||||
@@ -13429,6 +13553,19 @@ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallS
|
||||
const { isOpencode, isCodex, isCursor, isAugment, isQwen, isHermes, isCline } = runtimeFlags(runtime);
|
||||
const plan = resolveInstallPlan(runtime);
|
||||
|
||||
// #4249 Major: validate BEFORE this function's own settings.json write (and
|
||||
// before writeNonClaudeDefaults) instead of after. Cursor/Windsurf/Kimi/Cline
|
||||
// already persisted their config inside install() by this point, with no
|
||||
// rollback path covering those writes; Codex also persists inside install()
|
||||
// but its rollback binds to a full pre-install snapshot restore, so it IS
|
||||
// covered (see docs/how-to/update-gsd.md). For the settings-json surface
|
||||
// this ordering means a failing validation never reaches this function's
|
||||
// own write at all. On the production path this is a redundant backstop —
|
||||
// installAllRuntimes's own aggregate assertConfiguredEntrypoints call
|
||||
// already validates the superset before finishInstall runs for any
|
||||
// runtime — kept for a caller that invokes finishInstall directly.
|
||||
assertConfiguredEntrypoints(bannerOpts.configuredEntrypoints);
|
||||
|
||||
if (shouldInstallStatusline && plan.writesSharedSettings && !_hostBehaviors(runtime).skipSettingsUi) {
|
||||
if (!isGlobal && !forceStatusline) {
|
||||
// Local installs skip statusLine by default: repo settings.json takes precedence over
|
||||
@@ -14326,10 +14463,32 @@ function installAllRuntimes(runtimes, isGlobal, isInteractive) {
|
||||
|
||||
const rollbackFinalizedInstallerMigrations = (error) => {
|
||||
const rollbackFailures = [];
|
||||
// #4249: this discriminates on the error's KIND, never on which runtime
|
||||
// owns the failing entrypoint. `wide` is true for ANY entrypoint-validation
|
||||
// failure from ANY runtime, by design: the aggregate gate exists so a
|
||||
// multi-runtime install cannot report success while one of its entrypoints
|
||||
// is broken, so an invalid Cline entrypoint reverts Codex's pre-install
|
||||
// snapshot too — even though Codex itself was fine and its own "Done!"
|
||||
// summary already printed. tests/configured-entrypoint-validation.test.cjs
|
||||
// ('an aggregate entrypoint validation failure rolls the Codex install
|
||||
// back') exercises exactly that, and it is the all-or-nothing behaviour
|
||||
// docs/how-to/update-gsd.md documents.
|
||||
//
|
||||
// What this narrows is the OTHER axis: a finalize-stage exception that is
|
||||
// not an entrypoint-validation failure at all — e.g. a sibling runtime's
|
||||
// permission-config write dying with EACCES — gets only the
|
||||
// installer-migrations-only rollback that Phase 4 specifies
|
||||
// (docs/installer-migrations.md#phase-4-installupdate-integration).
|
||||
// Un-installing (and, on update, downgrading) an already-"Done!" Codex over
|
||||
// an unrelated error is not an outcome any doc promises, while the sibling
|
||||
// surfaces that write config inside install() would keep theirs regardless.
|
||||
const wide = !!(error && error.configuredEntrypointValidation);
|
||||
for (const result of [...results].reverse()) {
|
||||
if (!result || typeof result.rollbackInstallerMigrations !== 'function') continue;
|
||||
if (!result) continue;
|
||||
const rollback = (wide && result.rollbackPreInstallSnapshot) || result.rollbackInstallerMigrations;
|
||||
if (typeof rollback !== 'function') continue;
|
||||
try {
|
||||
result.rollbackInstallerMigrations();
|
||||
rollback();
|
||||
} catch (rollbackError) {
|
||||
rollbackFailures.push({
|
||||
runtime: result.runtime,
|
||||
@@ -14357,6 +14516,19 @@ function installAllRuntimes(runtimes, isGlobal, isInteractive) {
|
||||
|
||||
const finalize = (shouldInstallStatusline, shouldInstallBanner) => {
|
||||
try {
|
||||
const selectedConfiguredEntrypoints = (result) => {
|
||||
if (!result || result.skipped) return [];
|
||||
const useStatusline = statuslineRuntimes.includes(result.runtime)
|
||||
&& shouldInstallStatusline
|
||||
&& (isGlobal || forceStatusline);
|
||||
return [
|
||||
...(result.configuredEntrypoints || []),
|
||||
...(useStatusline ? (result.statuslineEntrypoints || []) : []),
|
||||
...(shouldInstallBanner ? (result.updateBannerEntrypoints || []) : []),
|
||||
];
|
||||
};
|
||||
assertConfiguredEntrypoints(results.flatMap(selectedConfiguredEntrypoints));
|
||||
|
||||
const printSummaries = () => {
|
||||
for (const result of results) {
|
||||
if (result && result.skipped) continue;
|
||||
@@ -14370,7 +14542,11 @@ function installAllRuntimes(runtimes, isGlobal, isInteractive) {
|
||||
result.runtime,
|
||||
isGlobal,
|
||||
result.configDir,
|
||||
{ shouldInstallBanner: !!shouldInstallBanner, bannerCommand: result.updateBannerCommand }
|
||||
{
|
||||
shouldInstallBanner: !!shouldInstallBanner,
|
||||
bannerCommand: result.updateBannerCommand,
|
||||
configuredEntrypoints: selectedConfiguredEntrypoints(result),
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -476,7 +476,7 @@ Node.js CLI utility (`gsd-tools.cjs`) with domain modules split across `gsd-core
|
||||
| `graphify-command-router.cjs` | ADR-959 capability command router — first real capability command cutover (phase 4d-impl-2); extracted from the `case 'graphify':` arm in `gsd-tools.cjs`; dispatches build/query/status/diff subcommands; discovered via `commandFamilies` in the capability registry |
|
||||
| `audit-command-router.cjs` | ADR-959 capability command router (phase 4d-impl-3); extracted from the `case 'audit-uat':` and `case 'audit-open':` arms in `gsd-tools.cjs`; `routeAuditUat` → `uat.cjs:cmdAuditUat`, `routeAuditOpen` → `audit.cjs:{auditOpenArtifacts,formatAuditReport}`; discovered via `commandFamilies` in the capability registry |
|
||||
| `intel-command-router.cjs` | ADR-959 capability command router (phase 4d-impl-4, last first-party cutover); extracted from the `case 'intel':` arm in `gsd-tools.cjs`; `routeIntelCommand` → all 9 intel subcommands via lazy `require('./intel.cjs')`; preserves non-raw `timeAgo` transform on `status.files[*].updated_at`; discovered via `commandFamilies` in the capability registry |
|
||||
| `runtime-hooks-surface.cjs` | Standalone hook-surface writer module (ADR-857 phase 5f-1); owns Cline rules/agents-md/pre-tool-use hook generation, Cursor `hooks.json` reconciliation, Copilot session-hook config, and Codex hook-block management; extracted verbatim from `bin/install.js` with no logic change. |
|
||||
| `runtime-hooks-surface.cjs` | Hook-surface writer and configured-entrypoint validation module (ADR-857 phase 5f-1); owns Cline rules/agents-md/pre-tool-use hook generation, Cursor/Windsurf `hooks.json`, Kimi hook TOML, Copilot session-hook config, Codex hook-block management, and construction-time records for paths emitted into runtime configuration. Installer success requires those records to pass non-executing file-type and interpreter-resolution checks. |
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -26,7 +26,11 @@ GSD will:
|
||||
8. Offer to restore the user-added files it backed up in step 5.
|
||||
9. Report whether locally modified GSD files were backed up to `gsd-local-patches/`.
|
||||
|
||||
Restart your runtime after the update to pick up new commands and agents.
|
||||
Before reporting completion, the installer checks each GSD-managed script and interpreter path written into runtime configuration, resolving the interpreter against the current install-time `PATH`. This only proves the path resolves now — a hook fired later under a different, more restricted `PATH` (e.g. a GUI launcher) can still fail even after this check passes.
|
||||
|
||||
If a script is missing, unreadable, has the wrong file type, lacks a required execute permission, or its interpreter cannot be resolved, the update fails and reports every invalid path, each tagged with what happens to that runtime's config next. For Claude Code and other settings.json-based runtimes, this check runs before the update writes settings.json, so nothing new is persisted (an earlier settings.json/settings.local.json migration, if one applied, is the one exception and stays applied) — reported as "not persisted". For Codex, this reverts config.toml/hooks.json along with the rest of that runtime's pre-install snapshot (skills/, agents/, gsd-core/VERSION) — reported as "reverted". For Cursor, Windsurf, Kimi, and Cline, the runtime's config file is already written earlier in the update, ahead of this check, so a failure is reported but that file is left in place, broken — reported as "NOT reverted". Fix the reported path problem and rerun `/gsd-update` — do not restart into the incomplete update.
|
||||
|
||||
Restart your runtime after a successful update to pick up new commands and agents.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ module.exports = {
|
||||
"tests/config-loader.test.cjs",
|
||||
"tests/config-schema.property.test.cjs",
|
||||
"tests/config.test.cjs",
|
||||
"tests/configured-entrypoint-validation.test.cjs",
|
||||
"tests/contributor-standards.test.cjs",
|
||||
"tests/core-utils.test.cjs",
|
||||
"tests/cursor-subagent-isolation.test.cjs",
|
||||
|
||||
@@ -62,6 +62,7 @@ module.exports = {
|
||||
"tests/config-loader.test.cjs",
|
||||
"tests/config-schema.property.test.cjs",
|
||||
"tests/config.test.cjs",
|
||||
"tests/configured-entrypoint-validation.test.cjs",
|
||||
"tests/copilot-install.test.cjs",
|
||||
"tests/copilot-upgrades.test.cjs",
|
||||
"tests/core-utils.test.cjs",
|
||||
|
||||
@@ -37,6 +37,12 @@
|
||||
* colon-namespace leaks (WORKFLOW_BODY_COLON_LEAK).
|
||||
* This check populates result.details with counters but does NOT return a
|
||||
* failure code by default; it is informational until enforcement is enabled.
|
||||
*
|
||||
* Configured-entrypoint checks (Cycle 4 — #4154):
|
||||
* For each runtime in entrypointRuntimes, runs the tarball-installed
|
||||
* installer into a throwaway HOME, then re-reads that runtime's own written
|
||||
* config files and asserts every GSD-managed script path they name resolves
|
||||
* to a file (ENTRYPOINT_UNRESOLVED). Requires fixtureDir.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
@@ -47,6 +53,8 @@ const os = require('os');
|
||||
const path = require('path');
|
||||
const { PACKAGE_NAME } = require('../gsd-core/bin/lib/package-identity.cjs');
|
||||
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
|
||||
const shellCmdProjection = require('../gsd-core/bin/lib/shell-command-projection.cjs');
|
||||
const { escapeRegex } = require('../gsd-core/bin/lib/pattern.cjs');
|
||||
// 120 s proved too tight for cold-cache `npm install -g` of a 1499-file tarball:
|
||||
// spawnSync fires SIGTERM at the deadline and returns { status: null, stdout: '',
|
||||
// stderr: '' } (Node docs: status is null when a subprocess is terminated by a
|
||||
@@ -86,6 +94,8 @@ const SMOKE = Object.freeze({
|
||||
INIT_FAILED: 'init_failed',
|
||||
// Cycle 3 code
|
||||
WORKFLOW_BODY_COLON_LEAK: 'workflow_body_colon_leak',
|
||||
// Cycle 4 code (#4154)
|
||||
ENTRYPOINT_UNRESOLVED: 'entrypoint_unresolved',
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -274,6 +284,106 @@ function scanWorkflowColonLeak(filePath, cmdNames) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cycle 4 helpers: configured-entrypoint resolution (#4154)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Top-level config files this scan reads. These are the surfaces that carry
|
||||
* every GSD-managed launch path for the runtimes Cycle 4 actually installs
|
||||
* (`entrypointRuntimes`, default claude + codex): claude registers into
|
||||
* settings.json, codex into hooks.json and config.toml.
|
||||
*
|
||||
* This is NOT an exhaustive map of where GSD writes launch paths across all
|
||||
* runtimes, and the scan is top-level only by design. Two known surfaces sit
|
||||
* outside it: Cline registers its hook at `.clinerules/hooks/PreToolUse` (a
|
||||
* subdirectory, and not one of these names — see writeClineArtifacts in
|
||||
* src/runtime-hooks-surface.cts), and Kimi's native `[[hooks]]` config.toml
|
||||
* lives under `resolveKimiHooksTomlDir()` (`~/.kimi`), a directory separate
|
||||
* from Kimi's own GSD configDir. Adding either runtime to entrypointRuntimes
|
||||
* requires teaching scanConfiguredEntrypoints about its surface first,
|
||||
* otherwise the scan reports zero entrypoints and silently proves nothing.
|
||||
*/
|
||||
const RUNTIME_CONFIG_FILES = Object.freeze(['settings.json', 'hooks.json', 'config.toml']);
|
||||
|
||||
/**
|
||||
* Extract every script path `text` names underneath `configDir`.
|
||||
*
|
||||
* #4249 (antigravity review): anchored on the literal, already-known
|
||||
* `configDir` prefix instead of a generic "any absolute path" character
|
||||
* class. The prior version excluded whitespace from the match to avoid
|
||||
* swallowing a shell command's trailing args, which also truncated any
|
||||
* legitimate path containing a space (e.g. `/Users/John Doe/.claude`) —
|
||||
* `scanConfiguredEntrypoints` would then silently report zero checked
|
||||
* paths. Anchoring on `configDir` removes the ambiguity outright: a match
|
||||
* can only start where the known prefix literally occurs in the text, so
|
||||
* an interpreter path concatenated ahead of it (`"/usr/bin/node
|
||||
* /configDir/hooks/foo.js"`) is never swallowed either, and interior
|
||||
* whitespace inside `configDir` or the script's own path segments is safe
|
||||
* to allow. This still scans raw, unparsed config text on purpose (see
|
||||
* scanConfiguredEntrypoints's doc comment) — it catches a writer that
|
||||
* embeds a launch path without registering it, which a structured
|
||||
* JSON.parse of the expected schema would miss entirely.
|
||||
*
|
||||
* Windows configs store paths with backslashes, which JSON/TOML doubles on
|
||||
* write; collapsing `\\` to `\` first makes the raw text scan work on both
|
||||
* platforms without parsing each config format separately (POSIX text has no
|
||||
* backslashes, so the collapse is a no-op there).
|
||||
*
|
||||
* Every writer bakes `configDir` through the same posixNormalize seam
|
||||
* (src/runtime-hooks-surface.cts) before writing it into config text, on
|
||||
* every platform — so the anchor must match that projection, not the
|
||||
* OS-native `configDir` string this function receives.
|
||||
*/
|
||||
function configuredEntrypointsIn(text, configDir) {
|
||||
const normalizedPrefix = shellCmdProjection.posixNormalize(configDir).replace(/\/+$/, '') + '/';
|
||||
const scriptPathRe = new RegExp(`${escapeRegex(normalizedPrefix)}[^"']{0,400}?\\.(?:js|cjs|mjs|sh|cmd|ps1)`, 'g');
|
||||
const found = new Set();
|
||||
for (const match of text.replace(/\\\\/g, '\\').matchAll(scriptPathRe)) {
|
||||
found.add(path.resolve(match[0]));
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
/**
|
||||
* Throwaway HOME the Cycle 4 install for `runtime` runs against. Exported so a
|
||||
* test can seed that runtime's config before the install rather than
|
||||
* hard-coding the layout runSmoke picks.
|
||||
*/
|
||||
function entrypointFixtureHome(fixtureDir, runtime) {
|
||||
return path.join(fixtureDir, `entrypoints-${runtime}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-derive the configured entrypoints a completed install wrote into a
|
||||
* runtime's own config files and report the ones that do not resolve to a
|
||||
* file. Internal to Cycle 4; the smoke's verdict is the exported contract.
|
||||
*
|
||||
* This deliberately does NOT consult the installer's own entrypoint list (the
|
||||
* assertConfiguredEntrypoints gate in bin/install.js). That gate can only
|
||||
* validate paths a config writer remembered to register; reading the written
|
||||
* config back is what catches a writer that emits a launch path without
|
||||
* registering it, and a stale registration an install left behind.
|
||||
*
|
||||
* @param {string} configDir - Absolute path to the runtime config dir.
|
||||
* @returns {{ checked: string[], unresolved: { configPath: string, scriptPath: string }[] }}
|
||||
*/
|
||||
function scanConfiguredEntrypoints(configDir) {
|
||||
const checked = [];
|
||||
const unresolved = [];
|
||||
for (const name of RUNTIME_CONFIG_FILES) {
|
||||
const configPath = path.join(configDir, name);
|
||||
if (!fs.existsSync(configPath) || !fs.statSync(configPath).isFile()) continue;
|
||||
const text = fs.readFileSync(configPath, 'utf-8');
|
||||
for (const scriptPath of configuredEntrypointsIn(text, configDir)) {
|
||||
checked.push(scriptPath);
|
||||
if (fs.existsSync(scriptPath) && fs.statSync(scriptPath).isFile()) continue;
|
||||
unresolved.push({ configPath, scriptPath });
|
||||
}
|
||||
}
|
||||
return { checked, unresolved };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure function: runSmoke
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -285,6 +395,8 @@ function scanWorkflowColonLeak(filePath, cmdNames) {
|
||||
* @param {string} opts.expectedVersion - semver string to assert (e.g. "1.50.0")
|
||||
* @param {string} [opts.fixtureDir] - Temp dir to run `init` into (must NOT be HOME)
|
||||
* @param {string[]} [opts.lifecycleCommands] - Commands to file-check (default: see below)
|
||||
* @param {string[]} [opts.entrypointRuntimes] - Runtime profiles whose configured entrypoints are
|
||||
* re-checked after a real install (default: see below). Requires fixtureDir; pass [] to skip.
|
||||
* @param {boolean} [opts.dryRun=false] - If true, skip actual npm install; validate input only
|
||||
* @param {object} [opts.npmEnv] - Optional env dict for the internal npm install
|
||||
* spawnSync call. Pass an isolated HOME env (e.g. from isolatedNpmEnv() in tests/helpers.cjs)
|
||||
@@ -298,6 +410,11 @@ function runSmoke({
|
||||
expectedVersion,
|
||||
fixtureDir,
|
||||
lifecycleCommands = ['init', 'discuss-phase', 'plan-phase', 'execute-phase'],
|
||||
// claude and codex cover the two top-level config surfaces this scan knows
|
||||
// how to read (settings.json, and hooks.json + config.toml). Most other
|
||||
// runtimes reuse one of those two shapes; Cline and Kimi do not (see
|
||||
// RUNTIME_CONFIG_FILES), so they are out of scope here rather than covered.
|
||||
entrypointRuntimes = ['claude', 'codex'],
|
||||
dryRun = false,
|
||||
npmEnv = undefined,
|
||||
}) {
|
||||
@@ -551,6 +668,75 @@ function runSmoke({
|
||||
// NOTE: colonLeakCount is informational here. Once the backlog is fixed,
|
||||
// a future enforcement mode can fail on non-zero counts.
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Cycle 4: configured-entrypoint resolution (#4154)
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// The installer's own gate (assertConfiguredEntrypoints) runs in-process and
|
||||
// only sees the paths a config writer registered with it. Installing the
|
||||
// packed tarball for real and reading each runtime's written config back is
|
||||
// what proves the launch paths a user's runtime will actually invoke exist
|
||||
// in the shipped layout.
|
||||
const entrypointProfiles = [];
|
||||
if (fixtureDir && entrypointRuntimes.length > 0) {
|
||||
for (const runtime of entrypointRuntimes) {
|
||||
// Own HOME per runtime so a --global install cannot reach the real one.
|
||||
const runtimeHome = entrypointFixtureHome(fixtureDir, runtime);
|
||||
const configDir = path.join(runtimeHome, `.${runtime}`);
|
||||
fs.mkdirSync(runtimeHome, { recursive: true });
|
||||
|
||||
const installResult = spawnSync(
|
||||
process.execPath,
|
||||
[path.join(pkg, 'bin', 'install.js'), `--${runtime}`, '--global', '--config-dir', configDir],
|
||||
{
|
||||
encoding: 'utf-8',
|
||||
cwd: runtimeHome,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...effectiveNpmEnv,
|
||||
HOME: runtimeHome,
|
||||
USERPROFILE: runtimeHome,
|
||||
// Same reason as the init check above: install.js skips its main()
|
||||
// block when GSD_TEST_MODE is set and would exit 0 writing nothing.
|
||||
GSD_TEST_MODE: '',
|
||||
NO_UPDATE_NOTIFIER: '1',
|
||||
},
|
||||
timeout: CHILD_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
|
||||
if (installResult.status !== 0) {
|
||||
// #4249 (antigravity review): this is the Cycle 4 per-runtime install,
|
||||
// not Cycle 1's `gsd init` — SMOKE.INSTALL_FAILED is the code Cycle 2's
|
||||
// identical spawnSync-failure check already uses for the same failure
|
||||
// class; reusing SMOKE.INIT_FAILED here conflated the two lifecycle
|
||||
// stages in the reported code.
|
||||
return {
|
||||
code: SMOKE.INSTALL_FAILED,
|
||||
details: {
|
||||
...details,
|
||||
runtime,
|
||||
configDir,
|
||||
stderr: installResult.stderr,
|
||||
stdout: installResult.stdout,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const scan = scanConfiguredEntrypoints(configDir);
|
||||
if (scan.unresolved.length > 0) {
|
||||
return {
|
||||
code: SMOKE.ENTRYPOINT_UNRESOLVED,
|
||||
details: { ...details, runtime, configDir, unresolved: scan.unresolved },
|
||||
};
|
||||
}
|
||||
|
||||
entrypointProfiles.push({ runtime, configDir, entrypointsChecked: scan.checked.length });
|
||||
}
|
||||
}
|
||||
|
||||
details.entrypointProfiles = entrypointProfiles;
|
||||
|
||||
return { code: SMOKE.OK, details };
|
||||
}
|
||||
|
||||
@@ -635,7 +821,14 @@ function cleanup(...dirs) {
|
||||
// Exports
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
module.exports = { SMOKE, runSmoke, binInvocation, CHILD_TIMEOUT_MS };
|
||||
module.exports = {
|
||||
SMOKE,
|
||||
runSmoke,
|
||||
binInvocation,
|
||||
entrypointFixtureHome,
|
||||
CHILD_TIMEOUT_MS,
|
||||
configuredEntrypointsIn,
|
||||
};
|
||||
|
||||
if (require.main === module) {
|
||||
runMain(cliMain);
|
||||
|
||||
@@ -56,6 +56,7 @@ const {
|
||||
shellHookOmitsBashRunner,
|
||||
escapeTomlDoubleQuotedString,
|
||||
escapePosixDoubleQuoted,
|
||||
resolveExecutableBinary,
|
||||
} = shellCmdProjection as {
|
||||
isManagedHookBasename: (scriptPath: string, opts?: { surface?: string }) => boolean;
|
||||
isManagedHookCommand: (cmd: string | null | undefined, opts?: { surface?: string; includeLegacyAliases?: boolean; configDir?: string }) => boolean;
|
||||
@@ -66,6 +67,7 @@ const {
|
||||
shellHookOmitsBashRunner: (opts: { platform: string; runtime: string; isShellHook: boolean }) => boolean;
|
||||
escapeTomlDoubleQuotedString: (value: unknown) => string;
|
||||
escapePosixDoubleQuoted: (value: unknown) => string;
|
||||
resolveExecutableBinary: (name: string, opts?: { platform?: string; requireExecutable?: boolean }) => string | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -642,7 +644,7 @@ interface BashRunnerOpts {
|
||||
existsSync?: (p: string) => boolean;
|
||||
}
|
||||
|
||||
function resolveBashRunner(opts?: BashRunnerOpts): string | null {
|
||||
function resolveBashExecutable(opts?: BashRunnerOpts): string | null {
|
||||
const platform = (opts && opts.platform) || process.platform;
|
||||
if (platform !== 'win32') return 'bash';
|
||||
|
||||
@@ -658,13 +660,19 @@ function resolveBashRunner(opts?: BashRunnerOpts): string | null {
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate && exists(candidate)) {
|
||||
return JSON.stringify(shellCmdProjection.posixNormalize(candidate));
|
||||
}
|
||||
if (candidate && exists(candidate)) return shellCmdProjection.posixNormalize(candidate);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveBashRunner(opts?: BashRunnerOpts): string | null {
|
||||
const executable = resolveBashExecutable(opts);
|
||||
if (executable === null) return null;
|
||||
return ((opts && opts.platform) || process.platform) === 'win32'
|
||||
? JSON.stringify(executable)
|
||||
: executable;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared: rewriteLegacyManagedNodeHookCommands
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -929,6 +937,7 @@ interface ReconcileResult {
|
||||
changed: boolean;
|
||||
wrote: boolean;
|
||||
path: string;
|
||||
configuredEntrypoints?: ConfiguredEntrypoint[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1117,14 +1126,17 @@ interface ShimIR {
|
||||
render: { cmd: () => string };
|
||||
}
|
||||
|
||||
function parseAbsoluteRunnerToken(absoluteRunnerToken: string): string {
|
||||
try {
|
||||
return JSON.parse(absoluteRunnerToken) as string;
|
||||
} catch {
|
||||
return absoluteRunnerToken;
|
||||
}
|
||||
}
|
||||
|
||||
function buildCodexHookWindowsShimIR(scriptAbsPath: string, absoluteRunnerToken: string | null): ShimIR | null {
|
||||
if (!absoluteRunnerToken) return null;
|
||||
let interpreter: string;
|
||||
try {
|
||||
interpreter = JSON.parse(absoluteRunnerToken) as string;
|
||||
} catch {
|
||||
interpreter = absoluteRunnerToken;
|
||||
}
|
||||
const interpreter = parseAbsoluteRunnerToken(absoluteRunnerToken);
|
||||
const targetAbs = shellCmdProjection.posixNormalize(scriptAbsPath);
|
||||
const scriptQuoted = JSON.stringify(targetAbs);
|
||||
const cmdPath = scriptAbsPath.replace(/\.js$/, '.cmd');
|
||||
@@ -1159,8 +1171,9 @@ function ensureCodexHooksJsonSessionStart(targetDir: string, opts: EnsureCodexSe
|
||||
|
||||
const scriptPath = shellCmdProjection.posixNormalize(path.resolve(targetDir, 'hooks', 'gsd-check-update.js'));
|
||||
const cmdShimPath = scriptPath.replace(/\.js$/, '.cmd');
|
||||
|
||||
const configuredEntrypoints: ConfiguredEntrypoint[] = [];
|
||||
let managedCommand: string | undefined;
|
||||
|
||||
if (platform === 'win32') {
|
||||
const shimIR = buildCodexHookWindowsShimIR(scriptPath, absoluteRunner);
|
||||
if (!shimIR) return { changed: false, wrote: false, path: hooksJsonPath };
|
||||
@@ -1176,6 +1189,10 @@ function ensureCodexHooksJsonSessionStart(targetDir: string, opts: EnsureCodexSe
|
||||
return { changed: false, wrote: false, path: hooksJsonPath };
|
||||
}
|
||||
managedCommand = shimIR.hookCommand;
|
||||
configuredEntrypoints.push(
|
||||
{ runtime: 'codex', configPath: hooksJsonPath, scriptPath: shimIR.cmdPath, platform, selfExecutable: true },
|
||||
{ runtime: 'codex', configPath: hooksJsonPath, scriptPath, interpreterCandidates: [parseAbsoluteRunnerToken(absoluteRunner)], platform },
|
||||
);
|
||||
} else {
|
||||
managedCommand = projectManagedHookCommand({
|
||||
absoluteRunner,
|
||||
@@ -1183,15 +1200,23 @@ function ensureCodexHooksJsonSessionStart(targetDir: string, opts: EnsureCodexSe
|
||||
runtime: 'codex',
|
||||
platform,
|
||||
}) ?? undefined;
|
||||
if (managedCommand) {
|
||||
configuredEntrypoints.push({
|
||||
runtime: 'codex',
|
||||
configPath: hooksJsonPath,
|
||||
scriptPath,
|
||||
interpreterCandidates: [parseAbsoluteRunnerToken(absoluteRunner)],
|
||||
platform,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!managedCommand) return { changed: false, wrote: false, path: hooksJsonPath };
|
||||
|
||||
const commandWindows = platform === 'win32'
|
||||
? JSON.stringify(shellCmdProjection.posixNormalize(cmdShimPath))
|
||||
: undefined;
|
||||
|
||||
return reconcileCodexHooksJsonSessionStart(targetDir, { managedCommand, commandWindows });
|
||||
const result = reconcileCodexHooksJsonSessionStart(targetDir, { managedCommand, commandWindows });
|
||||
return { ...result, configuredEntrypoints };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1397,7 +1422,77 @@ interface BuildHookCommandOpts {
|
||||
runtime?: string;
|
||||
hookShell?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
execPath?: string;
|
||||
existsSync?: (p: string) => boolean;
|
||||
configPath?: string;
|
||||
configuredEntrypoints?: ConfiguredEntrypoint[];
|
||||
}
|
||||
|
||||
function configuredEntrypointsForHook(
|
||||
configDir: string,
|
||||
hookName: string,
|
||||
opts: BuildHookCommandOpts,
|
||||
): ConfiguredEntrypoint[] {
|
||||
const platform = opts.platform || process.platform;
|
||||
const runtime = opts.runtime || 'generic';
|
||||
const configPath = opts.configPath || configDir;
|
||||
const target: ConfiguredEntrypoint = {
|
||||
runtime,
|
||||
configPath,
|
||||
scriptPath: path.join(configDir, 'hooks', hookName),
|
||||
platform,
|
||||
};
|
||||
const isShellHook = hookName.endsWith('.sh');
|
||||
|
||||
if (shellHookOmitsBashRunner({ platform, runtime, isShellHook })) return [{ ...target, selfExecutable: true }];
|
||||
|
||||
const bash = resolveBashExecutable(opts);
|
||||
if (isShellHook) {
|
||||
// An unresolved bash must still surface as an interpreterCandidates entry
|
||||
// (the literal token, same as the portableHooks runner below) so
|
||||
// validateConfiguredEntrypoints reports 'unresolved-interpreter' instead
|
||||
// of silently skipping the check because the field is absent.
|
||||
return [{ ...target, interpreterCandidates: [bash === null ? 'bash' : bash] }];
|
||||
}
|
||||
|
||||
// #4249: check the SAME stable alias buildNodeRunnerChainToken bakes as its
|
||||
// first candidate (normalizeNodePath rewrites a version-manager shim like
|
||||
// fnm/nvm/mise/volta into its persistent path), not the raw, currently-
|
||||
// running process.execPath — which always trivially resolves regardless of
|
||||
// whether the alias actually baked into the persisted command still does.
|
||||
const nodeCandidates = [
|
||||
normalizeNodePath(opts.execPath || process.execPath, opts),
|
||||
'node',
|
||||
'/usr/local/bin/node',
|
||||
'/usr/bin/node',
|
||||
].filter((candidate): candidate is string => Boolean(candidate));
|
||||
|
||||
if (!opts.portableHooks) {
|
||||
return [{ ...target, interpreterCandidates: nodeCandidates }];
|
||||
}
|
||||
|
||||
const runner: ConfiguredEntrypoint = {
|
||||
runtime,
|
||||
configPath,
|
||||
scriptPath: path.join(configDir, 'hooks', NODE_RUNNER_RESOLVER_HOOK),
|
||||
interpreterCandidates: bash === null ? ['bash'] : [bash],
|
||||
platform,
|
||||
};
|
||||
return [runner, { ...target, interpreterCandidates: nodeCandidates }];
|
||||
}
|
||||
|
||||
function recordConfiguredHookCommand(
|
||||
command: string | null,
|
||||
configDir: string,
|
||||
hookName: string,
|
||||
opts: BuildHookCommandOpts,
|
||||
): string | null {
|
||||
if (command && opts.configuredEntrypoints) {
|
||||
opts.configuredEntrypoints.push(
|
||||
...configuredEntrypointsForHook(configDir, hookName, opts).map(entry => ({ ...entry, command })),
|
||||
);
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookCommandOpts): string | null {
|
||||
@@ -1406,6 +1501,8 @@ function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookC
|
||||
const runtime = opts.runtime || 'generic';
|
||||
const hookShell = opts.hookShell;
|
||||
const isShellHook = hookName.endsWith('.sh');
|
||||
const track = (command: string | null): string | null =>
|
||||
recordConfiguredHookCommand(command, configDir, hookName, opts);
|
||||
|
||||
if (shellHookOmitsBashRunner({ platform, runtime, isShellHook })) {
|
||||
if (opts.portableHooks) {
|
||||
@@ -1413,9 +1510,9 @@ function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookC
|
||||
configDir,
|
||||
homeDir: os.homedir(),
|
||||
});
|
||||
return JSON.stringify(`${portableBaseDir}/hooks/${hookName}`);
|
||||
return track(JSON.stringify(`${portableBaseDir}/hooks/${hookName}`));
|
||||
}
|
||||
return JSON.stringify(shellCmdProjection.posixNormalize(configDir) + '/hooks/' + hookName);
|
||||
return track(JSON.stringify(shellCmdProjection.posixNormalize(configDir) + '/hooks/' + hookName));
|
||||
}
|
||||
|
||||
// .sh hooks keep the pre-#3662 shape everywhere: the bash runner resolves
|
||||
@@ -1423,30 +1520,42 @@ function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookC
|
||||
// (the absolute Git-Bash discovery covers win32 — #580/#3393).
|
||||
if (isShellHook) {
|
||||
const runner = resolveBashRunner(opts);
|
||||
if (runner === null) return null;
|
||||
if (runner === null) {
|
||||
// #4249 (antigravity review): this early return skips `track()` below,
|
||||
// so an unresolved bash on win32 (no Git Bash found) previously left
|
||||
// this hook silently unregistered with nothing for
|
||||
// validateConfiguredEntrypoints to reject — configuredEntrypointsForHook's
|
||||
// own 'unresolved bash must still surface' comment describes intent this
|
||||
// return never reached. Push the entry directly (no `command`, since
|
||||
// none was ever built) so the gate actually sees it.
|
||||
if (opts.configuredEntrypoints) {
|
||||
opts.configuredEntrypoints.push(...configuredEntrypointsForHook(configDir, hookName, opts));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (opts.portableHooks) {
|
||||
const portableBaseDir = projectPortableHookBaseDir({
|
||||
configDir,
|
||||
homeDir: os.homedir(),
|
||||
});
|
||||
return projectManagedHookCommand({
|
||||
return track(projectManagedHookCommand({
|
||||
absoluteRunner: runner,
|
||||
scriptPath: `${portableBaseDir}/hooks/${hookName}`,
|
||||
runtime: opts.runtime || 'generic',
|
||||
platform,
|
||||
hookShell,
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
const hooksPath = shellCmdProjection.posixNormalize(configDir) + '/hooks/' + hookName;
|
||||
return projectManagedHookCommand({
|
||||
return track(projectManagedHookCommand({
|
||||
absoluteRunner: runner,
|
||||
scriptPath: hooksPath,
|
||||
runtime,
|
||||
platform,
|
||||
hookShell,
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
// JS hooks (#3662): the node runner is resolved at hook-fire time, never
|
||||
@@ -1470,7 +1579,7 @@ function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookC
|
||||
// Absolute Git-Bash discovery on win32 when available (#580); `bash` on
|
||||
// PATH otherwise — the same assumption .sh hooks already make.
|
||||
const resolverRunner = resolveBashRunner(opts) || 'bash';
|
||||
return shellCmdProjection.projectShellCommandText({
|
||||
return track(shellCmdProjection.projectShellCommandText({
|
||||
runnerToken: resolverRunner,
|
||||
argTokens: [
|
||||
JSON.stringify(`${portableBaseDir}/hooks/${NODE_RUNNER_RESOLVER_HOOK}`),
|
||||
@@ -1480,19 +1589,19 @@ function buildHookCommand(configDir: string, hookName: string, opts?: BuildHookC
|
||||
runtime,
|
||||
platform,
|
||||
hookShell,
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
const chainRunner = buildNodeRunnerChainToken(opts);
|
||||
if (chainRunner === null) return null;
|
||||
const hooksPath = shellCmdProjection.posixNormalize(configDir) + '/hooks/' + hookName;
|
||||
return shellCmdProjection.projectShellCommandText({
|
||||
return track(shellCmdProjection.projectShellCommandText({
|
||||
runnerToken: chainRunner,
|
||||
argTokens: [JSON.stringify(hooksPath)],
|
||||
runtime,
|
||||
platform,
|
||||
hookShell,
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1600,8 +1709,9 @@ function mergeGsdAgentsMd(filePath: string, gsdContent: string): void {
|
||||
// writeClineArtifacts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function writeClineArtifacts(targetDir: string, isGlobalInstall: boolean): string[] {
|
||||
function writeClineArtifacts(targetDir: string, isGlobalInstall: boolean): { written: string[]; configuredEntrypoints: ConfiguredEntrypoint[] } {
|
||||
const written: string[] = [];
|
||||
const configuredEntrypoints: ConfiguredEntrypoint[] = [];
|
||||
const clinerulesDir = path.join(targetDir, '.clinerules');
|
||||
|
||||
try {
|
||||
@@ -1626,6 +1736,20 @@ function writeClineArtifacts(targetDir: string, isGlobalInstall: boolean): strin
|
||||
try { fs.chmodSync(hookPath, 0o755); } catch { /* Windows: hooks unsupported anyway */ }
|
||||
written.push('.clinerules/hooks/PreToolUse');
|
||||
console.log(` ${green}✓${reset} Wrote .clinerules/hooks/PreToolUse`);
|
||||
// #4249 (CodeRabbit): Cline invokes this file directly via its own
|
||||
// `#!/usr/bin/env node` shebang — a hybrid case. The script itself still
|
||||
// needs the execute bit (selfExecutable), but unlike GSD's other JS hooks
|
||||
// (which bake an absolute, install-time-resolved node path specifically to
|
||||
// avoid this) its interpreter is looked up on PATH by `env` at hook-fire
|
||||
// time, so `node` must also resolve or the hook can never run.
|
||||
configuredEntrypoints.push({
|
||||
runtime: 'cline',
|
||||
configPath: hookPath,
|
||||
scriptPath: hookPath,
|
||||
interpreterCandidates: ['node'],
|
||||
selfExecutable: true,
|
||||
platform: process.platform,
|
||||
});
|
||||
|
||||
if (isGlobalInstall) {
|
||||
try {
|
||||
@@ -1637,7 +1761,7 @@ function writeClineArtifacts(targetDir: string, isGlobalInstall: boolean): strin
|
||||
}
|
||||
}
|
||||
|
||||
return written;
|
||||
return { written, configuredEntrypoints };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1856,7 +1980,7 @@ function stageTransitiveHookLibs(opts: {
|
||||
return staged;
|
||||
}
|
||||
|
||||
function writeCursorHooksJson(targetDir: string, src: string, opts?: WriteCursorHooksJsonOpts): { hooksJsonPath: string; changed: boolean } {
|
||||
function writeCursorHooksJson(targetDir: string, src: string, opts?: WriteCursorHooksJsonOpts): { hooksJsonPath: string; changed: boolean; configuredEntrypoints: ConfiguredEntrypoint[] } {
|
||||
opts = opts || {};
|
||||
const hooksDir = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDir, { recursive: true });
|
||||
@@ -1915,7 +2039,13 @@ function writeCursorHooksJson(targetDir: string, src: string, opts?: WriteCursor
|
||||
ensureCommonJsMarker(hooksDir);
|
||||
}
|
||||
|
||||
const hookOpts: BuildHookCommandOpts = { runtime: 'cursor', platform: opts.platform || process.platform };
|
||||
const configuredEntrypoints: ConfiguredEntrypoint[] = [];
|
||||
const hookOpts: BuildHookCommandOpts = {
|
||||
runtime: 'cursor',
|
||||
platform: opts.platform || process.platform,
|
||||
configPath: path.join(targetDir, 'hooks.json'),
|
||||
configuredEntrypoints,
|
||||
};
|
||||
const commands: Record<string, string | null> = {};
|
||||
for (const ev of events) {
|
||||
const script = CURSOR_EVENT_SCRIPT_MAP[ev];
|
||||
@@ -1929,7 +2059,7 @@ function writeCursorHooksJson(targetDir: string, src: string, opts?: WriteCursor
|
||||
|
||||
const hooksJsonPath = path.join(targetDir, 'hooks.json');
|
||||
const result = reconcileCursorHooksJson(hooksJsonPath, managedEntries);
|
||||
return { hooksJsonPath, changed: result.changed };
|
||||
return { hooksJsonPath, changed: result.changed, configuredEntrypoints };
|
||||
}
|
||||
|
||||
function removeCursorHooksJson(targetDir: string): { changed: boolean } {
|
||||
@@ -2102,7 +2232,7 @@ interface WriteWindsurfHooksJsonOpts {
|
||||
* @param opts - `{ platform? }`
|
||||
* @returns `{ hooksJsonPath, changed }`
|
||||
*/
|
||||
function writeWindsurfHooksJson(targetDir: string, src: string, opts?: WriteWindsurfHooksJsonOpts): { hooksJsonPath: string; changed: boolean } {
|
||||
function writeWindsurfHooksJson(targetDir: string, src: string, opts?: WriteWindsurfHooksJsonOpts): { hooksJsonPath: string; changed: boolean; configuredEntrypoints: ConfiguredEntrypoint[] } {
|
||||
opts = opts || {};
|
||||
const hooksDir = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDir, { recursive: true });
|
||||
@@ -2154,7 +2284,13 @@ function writeWindsurfHooksJson(targetDir: string, src: string, opts?: WriteWind
|
||||
ensureCommonJsMarker(hooksDir);
|
||||
}
|
||||
|
||||
const hookOpts: BuildHookCommandOpts = { runtime: 'windsurf', platform: opts.platform || process.platform };
|
||||
const configuredEntrypoints: ConfiguredEntrypoint[] = [];
|
||||
const hookOpts: BuildHookCommandOpts = {
|
||||
runtime: 'windsurf',
|
||||
platform: opts.platform || process.platform,
|
||||
configPath: path.join(targetDir, 'hooks.json'),
|
||||
configuredEntrypoints,
|
||||
};
|
||||
const commands: Record<string, string | null> = {};
|
||||
for (const ev of WINDSURF_HOOK_EVENTS) {
|
||||
const script = WINDSURF_EVENT_SCRIPT_MAP[ev];
|
||||
@@ -2169,7 +2305,7 @@ function writeWindsurfHooksJson(targetDir: string, src: string, opts?: WriteWind
|
||||
|
||||
const hooksJsonPath = path.join(targetDir, 'hooks.json');
|
||||
const result = reconcileWindsurfHooksJson(hooksJsonPath, managedEntries);
|
||||
return { hooksJsonPath, changed: result.changed };
|
||||
return { hooksJsonPath, changed: result.changed, configuredEntrypoints };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3150,30 +3286,38 @@ function writeKimiHooksToml(
|
||||
configPath: string,
|
||||
targetDir: string,
|
||||
opts: { hookOpts: BuildHookCommandOpts },
|
||||
): { changed: boolean; path: string; entryCount: number } {
|
||||
): { changed: boolean; path: string; entryCount: number; configuredEntrypoints: ConfiguredEntrypoint[] } {
|
||||
const configuredEntrypoints: ConfiguredEntrypoint[] = [];
|
||||
const trackedOpts = {
|
||||
hookOpts: {
|
||||
...opts.hookOpts,
|
||||
configPath,
|
||||
configuredEntrypoints,
|
||||
},
|
||||
};
|
||||
const existing = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
|
||||
const stripped = stripKimiHooksTomlBlock(existing) ?? '';
|
||||
const block = buildKimiHooksTomlBlock(targetDir, opts);
|
||||
const block = buildKimiHooksTomlBlock(targetDir, trackedOpts);
|
||||
const entryCount = block ? (block.match(/\[\[hooks\]\]/g) || []).length : 0;
|
||||
|
||||
if (!block) {
|
||||
if (stripped === existing) return { changed: false, path: configPath, entryCount: 0 };
|
||||
if (stripped === existing) return { changed: false, path: configPath, entryCount: 0, configuredEntrypoints };
|
||||
if (stripped.trim() === '') {
|
||||
if (fs.existsSync(configPath)) fs.unlinkSync(configPath);
|
||||
} else {
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
||||
atomicWriteFileSync(configPath, stripped, 'utf8');
|
||||
}
|
||||
return { changed: true, path: configPath, entryCount: 0 };
|
||||
return { changed: true, path: configPath, entryCount: 0, configuredEntrypoints };
|
||||
}
|
||||
|
||||
const separator = stripped.trim() === '' ? '' : (stripped.endsWith('\n') ? '\n' : '\n\n');
|
||||
const next = stripped.trim() === '' ? `${block}\n` : `${stripped}${separator}${block}\n`;
|
||||
if (next === existing) return { changed: false, path: configPath, entryCount };
|
||||
if (next === existing) return { changed: false, path: configPath, entryCount, configuredEntrypoints };
|
||||
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
||||
atomicWriteFileSync(configPath, next, 'utf8');
|
||||
return { changed: true, path: configPath, entryCount };
|
||||
return { changed: true, path: configPath, entryCount, configuredEntrypoints };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3220,6 +3364,101 @@ function referencesHook(h: Record<string, unknown>, hookName: string): boolean {
|
||||
(typeof url === 'string' && url.includes(hookName));
|
||||
}
|
||||
|
||||
type ConfiguredEntrypointFailureReason = 'missing' | 'unreadable' | 'wrong-file-type' | 'unresolved-interpreter' | 'not-executable';
|
||||
|
||||
interface ConfiguredEntrypoint {
|
||||
runtime: string;
|
||||
configPath: string;
|
||||
scriptPath: string;
|
||||
interpreterCandidates?: string[];
|
||||
// #4249 (CodeRabbit): true when the OS execs scriptPath directly (via a
|
||||
// shebang, or Windows' own .cmd extension dispatch) — orthogonal to
|
||||
// interpreterCandidates, which every producer that needs both sets
|
||||
// alongside this rather than relying on their absence. Most self-executable
|
||||
// entries have no candidates (a Windows-Claude .sh hook, Codex's .cmd shim);
|
||||
// Cline's `#!/usr/bin/env node` is a hybrid needing both: the execute bit
|
||||
// AND `node` resolving on PATH.
|
||||
selfExecutable?: boolean;
|
||||
platform?: string;
|
||||
command?: string;
|
||||
}
|
||||
|
||||
interface ConfiguredEntrypointInvalid {
|
||||
runtime: string;
|
||||
configPath: string;
|
||||
role: 'script' | 'interpreter';
|
||||
path: string;
|
||||
reason: ConfiguredEntrypointFailureReason;
|
||||
}
|
||||
|
||||
type ConfiguredEntrypointValidationResult =
|
||||
| { ok: true }
|
||||
| { ok: false; invalid: ConfiguredEntrypointInvalid[] };
|
||||
|
||||
function validateConfiguredEntrypoints(
|
||||
entries: ConfiguredEntrypoint[],
|
||||
deps: { statSync?: typeof fs.statSync; accessSync?: typeof fs.accessSync; resolveExecutableBinary?: typeof resolveExecutableBinary } = {},
|
||||
): ConfiguredEntrypointValidationResult {
|
||||
const statSync = deps.statSync ?? fs.statSync;
|
||||
const accessSync = deps.accessSync ?? fs.accessSync;
|
||||
const resolve = deps.resolveExecutableBinary ?? resolveExecutableBinary;
|
||||
const invalid: ConfiguredEntrypointInvalid[] = [];
|
||||
for (const entry of entries) {
|
||||
let scriptOk = false;
|
||||
try {
|
||||
scriptOk = statSync(entry.scriptPath).isFile();
|
||||
if (!scriptOk) {
|
||||
invalid.push({ runtime: entry.runtime, configPath: entry.configPath, role: 'script', path: entry.scriptPath, reason: 'wrong-file-type' });
|
||||
} else {
|
||||
// #4249: statSync only needs search permission on the parent dirs, so
|
||||
// it succeeds even for a chmod-000 file — the EACCES catch below
|
||||
// never fires for that case. Read permission on the file itself must
|
||||
// be checked explicitly: an interpreter opens the script directly,
|
||||
// and even a self-executable shebang script is opened and read by
|
||||
// its kernel-invoked interpreter, not just exec'd — X_OK alone does
|
||||
// not prove it's readable.
|
||||
try {
|
||||
accessSync(entry.scriptPath, fs.constants.R_OK);
|
||||
} catch {
|
||||
scriptOk = false;
|
||||
invalid.push({ runtime: entry.runtime, configPath: entry.configPath, role: 'script', path: entry.scriptPath, reason: 'unreadable' });
|
||||
}
|
||||
}
|
||||
} catch (statErr) {
|
||||
// #4249 Nit: EACCES means a parent directory couldn't be searched —
|
||||
// a real (if rare) permission problem, distinct from ENOENT's "missing".
|
||||
// EPERM: Windows' equivalent permission-denied code for a directory a
|
||||
// parent path couldn't be traversed into.
|
||||
const code = (statErr as NodeJS.ErrnoException)?.code;
|
||||
const reason = code === 'EACCES' || code === 'EPERM' ? 'unreadable' : 'missing';
|
||||
invalid.push({ runtime: entry.runtime, configPath: entry.configPath, role: 'script', path: entry.scriptPath, reason });
|
||||
}
|
||||
// #4249: selfExecutable is the sole source of truth for whether the OS
|
||||
// execs scriptPath directly via its own shebang (set explicitly by every
|
||||
// producer that needs it — a Windows-Claude .sh hook, Codex's Windows
|
||||
// .cmd shim, Cline's hybrid `env node` hook — rather than inferred from
|
||||
// the absence of interpreterCandidates, which Cline's hybrid case also
|
||||
// carries). Skip on win32 like resolveExecutableBinary's own X_OK
|
||||
// carve-out does: POSIX mode bits don't mean executable on Windows, and a
|
||||
// real accessSync(X_OK) there would fail a .cmd shim under a test that
|
||||
// simulates win32 on a POSIX runner (Node's own no-op only protects an
|
||||
// actual Windows machine). Cline is the only producer where this runs.
|
||||
if (scriptOk && entry.selfExecutable && (entry.platform ?? process.platform) !== 'win32') {
|
||||
try {
|
||||
accessSync(entry.scriptPath, fs.constants.X_OK);
|
||||
} catch {
|
||||
invalid.push({ runtime: entry.runtime, configPath: entry.configPath, role: 'script', path: entry.scriptPath, reason: 'not-executable' });
|
||||
}
|
||||
}
|
||||
if (entry.interpreterCandidates && !entry.interpreterCandidates.some(candidate =>
|
||||
resolve(candidate, { platform: entry.platform, requireExecutable: true }) !== null,
|
||||
)) {
|
||||
invalid.push({ runtime: entry.runtime, configPath: entry.configPath, role: 'interpreter', path: entry.interpreterCandidates.join(' | '), reason: 'unresolved-interpreter' });
|
||||
}
|
||||
}
|
||||
return invalid.length === 0 ? { ok: true } : { ok: false, invalid };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exports
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3295,7 +3534,9 @@ export = {
|
||||
// Shared
|
||||
stageTransitiveHookLibs,
|
||||
buildHookCommand,
|
||||
recordConfiguredHookCommand,
|
||||
applySettingsJsonHooks,
|
||||
validateConfiguredEntrypoints,
|
||||
referencesHook,
|
||||
rewriteLegacyManagedNodeHookCommands,
|
||||
reconcileManagedShellHookCommands,
|
||||
|
||||
@@ -249,6 +249,7 @@ const MANAGED_HOOK_COMMAND_BASENAMES_BY_SURFACE: Record<string, Set<string>> = {
|
||||
'gsd-session-state.sh',
|
||||
'gsd-validate-commit.sh',
|
||||
'gsd-phase-boundary.sh',
|
||||
'gsd-graphify-update.sh',
|
||||
// #3662: same three guards as MANAGED_HOOK_BASENAMES_BY_SURFACE above —
|
||||
// their absence here meant isManagedHookCommand never recognized them, so
|
||||
// the settings.json→settings.local.json migration filter (and uninstall
|
||||
|
||||
@@ -2361,6 +2361,95 @@ describe('#3245 — idempotent rollback reverts skills/, agents/, and VERSION',
|
||||
});
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// #4249 — install() exposes the full snapshot restore, not just migrations rollback
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
{
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const os = require('os');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
const previousGsdTestMode = process.env.GSD_TEST_MODE;
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
const { install } = require('../bin/install.js');
|
||||
if (previousGsdTestMode === undefined) {
|
||||
delete process.env.GSD_TEST_MODE;
|
||||
} else {
|
||||
process.env.GSD_TEST_MODE = previousGsdTestMode;
|
||||
}
|
||||
|
||||
// concurrency: false — drives the real install pipeline like the block above.
|
||||
describe('#4249 — install() exposes the full snapshot restore, not just migrations rollback', { concurrency: false }, () => {
|
||||
let tmpDir;
|
||||
let codexHome;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4249-codex-rollback-'));
|
||||
codexHome = path.join(tmpDir, 'codex-home');
|
||||
fs.mkdirSync(codexHome, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(tmpDir));
|
||||
|
||||
test('result.rollbackPreInstallSnapshot() reverts skills/, agents/, and VERSION', () => {
|
||||
// Skills resolve $HOME-relative independent of CODEX_HOME (#2088), so the
|
||||
// rollback closure must run before this sandboxing is torn down — inline
|
||||
// runCodexInstall's env dance instead of using the auto-restoring helper,
|
||||
// matching how installAllRuntimes' real aggregate gate calls it: in the
|
||||
// same process env install() itself ran in, never after it's restored.
|
||||
const previousHome = process.env.HOME;
|
||||
const previousUserProfile = process.env.USERPROFILE;
|
||||
const previousCodexHome = process.env.CODEX_HOME;
|
||||
const previousCwd = process.cwd();
|
||||
process.env.HOME = codexHome;
|
||||
process.env.USERPROFILE = codexHome;
|
||||
process.env.CODEX_HOME = codexHome;
|
||||
process.chdir(path.join(__dirname, '..'));
|
||||
try {
|
||||
const result = install(true, 'codex');
|
||||
|
||||
// A configured-entrypoint validation failure discovered outside install()
|
||||
// (installAllRuntimes' aggregate assertConfiguredEntrypoints, run after
|
||||
// this function already returned) reaches for this field. Before #4249
|
||||
// the only rollback Codex exposed was rollbackInstallerMigrations, which
|
||||
// reverts installer-migration state only and leaves the skills/agents/
|
||||
// VERSION this successful install just wrote untouched.
|
||||
result.rollbackPreInstallSnapshot();
|
||||
|
||||
const skillsDir = codexSkillsRoot(codexHome);
|
||||
const gsdSkills = fs.existsSync(skillsDir)
|
||||
? fs.readdirSync(skillsDir, { withFileTypes: true }).filter(e => e.isDirectory() && e.name.startsWith('gsd-'))
|
||||
: [];
|
||||
assert.strictEqual(gsdSkills.length, 0, 'rollback must remove all gsd-* skill directories: ' + gsdSkills.map(e => e.name).join(', '));
|
||||
|
||||
const versionPath = path.join(codexHome, 'gsd-core', 'VERSION');
|
||||
assert.strictEqual(fs.existsSync(versionPath), false, 'rollback must remove gsd-core/VERSION');
|
||||
|
||||
// #4249 (agy adversarial review): the whole point of this describe block
|
||||
// is that rollback covers the full pre-install snapshot, not just
|
||||
// installer migrations — config.toml/hooks.json must revert too. Both
|
||||
// were absent before this fresh install, so rollback must remove them.
|
||||
assert.strictEqual(
|
||||
fs.existsSync(path.join(codexHome, 'config.toml')),
|
||||
false,
|
||||
'rollback must remove config.toml (absent before this fresh install)'
|
||||
);
|
||||
assert.strictEqual(
|
||||
fs.existsSync(path.join(codexHome, 'hooks.json')),
|
||||
false,
|
||||
'rollback must remove hooks.json (absent before this fresh install)'
|
||||
);
|
||||
} finally {
|
||||
process.chdir(previousCwd);
|
||||
if (previousHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = previousHome;
|
||||
if (previousUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = previousUserProfile;
|
||||
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = previousCodexHome;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// Folded from tests/bug-3285-codex-hooks-state-allowed.test.cjs — consolidation epic #1969 (B1 #1970)
|
||||
|
||||
558
tests/configured-entrypoint-validation.test.cjs
Normal file
558
tests/configured-entrypoint-validation.test.cjs
Normal file
@@ -0,0 +1,558 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const test = require('node:test');
|
||||
|
||||
const helpers = require('./helpers.cjs');
|
||||
|
||||
const hooksSurface = require('../gsd-core/bin/lib/runtime-hooks-surface.cjs');
|
||||
const { install, installAllRuntimes, finishInstall } = require('../bin/install.js');
|
||||
|
||||
/**
|
||||
* Run `fn` with HOME/USERPROFILE pointed at a fresh temp dir and every
|
||||
* config-location env var scrubbed, so a real install() never touches the
|
||||
* developer's own config. Restores all of it, and cleans the dir, afterwards.
|
||||
*/
|
||||
function withSandboxedHome(t, prefix, fn) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const savedHome = process.env.HOME;
|
||||
const savedUserProfile = process.env.USERPROFILE;
|
||||
process.env.HOME = root;
|
||||
process.env.USERPROFILE = root;
|
||||
const restoreConfigLocationEnv = helpers.scrubConfigLocationEnv();
|
||||
try {
|
||||
return fn(root);
|
||||
} finally {
|
||||
if (savedHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = savedHome;
|
||||
if (savedUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = savedUserProfile;
|
||||
restoreConfigLocationEnv();
|
||||
}
|
||||
}
|
||||
|
||||
test('configured entrypoint validation exposes an aggregate typed boundary', () => {
|
||||
assert.equal(
|
||||
typeof hooksSurface.validateConfiguredEntrypoints,
|
||||
'function',
|
||||
'the Runtime Hooks Surface must export configured-entrypoint validation',
|
||||
);
|
||||
});
|
||||
|
||||
test('finishInstall rejects an invalid configured entrypoint before Done output', (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-finish-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const logs = [];
|
||||
const originalLog = console.log;
|
||||
console.log = (...args) => logs.push(args.join(' '));
|
||||
// #2665/#4249: finishInstall asserts configured entrypoints before any of its
|
||||
// own writes now, but still sandbox HOME (+ USERPROFILE for os.homedir() on
|
||||
// Windows) and config-location env defensively, so a future reordering that
|
||||
// reintroduces a pre-assertion write can never redirect it to a live config dir.
|
||||
const savedHome = process.env.HOME;
|
||||
const savedUserProfile = process.env.USERPROFILE;
|
||||
process.env.HOME = root;
|
||||
process.env.USERPROFILE = root;
|
||||
const restoreConfigLocationEnv = helpers.scrubConfigLocationEnv();
|
||||
try {
|
||||
assert.throws(() => finishInstall(null, null, null, false, 'cline', false, root, {
|
||||
configuredEntrypoints: [{ runtime: 'cline', configPath: path.join(root, 'config'), scriptPath: path.join(root, 'missing.js') }],
|
||||
}), /Configured entrypoint validation failed/);
|
||||
// #4249 review, Major: the message must name the actual consequence for
|
||||
// the failing runtime, not just that something failed — Cline has no
|
||||
// revert path, so its entry must be flagged "NOT reverted".
|
||||
assert.throws(() => finishInstall(null, null, null, false, 'cline', false, root, {
|
||||
configuredEntrypoints: [{ runtime: 'cline', configPath: path.join(root, 'config'), scriptPath: path.join(root, 'missing.js') }],
|
||||
}), /NOT reverted/);
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
restoreConfigLocationEnv();
|
||||
if (savedHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = savedHome;
|
||||
if (savedUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = savedUserProfile;
|
||||
}
|
||||
assert.equal(logs.some(line => line.includes('Done!')), false);
|
||||
});
|
||||
|
||||
test('a hook already registered under a stale command is still tracked for validation on re-install (#4154 Blocker)', (t) => {
|
||||
withSandboxedHome(t, 'configured-entrypoint-stale-', () => {
|
||||
const first = install(true, 'claude');
|
||||
assert.ok(first.settingsPath, 'a fresh global install must produce a settings path');
|
||||
finishInstall(first.settingsPath, first.settings, first.statuslineCommand, false, 'claude', true, first.configDir, {
|
||||
configuredEntrypoints: first.configuredEntrypoints,
|
||||
});
|
||||
|
||||
// Simulate an entry registered by an older installer under a DIFFERENT
|
||||
// node install (e.g. an nvm switch, #4087/#4098/#4137): same real
|
||||
// scriptPath under <configDir>/hooks/ (that never changes across
|
||||
// installer versions) and still shaped as the modern runtime-resolving
|
||||
// chain (rewriteLegacyManagedNodeHookCommands deliberately never touches
|
||||
// an already-current-format entry — #3662), but baked with a node path
|
||||
// this install would never produce. `hasGsdUpdateHook` still finds it and
|
||||
// applySettingsJsonHooks takes its register-only-if-absent branch on the
|
||||
// next install (never rewriting it).
|
||||
const onDisk = JSON.parse(fs.readFileSync(first.settingsPath, 'utf8'));
|
||||
const staleEntry = (onDisk.hooks.SessionStart || []).find(entry =>
|
||||
entry.hooks && entry.hooks.some(h => h.command && h.command.includes('gsd-check-update.js'))
|
||||
);
|
||||
assert.ok(staleEntry, 'a fresh install must register the check-update hook');
|
||||
const staleCommand = hooksSurface.buildHookCommand(first.configDir, 'gsd-check-update.js', {
|
||||
execPath: '/old/nvm/pinned/node',
|
||||
platform: process.platform,
|
||||
runtime: 'claude',
|
||||
});
|
||||
for (const h of staleEntry.hooks) {
|
||||
if (h.command && h.command.includes('gsd-check-update.js')) {
|
||||
h.command = staleCommand;
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(first.settingsPath, JSON.stringify(onDisk, null, 2));
|
||||
|
||||
const second = install(true, 'claude');
|
||||
const trackedNames = (second.configuredEntrypoints || []).map(entry => path.basename(entry.scriptPath));
|
||||
assert.ok(
|
||||
trackedNames.includes('gsd-check-update.js'),
|
||||
`a hook already registered under a stale command must still be tracked for validation, got: ${trackedNames.join(', ')}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('configured entrypoint validation aggregates file and interpreter failures without execution', (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const directory = path.join(root, 'directory');
|
||||
fs.mkdirSync(directory);
|
||||
|
||||
const unreadablePath = path.join(root, 'unreadable.js');
|
||||
const notExecutablePath = path.join(root, 'not-executable.js');
|
||||
|
||||
const result = hooksSurface.validateConfiguredEntrypoints([
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath: path.join(root, 'missing.js') },
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath: directory },
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath: __filename, interpreterCandidates: ['missing-node'] },
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath: unreadablePath },
|
||||
// #4249: selfExecutable means this entry is invoked directly via its own
|
||||
// shebang (e.g. a Windows-Claude .sh hook) — must itself be +x.
|
||||
// platform pinned to non-win32: the X_OK check itself is a POSIX-only
|
||||
// concept (skipped entirely on win32, matching production) — this case
|
||||
// must exercise it deterministically regardless of which OS runs the test.
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath: notExecutablePath, selfExecutable: true, platform: 'linux' },
|
||||
], {
|
||||
resolveExecutableBinary: () => null,
|
||||
statSync: (p) => {
|
||||
if (p === unreadablePath) {
|
||||
const err = new Error('EACCES: permission denied');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
return fs.statSync(p === notExecutablePath ? __filename : p);
|
||||
},
|
||||
accessSync: (p, mode) => {
|
||||
if (p === notExecutablePath && mode === fs.constants.X_OK) {
|
||||
const err = new Error('EACCES: permission denied');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
// notExecutablePath is never written to disk (its statSync mock above
|
||||
// redirects to a real file instead) — its R_OK call must redirect too,
|
||||
// or this falls through to a real accessSync on a nonexistent path.
|
||||
return fs.accessSync(p === notExecutablePath ? __filename : p, mode);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
assert.deepEqual(result.invalid.map(({ role, reason }) => [role, reason]), [
|
||||
['script', 'missing'],
|
||||
['script', 'wrong-file-type'],
|
||||
['interpreter', 'unresolved-interpreter'],
|
||||
['script', 'unreadable'],
|
||||
['script', 'not-executable'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('an interpreter-invoked script that exists but has no read permission is reported unreadable, not ok (#4249 agy review)', (t) => {
|
||||
// statSync only needs search (+x) permission on the parent directories, so
|
||||
// it succeeds on a chmod-000 file even though `node <script>` would fail
|
||||
// with EACCES at hook-fire time.
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-unreadable-interp-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const scriptPath = path.join(root, 'hook.js');
|
||||
fs.writeFileSync(scriptPath, '// unreadable to the invoking user at hook-fire time\n');
|
||||
|
||||
const result = hooksSurface.validateConfiguredEntrypoints([
|
||||
{
|
||||
runtime: 'claude',
|
||||
configPath: path.join(root, 'settings.json'),
|
||||
scriptPath,
|
||||
interpreterCandidates: ['/usr/bin/node'],
|
||||
},
|
||||
], {
|
||||
resolveExecutableBinary: () => '/usr/bin/node',
|
||||
accessSync: (p, mode) => {
|
||||
if (p === scriptPath && mode === fs.constants.R_OK) {
|
||||
const err = new Error('EACCES: permission denied');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
return fs.accessSync(p, mode);
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
assert.deepEqual(result.invalid.map(({ role, reason }) => [role, reason]), [
|
||||
['script', 'unreadable'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('an EPERM from statSync (Windows equivalent of EACCES on a parent directory) is also reported unreadable, not missing (#4249 agy review)', (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-eperm-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const scriptPath = path.join(root, 'hook.js');
|
||||
|
||||
const result = hooksSurface.validateConfiguredEntrypoints([
|
||||
{ runtime: 'claude', configPath: path.join(root, 'settings.json'), scriptPath },
|
||||
], {
|
||||
statSync: () => {
|
||||
const err = new Error('EPERM: operation not permitted');
|
||||
err.code = 'EPERM';
|
||||
throw err;
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
assert.deepEqual(result.invalid.map(({ role, reason }) => [role, reason]), [
|
||||
['script', 'unreadable'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('a selfExecutable + interpreterCandidates entry checks both the execute bit and the interpreter (#4249 CodeRabbit review — Cline\'s hybrid `env node` shebang)', (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-self-exec-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const okScript = path.join(root, 'ok.js');
|
||||
const notExecScript = path.join(root, 'not-exec.js');
|
||||
fs.writeFileSync(okScript, '#!/usr/bin/env node\n');
|
||||
fs.writeFileSync(notExecScript, '#!/usr/bin/env node\n');
|
||||
|
||||
const makeEntry = (scriptPath) => ({
|
||||
runtime: 'cline',
|
||||
configPath: path.join(root, '.clinerules', 'hooks', 'PreToolUse'),
|
||||
scriptPath,
|
||||
interpreterCandidates: ['node'],
|
||||
selfExecutable: true,
|
||||
// X_OK is a POSIX-only concept (skipped entirely on win32, matching
|
||||
// production) — pinned here so the execute-bit case below is exercised
|
||||
// deterministically regardless of which OS runs the test.
|
||||
platform: 'linux',
|
||||
});
|
||||
|
||||
// plain writeFileSync never sets the execute bit (and the repo bans chmod
|
||||
// in tests), so every case below stubs accessSync to simulate the exact
|
||||
// permission state under test rather than relying on the real filesystem.
|
||||
const alwaysOk = () => {};
|
||||
|
||||
// node missing from PATH entirely: caught even though the script itself is fine.
|
||||
const missingInterpreter = hooksSurface.validateConfiguredEntrypoints([makeEntry(okScript)], {
|
||||
resolveExecutableBinary: () => null,
|
||||
accessSync: alwaysOk,
|
||||
});
|
||||
assert.equal(missingInterpreter.ok, false);
|
||||
assert.deepEqual(missingInterpreter.invalid.map(({ role, reason }) => [role, reason]), [
|
||||
['interpreter', 'unresolved-interpreter'],
|
||||
]);
|
||||
|
||||
// node resolves fine, but the script itself lost its execute bit: caught too —
|
||||
// interpreterCandidates being present must not skip the X_OK check here.
|
||||
const notExecutable = hooksSurface.validateConfiguredEntrypoints([makeEntry(notExecScript)], {
|
||||
resolveExecutableBinary: () => '/usr/bin/node',
|
||||
accessSync: (p, mode) => {
|
||||
if (p === notExecScript && mode === fs.constants.X_OK) {
|
||||
const err = new Error('EACCES: permission denied');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
});
|
||||
assert.equal(notExecutable.ok, false);
|
||||
assert.deepEqual(notExecutable.invalid.map(({ role, reason }) => [role, reason]), [
|
||||
['script', 'not-executable'],
|
||||
]);
|
||||
|
||||
// both hold: clean pass.
|
||||
const clean = hooksSurface.validateConfiguredEntrypoints([makeEntry(okScript)], {
|
||||
resolveExecutableBinary: () => '/usr/bin/node',
|
||||
accessSync: alwaysOk,
|
||||
});
|
||||
assert.equal(clean.ok, true);
|
||||
});
|
||||
|
||||
test('a win32 selfExecutable entry (Codex .cmd shim) skips the execute-bit check (#4249 agy review)', (t) => {
|
||||
// POSIX mode bits don't mean executable on win32 — this must not depend on
|
||||
// Node's own accessSync(X_OK)-as-F_OK no-op (which only protects a real
|
||||
// Windows machine), or a test simulating win32 on a POSIX runner would see
|
||||
// a spurious 'not-executable' for a .cmd shim that was never chmod'd +x.
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-win32-cmd-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const cmdPath = path.join(root, 'gsd-check-update.cmd');
|
||||
fs.writeFileSync(cmdPath, '@echo off\r\n');
|
||||
|
||||
const result = hooksSurface.validateConfiguredEntrypoints([
|
||||
{
|
||||
runtime: 'codex',
|
||||
configPath: path.join(root, 'hooks.json'),
|
||||
scriptPath: cmdPath,
|
||||
platform: 'win32',
|
||||
selfExecutable: true,
|
||||
},
|
||||
], {
|
||||
accessSync: (p, mode) => {
|
||||
if (mode === fs.constants.X_OK) {
|
||||
const err = new Error('EACCES: permission denied');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.ok, true, JSON.stringify(result));
|
||||
});
|
||||
|
||||
test('runtime config writers expose the exact configured entrypoints they emit', (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'configured-entrypoint-writers-'));
|
||||
t.after(() => helpers.cleanup(root));
|
||||
const sourceRoot = path.join(__dirname, '..');
|
||||
|
||||
const codexRoot = path.join(root, 'codex');
|
||||
// On win32, ensureCodexHooksJsonSessionStart writes a .cmd shim under
|
||||
// <codexRoot>/hooks/; the real installer only calls this once that dir
|
||||
// (and gsd-check-update.js) already exist, so create it here too.
|
||||
fs.mkdirSync(path.join(codexRoot, 'hooks'), { recursive: true });
|
||||
const codex = hooksSurface.ensureCodexHooksJsonSessionStart(codexRoot, {
|
||||
absoluteRunner: JSON.stringify(process.execPath),
|
||||
});
|
||||
// win32 emits two entries (the .cmd shim plus the underlying script);
|
||||
// every other platform emits the script alone — assert the shape common
|
||||
// to both rather than a platform-fixed array.
|
||||
assert.ok(codex.configuredEntrypoints.length >= 1);
|
||||
assert.ok(codex.configuredEntrypoints.every(entry => entry.runtime === 'codex'
|
||||
&& entry.configPath === path.join(codexRoot, 'hooks.json')
|
||||
&& entry.platform === process.platform));
|
||||
assert.ok(codex.configuredEntrypoints.some(
|
||||
entry => path.basename(entry.scriptPath) === 'gsd-check-update.js'
|
||||
&& Array.isArray(entry.interpreterCandidates)
|
||||
&& entry.interpreterCandidates.length === 1,
|
||||
));
|
||||
|
||||
const cursorRoot = path.join(root, 'cursor');
|
||||
const cursor = hooksSurface.writeCursorHooksJson(cursorRoot, sourceRoot, {
|
||||
managedHookEvents: ['sessionStart'],
|
||||
});
|
||||
assert.deepEqual(
|
||||
cursor.configuredEntrypoints.map(entry => path.basename(entry.scriptPath)),
|
||||
['gsd-cursor-session-start.js'],
|
||||
);
|
||||
assert.ok(cursor.configuredEntrypoints.every(entry => entry.configPath === cursor.hooksJsonPath));
|
||||
|
||||
const windsurfRoot = path.join(root, 'windsurf');
|
||||
const windsurf = hooksSurface.writeWindsurfHooksJson(windsurfRoot, sourceRoot);
|
||||
assert.deepEqual(
|
||||
windsurf.configuredEntrypoints.map(entry => path.basename(entry.scriptPath)).sort(),
|
||||
['gsd-windsurf-pre-command.js', 'gsd-windsurf-pre-write.js'],
|
||||
);
|
||||
|
||||
const kimiRoot = path.join(root, 'kimi');
|
||||
fs.cpSync(path.join(sourceRoot, 'hooks'), path.join(kimiRoot, 'hooks'), { recursive: true });
|
||||
const kimiConfig = path.join(root, 'kimi-config.toml');
|
||||
const kimi = hooksSurface.writeKimiHooksToml(kimiConfig, kimiRoot, {
|
||||
hookOpts: { runtime: 'kimi' },
|
||||
});
|
||||
assert.equal(kimi.configuredEntrypoints.length, kimi.entryCount);
|
||||
assert.ok(kimi.configuredEntrypoints.every(entry => entry.configPath === kimiConfig));
|
||||
|
||||
const clineRoot = path.join(root, 'cline');
|
||||
const cline = hooksSurface.writeClineArtifacts(clineRoot, false);
|
||||
assert.deepEqual(
|
||||
cline.configuredEntrypoints.map(entry => path.basename(entry.scriptPath)),
|
||||
['PreToolUse'],
|
||||
);
|
||||
// #4249 (CodeRabbit): Cline's `#!/usr/bin/env node` hook is a hybrid —
|
||||
// self-executable (needs its own execute bit checked) AND PATH-dependent
|
||||
// on `node` (needs an interpreter candidate resolved), unlike GSD's other
|
||||
// JS hooks which bake an absolute node path specifically to avoid this.
|
||||
assert.equal(cline.configuredEntrypoints[0].selfExecutable, true);
|
||||
assert.deepEqual(cline.configuredEntrypoints[0].interpreterCandidates, ['node']);
|
||||
|
||||
const portable = [];
|
||||
assert.ok(hooksSurface.buildHookCommand(root, 'gsd-context-monitor.js', {
|
||||
runtime: 'claude',
|
||||
portableHooks: true,
|
||||
configPath: path.join(root, 'settings.json'),
|
||||
configuredEntrypoints: portable,
|
||||
}));
|
||||
assert.deepEqual(
|
||||
portable.map(entry => path.basename(entry.scriptPath)),
|
||||
['gsd-node-runner.sh', 'gsd-context-monitor.js'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a minimal Codex rollback restores skills from the alternate skills home (#4249 CodeRabbit)', (t) => {
|
||||
withSandboxedHome(t, 'configured-entrypoint-codex-skills-', (root) => {
|
||||
const first = install(true, 'codex');
|
||||
// Codex resolves skills to $HOME/.agents/skills, NOT configDir (ADR-1239
|
||||
// skills-kind `home` override) — the surface #3245's own snapshot owns and
|
||||
// the manifest-driven pass deliberately leaves to it.
|
||||
const skillsRoot = path.join(root, '.agents', 'skills');
|
||||
const skillDir = fs.readdirSync(skillsRoot).find(name => name.startsWith('gsd-'));
|
||||
assert.ok(skillDir, `a Codex install must write gsd-* skills under ${skillsRoot}`);
|
||||
const skillFile = path.join(skillsRoot, skillDir, 'SKILL.md');
|
||||
|
||||
const priorBytes = '# bytes only this test wrote\n';
|
||||
fs.writeFileSync(skillFile, priorBytes);
|
||||
|
||||
// Marker-driven core profile — the `gsd update` path into minimal mode.
|
||||
fs.writeFileSync(path.join(first.configDir, '.gsd-profile'), 'core\n');
|
||||
const second = install(true, 'codex');
|
||||
second.rollbackPreInstallSnapshot();
|
||||
|
||||
assert.equal(
|
||||
fs.existsSync(skillFile),
|
||||
true,
|
||||
'a minimal-mode rollback must not delete a skill dir it never snapshotted',
|
||||
);
|
||||
assert.equal(
|
||||
fs.readFileSync(skillFile, 'utf8'),
|
||||
priorBytes,
|
||||
'a minimal-mode rollback must restore alternate-home skills byte-for-byte',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('an aggregate entrypoint validation failure rolls the Codex install back (#4249)', (t) => {
|
||||
withSandboxedHome(t, 'configured-entrypoint-aggregate-', () => {
|
||||
const first = install(true, 'codex');
|
||||
// config.toml is the surface #3245's snapshot restores and the one this
|
||||
// runtime's writer rewrites on every install, so a sentinel surviving here
|
||||
// can only be the rollback's doing.
|
||||
const configPath = path.join(first.configDir, 'config.toml');
|
||||
const priorBytes = '# bytes only this test wrote\n';
|
||||
fs.writeFileSync(configPath, priorBytes);
|
||||
|
||||
// Cline's `#!/usr/bin/env node` hook records interpreterCandidates: ['node'],
|
||||
// resolved off PATH. Emptying PATH makes exactly that entry fail, which is
|
||||
// the only way to drive a REAL aggregate failure through installAllRuntimes:
|
||||
// every other entrypoint is a path the installer just wrote. Codex installs
|
||||
// first, so the reversed rollback loop reaches its restoreCodexSnapshot.
|
||||
const savedPath = process.env.PATH;
|
||||
process.env.PATH = '';
|
||||
try {
|
||||
assert.throws(
|
||||
() => installAllRuntimes(['codex', 'cline'], true, false),
|
||||
/Configured entrypoint validation failed/,
|
||||
'an unresolvable interpreter must fail the aggregate gate',
|
||||
);
|
||||
} finally {
|
||||
process.env.PATH = savedPath;
|
||||
}
|
||||
|
||||
assert.equal(
|
||||
fs.readFileSync(configPath, 'utf8'),
|
||||
priorBytes,
|
||||
'the aggregate failure must reach restoreCodexSnapshot, not just throw',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('an aggregate entrypoint validation failure leaves Cline\'s own config file on disk, unreverted (#4249 review, Major)', (t) => {
|
||||
withSandboxedHome(t, 'configured-entrypoint-unreverted-', () => {
|
||||
// Cline is one of the four runtimes (Cursor/Windsurf/Kimi/Cline) that
|
||||
// write their config file inside install(), ahead of the validation
|
||||
// gate, with no snapshot/restore path — see the rollback-matrix
|
||||
// paragraph in the update-gsd how-to. Unlike the Codex companion test above,
|
||||
// this asserts the POSITIVE case that same paragraph discloses in
|
||||
// prose but no prior test proved: the file the failing runtime itself
|
||||
// just wrote is still there afterward, broken and unreverted.
|
||||
const clineFirst = install(true, 'cline');
|
||||
const clineHookPath = path.join(clineFirst.configDir, '.clinerules', 'hooks', 'PreToolUse');
|
||||
assert.equal(fs.existsSync(clineHookPath), true, 'precondition: Cline hook must exist before the failing install');
|
||||
|
||||
// Same technique as the Codex rollback test: an emptied PATH makes
|
||||
// Cline's own `#!/usr/bin/env node` hook fail interpreter resolution,
|
||||
// driving a REAL aggregate failure through installAllRuntimes.
|
||||
const savedPath = process.env.PATH;
|
||||
process.env.PATH = '';
|
||||
try {
|
||||
assert.throws(
|
||||
() => installAllRuntimes(['codex', 'cline'], true, false),
|
||||
/Configured entrypoint validation failed/,
|
||||
'an unresolvable interpreter must fail the aggregate gate',
|
||||
);
|
||||
} finally {
|
||||
process.env.PATH = savedPath;
|
||||
}
|
||||
|
||||
assert.equal(
|
||||
fs.existsSync(clineHookPath),
|
||||
true,
|
||||
'Cline has no snapshot/restore path — its already-written hook file must remain on disk, not be deleted',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('a NON-entrypoint finalize failure leaves an already-successful Codex install in place (#4249)', (t) => {
|
||||
withSandboxedHome(t, 'configured-entrypoint-nonentry-', () => {
|
||||
const first = install(true, 'codex');
|
||||
// config.toml sits inside surface #3245's pre-install snapshot, so these
|
||||
// bytes come back if — and only if — the full restoreCodexSnapshot() runs.
|
||||
const configPath = path.join(first.configDir, 'config.toml');
|
||||
const priorBytes = '# bytes only this test wrote\n';
|
||||
fs.writeFileSync(configPath, priorBytes);
|
||||
|
||||
// Kilo is the smallest real non-Codex runtime whose finishInstall still
|
||||
// writes: plan.finishPermissionWriter === 'kilo' makes it call
|
||||
// configureKiloPermissions unconditionally (that writer, unlike OpenCode's,
|
||||
// is NOT GSD_TEST_MODE-gated), ending in an unguarded
|
||||
// fs.writeFileSync(<configDir>/kilo.json). Cline can't stand in here — its
|
||||
// plan is writesSharedSettings:false + finishPermissionWriter:null, so its
|
||||
// finishInstall performs no write at all and has no non-entrypoint failure
|
||||
// path to force. EACCES on the Kilo write is injected by monkeypatching
|
||||
// node:fs and restoring it in a finally — never chmod 0o000, which root
|
||||
// bypasses under Docker/CI and would give this test zero real coverage.
|
||||
const realWriteFileSync = fs.writeFileSync;
|
||||
fs.writeFileSync = function poisonedWriteFileSync(target, ...args) {
|
||||
const targetStr = typeof target === 'string' ? target : String(target);
|
||||
if (/[\\/]kilo\.jsonc?$/.test(targetStr)) {
|
||||
const injected = new Error(`EACCES: permission denied, open '${targetStr}'`);
|
||||
injected.code = 'EACCES';
|
||||
throw injected;
|
||||
}
|
||||
return realWriteFileSync.apply(fs, [target, ...args]);
|
||||
};
|
||||
try {
|
||||
assert.throws(
|
||||
() => installAllRuntimes(['codex', 'kilo'], true, false),
|
||||
/EACCES: permission denied/,
|
||||
'a failed Kilo permission write must abort the aggregate install',
|
||||
);
|
||||
} finally {
|
||||
fs.writeFileSync = realWriteFileSync;
|
||||
}
|
||||
|
||||
// Codex installs first and finishInstall prints its "Done!" summary before
|
||||
// Kilo's throws, so the reversed rollback loop does reach Codex's entry —
|
||||
// but with a non-entrypoint error it must take the installer-migrations-only
|
||||
// closure, not restoreCodexSnapshot. A configured-entrypoint validation
|
||||
// failure is the only trigger docs/how-to/update-gsd.md documents for
|
||||
// reverting a runtime install that otherwise succeeded; un-installing (on
|
||||
// update, downgrading) Codex because an unrelated runtime hit EACCES would
|
||||
// contradict the "Done!" the user has already been shown.
|
||||
assert.notEqual(
|
||||
fs.readFileSync(configPath, 'utf8'),
|
||||
priorBytes,
|
||||
'a non-entrypoint finalize failure must not restore the Codex pre-install snapshot',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -562,13 +562,16 @@ describe('install/uninstall — trae (nested skills/gsd-<router>/skills/<stem>/
|
||||
const result = install(false, 'trae');
|
||||
const targetDir = path.join(tmpDir, '.trae');
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
assert.equal(typeof result.rollbackInstallerMigrations, 'function');
|
||||
const { rollbackInstallerMigrations: _rollbackInstallerMigrations, ...resultWithoutRollback } = result;
|
||||
assert.deepStrictEqual(resultWithoutRollback, {
|
||||
settingsPath: null,
|
||||
settings: null,
|
||||
statuslineCommand: null,
|
||||
updateBannerCommand: null,
|
||||
runtime: 'trae',
|
||||
configDir: fs.realpathSync(targetDir),
|
||||
configuredEntrypoints: [],
|
||||
});
|
||||
|
||||
// trae nests: skills/gsd-<router>/skills/<stem>/SKILL.md
|
||||
@@ -5466,6 +5469,36 @@ describe('#338 case 1: fresh local Claude install writes to settings.local.json'
|
||||
`install() must return settingsPath ending in settings.local.json for local Claude installs; got: ${result.settingsPath}`
|
||||
);
|
||||
});
|
||||
|
||||
// #4249 (agy adversarial review, round 8): every early-return branch of
|
||||
// install() must still return the configuredEntrypoints/rollbackInstallerMigrations
|
||||
// shape — rollbackFinalizedInstallerMigrations reads the latter unconditionally,
|
||||
// so an omission here silently drops this runtime's rollback on a later
|
||||
// finalize-stage failure.
|
||||
test('malformed settings.local.json still returns configuredEntrypoints and a working rollbackInstallerMigrations', (t) => {
|
||||
const origCwd = process.cwd();
|
||||
t.after(() => { process.chdir(origCwd); });
|
||||
process.chdir(tmpDir);
|
||||
|
||||
fs.mkdirSync(path.join(tmpDir, '.claude'), { recursive: true });
|
||||
fs.writeFileSync(path.join(tmpDir, '.claude', 'settings.local.json'), '{ not valid json', 'utf-8');
|
||||
|
||||
const result = install(false, 'claude');
|
||||
assert.deepStrictEqual(
|
||||
result.configuredEntrypoints,
|
||||
[],
|
||||
'unparseable settings.local.json must still return configuredEntrypoints: []'
|
||||
);
|
||||
assert.strictEqual(
|
||||
typeof result.rollbackInstallerMigrations,
|
||||
'function',
|
||||
'unparseable settings.local.json must still return a callable rollbackInstallerMigrations'
|
||||
);
|
||||
assert.doesNotThrow(
|
||||
() => result.rollbackInstallerMigrations(),
|
||||
'rollbackInstallerMigrations() must not throw when called on this early-return path'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Case 2: global Claude install (regression guard) ────────────────────────
|
||||
|
||||
@@ -10,12 +10,14 @@ 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 { SMOKE, runSmoke, CHILD_TIMEOUT_MS } = require('../scripts/release-tarball-smoke.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)}`;
|
||||
@@ -85,6 +87,11 @@ describe('release-tarball-smoke', () => {
|
||||
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-');
|
||||
@@ -436,6 +443,124 @@ describe('release-tarball-smoke', () => {
|
||||
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)]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -3135,8 +3135,14 @@ describe('partitionIsolatedFiles (#4497 codex-config.test.cjs chunk isolation, d
|
||||
// same set as each other under the OLD (pre-fix) platform-scaled rule this
|
||||
// row is guarding against — confirming both rows are load-bearing, not
|
||||
// vacuous.
|
||||
//
|
||||
// #4249 split codex-config.test.cjs's heavy install()-pipeline blocks into
|
||||
// codex-config-hooks.test.cjs, dropping codex-config.test.cjs's own
|
||||
// measured weight from 127783ms to 189ms — well under this derived bar
|
||||
// (0.3 * CHUNK_WORKING_BUDGET_MS ~= 120000ms). It correctly no longer
|
||||
// appears in the live-computed isolated set, so it is dropped from this
|
||||
// pinned expectation too, in place of being isolated by name.
|
||||
const EXPECTED_ISOLATED_UNIT_FILES = [
|
||||
'codex-config.test.cjs',
|
||||
'config.test.cjs',
|
||||
'emitted-attribution.test.cjs',
|
||||
'install-minimal-hooks.test.cjs',
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
"unit": "ms",
|
||||
"sources": [
|
||||
"test-events-linux-node22.jsonl",
|
||||
"test-events-linux-node24.jsonl"
|
||||
"test-events-linux-node24.jsonl",
|
||||
"manual: codex-config.test.cjs/codex-config-hooks.test.cjs re-measured locally (node --test --test-reporter=tap, max of 3 runs) after next split codex-config.test.cjs (#4139/#4540) — the old 127783ms entry predated the split and codex-config-hooks.test.cjs, which now holds the #3245/#4249 install()-pipeline blocks, had no entry at all (PR #4249)."
|
||||
],
|
||||
"file_count": 770,
|
||||
"file_count": 771,
|
||||
"timings": {
|
||||
"active-workstream-store.test.cjs": 81,
|
||||
"active-workstream-store.unit.test.cjs": 364,
|
||||
@@ -129,7 +130,8 @@
|
||||
"codebase-mapper-date-restamp.test.cjs": 138,
|
||||
"codebuddy-install.test.cjs": 3763,
|
||||
"codebuddy-upgrades.test.cjs": 2932,
|
||||
"codex-config.test.cjs": 127783,
|
||||
"codex-config-hooks.test.cjs": 3454,
|
||||
"codex-config.test.cjs": 189,
|
||||
"codex-declarative-reference.test.cjs": 205,
|
||||
"command-arg-projection.test.cjs": 113,
|
||||
"command-contract.test.cjs": 1105,
|
||||
|
||||
Reference in New Issue
Block a user