feat(#2870): resolve install scope as a value (#3278)

* test(#2870): failing-first suite for the Install Scope Module

19 tests over the 50-test-matrix rows 1-19. RED by construction: the
module under test does not exist yet, so the suite fails at require with
MODULE_NOT_FOUND until src/install-scope.cts lands.

Every row asserts a returned value with injected env/home/existsSync --
no filesystem, per the issue's acceptance criterion that tests assert the
resolved value directly.

Row 7 asserts the RELATION rank(global) > rank(local) rather than a
literal, so Phase 2 (#2871) can re-base the numbers without a fixture
edit. Row 4 iterates the real runtime registry rather than a hardcoded
list, excluding vscode, which declares configHome.kind none and is never
CLI-installed.

* feat(#2870): add the Install Scope Module

Scope becomes one resolved value instead of a bare string re-derived at
every layer. resolveScope({id, runtime, ...}) returns
{id, configHome, settingsFile, consentRequired, hostPrecedenceRank}.

It COMPOSES resolveConfigHomeFromDescriptor rather than extending it.
That function has 60 dependents across 13 files and 2 process flows -- a
CRITICAL blast radius -- so adding a scope parameter to it, which the
issue's framing invites, would ripple through all of them. Composing
costs nothing and leaves every existing caller byte-identical.

The module owns the InstallScope type name, which previously lived
privately in runtime-artifact-install-plan.cts; that module now imports
it. A fifth spelling of the same concept would have defeated the phase.

settingsFile is null for the 18 runtimes that declare no
settingsFileByScope -- absence is a value, not an error, and inventing a
Claude-shaped default would leak that host's shape onto every other one.

hostPrecedenceRank ships unread: Phase 2 (#2871) is its first consumer.
It is carried as data only, per this issue's out-of-scope note that
precedence semantics belong to that phase.

Vocabulary: the install axis standardizes on local. ConsentRecord.scope
keeps project deliberately -- that literal is serialized into consent
records in the user's home, and renaming it would silently deactivate
every project-scoped capability on the machine. CONTEXT.md records the
boundary mapping instead.

Every environmental input is injectable (env, home, existsSync, cwd), so
the resolved value is assertable with no filesystem at all.

Registration ripple: .gitignore, eslint.config.mjs, CONTEXT.md glossary,
docs/INVENTORY.md, and the inventory manifest (regenerated after
build:lib, never before).

Verified via the remote runner.

* refactor(#2870): route scope re-derivations through the module

bin/install.js resolves scope once per function instead of inline at
each of its 12 sites, and the settingsFileByScope consumer reads it
through resolveScope().

Seven downstream boolean re-derivations now call the module's
isGlobalScope() instead of comparing the literal independently:
runtime-artifact-install-plan, both runtime-artifact-layout kind
builders, dispatchKindEntry, surface, and two install-engine sites. The
fifth through seventh were not named in the issue -- they are the same
re-derivation class, and leaving them would have made the acceptance
criterion false.

_computePathPrefix keeps its isGlobal boolean API, so the projection is
centralized rather than eliminated. resolveScope and isGlobalScope share
one validator, so the two surfaces cannot drift.

TWO SITES DELIBERATELY NOT ROUTED: runtime-artifact-conversion's
rewriteStagedSkillBodies and rewriteStagedCommandBodies. ADR-1508 fixes
the direction as installer/layout -> conversion, never upward, and
install-scope composes runtime-homes, so importing it into the
conversion module would invert that direction. Left as-is on purpose.

Behavior-preserving throughout. Each step was proven by capturing full
layout and plan output -- including every kind's home field and the
hashed contents of emitted files -- before and after, across both scopes
for claude, codex, opencode, hermes, kimi and kilo. Byte-identical.

surface.cts keeps a scope ?? 'global' default before the call because
Layout.scope is optional there; isGlobalScope throws where the old
inline compare returned false, and that difference would have been a
placement regression.

Verified via the remote runner.

* fix(#2870): cover the no-config-home throw and document the strictness

Two findings from the isolated adversarial review.

The vscode case was implemented but untested. resolveScope throws for a
runtime whose descriptor declares configHome.kind 'none', which is the
design's own behavior-table row 13, but the registry sweep excluded
vscode rather than asserting the throw -- so the behavior shipped with
no test. The exclusion is now legitimate because the case has its own
test naming the runtime in the assertion.

isGlobalScope throws where the inline compare it replaced returned
false. No reachable caller can deliver an out-of-union value today, but
the types are not enforced at runtime, so a future caller passing an
optional Layout.scope would crash rather than silently misroute. That is
the better failure -- misrouting writes artifacts to the wrong place --
but it was undocumented, so the reason is now on the function.

Adds the changeset the acceptance criteria require.

* refactor(#2870): route the last two sites; correct the ADR-1508 claim

The previous commit declined to route runtime-artifact-conversion's
rewriteStagedSkillBodies and rewriteStagedCommandBodies, claiming
ADR-1508's dependency direction forbade the import. That reasoning was
wrong, and this commit corrects it.

Two independent reviewers checked the actual import graph:
runtime-artifact-conversion already imports capability-registry,
command-roster, runtime-name-policy and shell-command-projection -- it
depends on leaf-tier siblings today. install-scope imports only
runtime-homes plus node builtins, and runtime-homes imports only node
builtins, so there is no cycle at any depth. ADR-1508 governs the
installer/layout to conversion boundary, not a leaf-to-leaf sibling
import of the same shape conversion already makes.

With those two routed, every isGlobal re-derivation in the tree now goes
through one owner and acceptance criterion 1 is fully met rather than
partially. Nine sites, not the four the issue enumerated.

Also from the review:

Tests were falling through to the real process.cwd() at five local-scope
call sites, which contradicts the acceptance criterion that the resolved
value be assertable with no filesystem. Every one now injects a cwd. One
of the five was a site the review had not spotted.

bin/install.js carried two near-identical copies of the guarded
resolveScope block, one in install() and one in uninstall() -- duplicated
scope logic in the phase whose purpose is removing it. Extracted to one
helper, and the new sites use the file's existing ternary idiom rather
than the if/else that replaced it.

Equivalence re-proven across both scopes for claude, codex, opencode,
kilo and hermes, now including the staged skill and command body
rewrites hashed per file, since those decide the literal spec-root path
baked into every emitted artifact. Byte-identical.

Verified via the remote runner.

* fix(#2870): assert configHome portably instead of with a native separator

The windows-latest node24 shard failed on two install-scope assertions.
The module was right and the tests were wrong: they built their expected
value with path.join, which emits \fake\home\.claude on Windows, while
resolveScope normalizes separators unconditionally to /fake/home/.claude.

That unconditional normalization is deliberate -- backslash paths arrive
on Linux too, so normalizing via path.sep is the documented defect this
repo guards against. Weakening it to make the assertion pass would have
inverted the fix.

Every path.join-built expectation in the suite now goes through
toPosixPath from tests/helpers.cjs, which is the pattern the
no-path-literal-in-assert rule's own valid-case list sanctions. It splits
on the running platform's path.sep and rejoins with forward slashes, so
it reverses whatever path.join produced on that same platform and the
expectation is invariant everywhere.

Two more call sites had the same latent problem and passed on Linux and
macOS by luck; they are fixed too.

This is the class of defect the remote runner structurally cannot catch
-- its matrix is Linux-only, so a green pass there is not evidence of
portability, and CI's Windows lane is the only place it surfaces.

Verified via the remote runner.

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-09 20:16:23 -04:00
committed by GitHub
parent b901d1e06f
commit c2f24265f2
14 changed files with 777 additions and 24 deletions

View File

@@ -32,6 +32,12 @@ import retiredArtifactCleanup = require('./retired-artifact-cleanup.cjs');
import { posixNormalize } from './shell-command-projection.cjs';
import { isPathConfined } from './external-descriptor-trust.cjs';
import { ensureCommonJsMarker } from './commonjs-marker.cjs';
// #2870: InstallScope is owned by install-scope.cts, not re-declared here.
// `isGlobalScope` centralizes the `scope === 'global'` boolean projection
// this module's two remaining re-derivation sites need (see the
// module-level doc comment on `isGlobalScope` for why the projection is
// centralized rather than eliminated).
import { isGlobalScope, type InstallScope } from './install-scope.cjs';
const { processAttribution } = runtimeArtifactConversion;
// resolveRuntimeArtifactLayout: accessed via module ref (not destructured) so
@@ -673,7 +679,15 @@ function _runLegacyUninstallCleanup(runtime: string, configDir: string, scope: s
// to the same location (#1423). Using migrateLegacyDevPreferencesToSkill here
// (which would redirect to skills/) conflicts with the test contract for local installs.
const _lu = _hostBehaviors(runtime).legacyCommandsGsdUninstall;
const isLegacyCommandsGsd = _lu === true || (_lu === 'global' && scope === 'global');
// #2870: `scope` keeps its exported `string = 'global'` signature (no
// signature change), but every real caller — `uninstallRuntimeArtifacts`'s
// own required `scope` param, always fed a validated 'global' | 'local'
// literal by bin/install.js's scope-resolution ternary, plus every direct
// test call site — only ever supplies 'global' or 'local'. The existing
// `= 'global'` default already reproduces today's behavior for an omitted
// scope, so the cast below is safe: `isGlobalScope` never sees a value
// outside its union here.
const isLegacyCommandsGsd = _lu === true || (_lu === 'global' && isGlobalScope(scope as InstallScope));
if (isLegacyCommandsGsd) {
const legacyCommandsGsd = path.join(configDir, 'commands', 'gsd');
if (fs.existsSync(legacyCommandsGsd)) {
@@ -1280,7 +1294,12 @@ function installOpencodeFamilyArtifacts(
behaviors: any = {},
capabilityRegistry?: any,
): void {
const isGlobal = scope === 'global';
// #2870: `scope` keeps its exported required `string` signature (no
// signature change). It is always the `installRuntimeArtifacts`-forwarded
// 'global' | 'local' literal produced by bin/install.js's scope-resolution
// ternary (both real call sites and every test call site), so the cast is
// safe: `isGlobalScope` never sees a value outside its union here.
const isGlobal = isGlobalScope(scope as InstallScope);
// findInstallSourceRoot resolves DIRECTLY to the commands/gsd source dir
// (via the .gsd-source marker or a walk-up from __dirname) — every other
// call site in runtime-artifact-layout.cts feeds its return value straight

321
src/install-scope.cts Normal file
View File

@@ -0,0 +1,321 @@
/**
* install-scope.cts — Install Scope Module (#2870, ADR-2866, governed by
* ADR-2866, Phase 0 PR #3265).
*
* `resolveScope()` turns a bare `'global' | 'local'` string — previously
* re-derived at 12 `isGlobal ? 'global' : 'local'` sites in `bin/install.js`
* plus several downstream consumers — into ONE resolved value produced by
* ONE module. See `.gsd/phase/feat-2870-install-scope-module/40-design.md`
* for the full behavior table and rationale; the summary that matters for
* future readers is captured in the comments below.
*
* This module OWNS the `InstallScope` type name. It was previously declared
* (as a private, non-exported `TypeAlias`) inside
* `runtime-artifact-install-plan.cts`; that module now imports it from here
* instead of re-declaring it, so the codebase has one spelling of "install
* scope" instead of a fifth one appearing alongside the three that already
* existed (`'local' | 'global'` in the layout module, `'global' | 'project'`
* in capability-lifecycle, and the single literal `'project'` in
* capability-consent).
*
* ── Compose, never modify, resolveConfigHomeFromDescriptor ─────────────────
* `resolveConfigHomeFromDescriptor` (`runtime-homes.cts`) is rated CRITICAL
* blast radius: 60 dependents across 13 files and 2 process flows. Adding a
* `scope` parameter to it — the "obvious" refactor — would touch all 60 for
* no reason this module needs: it already resolves the GLOBAL config home
* correctly today. So this module calls it as-is for the global scope and
* derives the LOCAL scope's config dir independently (see
* `resolveScopeConfigHome` below) — genuine composition, not a rename. Every
* one of those 60 call sites stays byte-identical.
*
* ── Why `settingsFile: null` is correct, not a bug ──────────────────────────
* Only `claude` declares `hostBehaviors.settingsFileByScope` in the
* capability registry; the other 18 registered runtimes do not have a
* per-scope settings file at all. Returning `null` for them is honest —
* substituting `'settings.json'` (or any other Claude-shaped default) would
* invent a fact for every non-Claude runtime that asked. Callers that
* legitimately want a Claude-specific fallback (there is exactly one today,
* `bin/install.js:550`) apply it themselves; this module does not.
*/
import path from 'node:path';
import os from 'node:os';
import {
resolveConfigHomeFromDescriptor,
type ConfigHomeDescriptor,
} from './runtime-homes.cjs';
// In .cts (CommonJS output) files, `require` is available as a global.
const _require: NodeRequire = require;
// ── Public types ────────────────────────────────────────────────────────
/**
* The two install-scope axis values. Spelling is `'local'`, not `'project'`:
* `'local'` is the CLI's own vocabulary (`--local`), matches what the
* artifact-layout module and the manifest already use, and is what the user
* types. `'project'` is a SEPARATE, deliberately un-unified vocabulary that
* belongs to the capability consent/lifecycle subsystem — see the boundary
* mapping below.
*/
export type InstallScope = 'global' | 'local';
export interface ResolvedScope {
id: InstallScope;
/** Absolute config directory for this scope, normalized to forward
* slashes (see `normalizeSeparators` below). */
configHome: string;
/** Per-scope settings filename declared by the runtime's descriptor, or
* `null` when the runtime declares none. `null` is a value, not an
* error — see the module-level comment above. */
settingsFile: string | null;
/** `false` for `global` (nothing is recorded — the scope lives under the
* user's own home, matching `capability-lifecycle.cts:163`'s rule).
* `true` for `local`. This module reports the requirement; it does not
* perform or waive consent — `capability-consent.cts` owns that. */
consentRequired: boolean;
/** Higher wins; `global` outranks `local`. Carried as data only — nothing
* in this phase reads it (Phase 2, #2871, is the first consumer). Not a
* shadowing/collision answer on its own: whether two artifacts actually
* collide needs the trigger, which is out of scope here. */
hostPrecedenceRank: number;
}
export interface ResolveScopeInput {
id: InstallScope;
runtime: string;
/** Explicit config-dir override (e.g. `--config-dir`). Honored identically
* to `getGlobalConfigDir(runtime, explicitDir)` — takes precedence over
* every other resolution path, for both scopes. */
explicitDir?: string;
env?: Record<string, string | undefined>;
home?: string;
existsSync?: (p: string) => boolean;
/** Working directory the `local` scope's `configHome` is resolved against
* — defaults to `process.cwd()`, so local-scope resolution is assertable
* without a real working directory, matching `env`/`home`/`existsSync`. */
cwd?: string;
}
// ── The `local` / `project` boundary (see CONTEXT.md glossary entry) ──────
//
// `ConsentRecord.scope: 'project'` (capability-consent.cts) and
// `capability-lifecycle.cts:163`'s `'global' | 'project'` are NOT renamed to
// match this module's `'local'` spelling. `ConsentRecord.scope` is persisted
// on disk in user-owned consent records outside this repo; renaming that
// literal would silently invalidate every existing project-scoped consent
// record on a user's machine the next time it is read back. The
// reconciliation is a documented boundary mapping, not a rename sweep:
// install scope 'local' ⇄ consent scope 'project'
// install scope 'global' ⇄ no consent record at all
// `consentRequired` above reports the install-scope side of that mapping;
// it is deliberately still the CLI's own vocabulary.
const VALID_SCOPE_IDS: ReadonlySet<string> = new Set(['global', 'local']);
/**
* Single owner of the `'global' | 'local'` membership check. `resolveScope`
* and `isGlobalScope` (below) both call this instead of each carrying its
* own copy of the rule — two surfaces reading one validator, not two
* validators that could silently diverge.
*/
function validateScopeId(id: unknown, caller: string): InstallScope {
if (typeof id !== 'string' || !VALID_SCOPE_IDS.has(id)) {
throw new TypeError(
`${caller}: id must be one of 'global' | 'local', got ${JSON.stringify(id)}`,
);
}
return id as InstallScope;
}
// Higher wins. Not exported as a public constant — only the resulting
// `hostPrecedenceRank` field on `ResolvedScope` is public API, so a future
// re-basing of the literal values (Phase 2, #2871) never requires touching
// an exported symbol.
const HOST_PRECEDENCE_RANK: Record<InstallScope, number> = {
global: 2,
local: 1,
};
interface HostBehaviorsForScope {
settingsFileByScope?: Partial<Record<InstallScope, string>>;
}
interface RuntimeDescriptorForScope {
configHome: ConfigHomeDescriptor;
/** Project-relative local config dir (e.g. `.claude`), or `null` for a
* runtime with no installable config dir at all (vscode). Resolved
* against `resolveScope`'s input `cwd` (defaulting to the real process
* cwd), the same way `bin/install.js`'s existing local-scope call sites
* (e.g. `path.join(process.cwd(), '.agents')`) resolve it today. */
localConfigDir?: string | null;
hostBehaviors?: HostBehaviorsForScope;
}
interface RegistryLike {
runtimes: Record<string, { runtime?: RuntimeDescriptorForScope }>;
}
/** Lazy registry accessor — mirrors the pattern in runtime-homes.cts /
* runtime-artifact-layout.cts (5b/5c/5d). */
function getRegistry(): RegistryLike {
return _require('./capability-registry.cjs') as RegistryLike;
}
/**
* Normalize path separators UNCONDITIONALLY (never gated on `path.sep` /
* `process.platform`). A Windows-shaped `home` (`C:\Users\x`) can arrive on
* any host — via an injected test fixture, a cross-platform config sync, or
* a value copied from a Windows machine — so the normalization must not
* depend on which OS this process happens to be running on.
*/
function normalizeSeparators(p: string): string {
return p.replace(/\\/g, '/');
}
/**
* Minimal leading-`~` expansion for `explicitDir`. `runtime-homes.cts`'s own
* `expandTilde` is NOT exported (it is a private helper), and this module
* must not add exports to that CRITICAL-blast-radius file just to reuse
* three lines — so this is an intentionally small, independent
* reimplementation, not a fork of shared logic.
*/
function expandTildeForExplicitDir(p: string, home: string | undefined): string {
const resolvedHome = home ?? os.homedir();
if (p === '~') return resolvedHome;
if (p.startsWith('~/')) return path.join(resolvedHome, p.slice(2));
return p;
}
/**
* Resolve the config-home directory for one scope. `explicitDir` short-
* circuits both scopes identically (matches `getGlobalConfigDir`'s existing
* override behavior — the module must not regress it). Otherwise:
* - `global`: delegates entirely to `resolveConfigHomeFromDescriptor`
* (composition — see the module-level comment).
* - `local`: joins the registry's `localConfigDir` onto `cwd` (defaulting
* to the real process cwd) — the project-local dir, independent of
* `home`/`env`.
*/
function resolveScopeConfigHome(
id: InstallScope,
descriptor: RuntimeDescriptorForScope,
input: ResolveScopeInput,
): string {
const explicitDir = input.explicitDir;
if (typeof explicitDir === 'string' && explicitDir.trim() !== '') {
return normalizeSeparators(expandTildeForExplicitDir(explicitDir, input.home));
}
if (id === 'local') {
// localConfigDir is guaranteed non-null here: the only registered
// runtime with `localConfigDir: null` is vscode, and vscode's
// `configHome.kind === 'none'` already causes resolveScope to throw
// before this function is ever called (see the 'none' guard below).
const localConfigDir = descriptor.localConfigDir as string;
const cwd = input.cwd ?? process.cwd();
return normalizeSeparators(path.join(cwd, localConfigDir));
}
return normalizeSeparators(
resolveConfigHomeFromDescriptor(descriptor.configHome, {
env: input.env,
home: input.home,
existsSync: input.existsSync,
}),
);
}
/**
* Resolve a bare `'global' | 'local'` scope id plus a runtime into a single
* `ResolvedScope` value: the config directory, the per-scope settings
* filename (or `null`), whether the scope requires a consent record, and a
* precedence rank (data only this phase — see `hostPrecedenceRank` above).
*
* Pure: performs no writes and no I/O of its own beyond what
* `resolveConfigHomeFromDescriptor` already performs via the injected
* `existsSync` (for `global`) or the injected `cwd`, defaulting to
* `process.cwd()` (for `local`). Never mutates `input`. The returned object
* is frozen so a caller mutating the result cannot corrupt a subsequent
* call.
*
* Throws `TypeError` for:
* - an `id` outside `'global' | 'local'` — including wrong case, empty,
* missing, or any non-string value (no coercion, ever);
* - an unknown `runtime` (no matching capability-registry entry);
* - a `runtime` whose descriptor has `configHome.kind === 'none'`
* (vscode) — there is no installable config directory to resolve, so
* inventing one (or silently returning `configHome: null`) would be
* dishonest. All three cases share one catch shape (`instanceof
* TypeError`) with `resolveRuntimeArtifactLayout`'s existing contract
* for unknown runtimes, so callers of both never need two different
* catch blocks.
*/
export function resolveScope(input: ResolveScopeInput): ResolvedScope {
const scopeId = validateScopeId(input?.id, 'resolveScope');
const runtime = input.runtime;
const registryEntry = typeof runtime === 'string'
? getRegistry().runtimes[runtime]
: undefined;
const descriptor = registryEntry?.runtime;
if (!descriptor) {
throw new TypeError(
`resolveScope: unknown runtime '${String(runtime)}' — not present in the capability registry`,
);
}
if (descriptor.configHome.kind === 'none') {
// #2103: vscode-shaped runtimes (Marketplace/VSIX, installSurface:
// 'none') have no file-projected config directory at all — the same
// carve-out tests/runtime-flags.test.cjs's NON_INSTALLABLE_RUNTIMES
// already documents. Throwing here matches
// resolveConfigHomeFromDescriptor's own deliberate throw on this kind,
// rather than silently inventing an install scope for a runtime that
// cannot be installed.
throw new TypeError(
`resolveScope: runtime '${runtime}' has no installable config directory (configHome.kind === 'none')`,
);
}
const configHome = resolveScopeConfigHome(scopeId, descriptor, input);
const settingsFile = descriptor.hostBehaviors?.settingsFileByScope?.[scopeId] ?? null;
const consentRequired = scopeId === 'local';
const hostPrecedenceRank = HOST_PRECEDENCE_RANK[scopeId];
return Object.freeze({
id: scopeId,
configHome,
settingsFile,
consentRequired,
hostPrecedenceRank,
});
}
/**
* Project an `InstallScope` down to the boolean shape some downstream APIs
* still require. Four call sites (both kind-builder closures in
* `runtime-artifact-layout.cts`, plus one each in
* `runtime-artifact-install-plan.cts` and `surface.cts`) were each
* independently re-deriving this same `scope === 'global'` comparison — four
* copies of one rule that could silently drift apart (#2870). They exist
* because `runtime-artifact-conversion.cts`'s `_computePathPrefix` takes
* `isGlobal: boolean` at its API boundary, and that boundary is not changing
* here, so the boolean projection cannot be eliminated — only centralized to
* the one place below.
*
* Throws the same `TypeError`, with the same message shape, as
* `resolveScope` throws for an `id` outside `'global' | 'local'` — both call
* `validateScopeId` above, so the two error contracts cannot diverge.
*
* Deliberately throws, rather than returning `false`, for an out-of-union
* value — unlike the inline `scope === 'global'` comparison it replaced,
* which silently returned `false` for anything unrecognized. The
* alternative is silently treating an unknown scope as "not global" and
* writing artifacts to the wrong place, which is worse than failing loud.
* A caller holding an optional `scope` (e.g. a raw `Layout.scope`) must
* default it before calling this — see `surface.cts` for the pattern.
*/
export function isGlobalScope(scope: InstallScope): boolean {
return validateScopeId(scope, 'isGlobalScope') === 'global';
}

View File

@@ -25,6 +25,10 @@ import runtimeNamePolicy = require('./runtime-name-policy.cjs');
const { getDirName } = runtimeNamePolicy;
import capabilityRegistry = require('./capability-registry.cjs');
import { posixNormalize } from './shell-command-projection.cjs';
// #2870: install-scope.cts is a leaf-tier sibling (imports only
// runtime-homes.cjs + node builtins, never this module) — no cycle. See the
// isGlobal sites below for why the boolean projection is centralized here too.
import { isGlobalScope } from './install-scope.cjs';
// #1383: resolve GSD's version WITHOUT a top-level
// `require('../../../package.json')`. That require ran at module load on every
@@ -2862,7 +2866,10 @@ function rewriteStagedSkillBodies(stagedDir, opts) {
const resolvedTarget = posixNormalize(path.resolve(configDir));
const homeDir = posixNormalize(homedir());
const isGlobal = scope === 'global';
// #2870: `scope` is defaulted to 'global' above, so it is never undefined
// here, and every reachable caller passes 'global' | 'local' | undefined —
// isGlobalScope's throw-on-out-of-union case is unreachable at this site.
const isGlobal = isGlobalScope(scope);
const isOpencode = false; // #2087: opencode installs via the combined-family engine path, never through the generic rewrite
const isWindowsHost = platform === 'win32';
const pathPrefix = computePathPrefix({ isGlobal, isOpencode, isWindowsHost, resolvedTarget, homeDir });
@@ -2900,7 +2907,10 @@ function rewriteStagedCommandBodies(stagedDir, opts) {
const resolvedTarget = posixNormalize(path.resolve(configDir));
const homeDir = posixNormalize(homedir());
const isGlobal = scope === 'global';
// #2870: `scope` is defaulted to 'global' above, so it is never undefined
// here, and every reachable caller passes 'global' | 'local' | undefined —
// isGlobalScope's throw-on-out-of-union case is unreachable at this site.
const isGlobal = isGlobalScope(scope);
const isOpencode = false; // #2087: opencode installs via the combined-family engine path, never through the generic rewrite
const isWindowsHost = platform === 'win32';
const pathPrefix = computePathPrefix({ isGlobal, isOpencode, isWindowsHost, resolvedTarget, homeDir });

View File

@@ -12,8 +12,14 @@
const _require: NodeRequire = require;
const path = _require('node:path') as typeof import('node:path');
// #2870: InstallScope is owned by install-scope.cts, not re-declared here.
// `isGlobalScope` centralizes the `scope === 'global'` boolean projection
// this module needs at `_computePathPrefix`'s `isGlobal: boolean` boundary
// (see the module-level doc comment on `isGlobalScope` for why the
// projection is centralized rather than eliminated).
import { isGlobalScope, type InstallScope } from './install-scope.cjs';
type ArtifactKindName = 'commands' | 'agents' | 'skills' | 'kimi-agents';
type InstallScope = 'local' | 'global';
interface ResolvedProfile {
name?: string;
@@ -181,7 +187,11 @@ function createRuntimeArtifactInstallPlan(args: CreateRuntimeArtifactInstallPlan
const homedirFn: () => string = homedir ?? (() => os.homedir());
const resolvedTarget = posixNormalize(path.resolve(layout.configDir));
const homeDir = posixNormalize(homedirFn());
const isGlobal = scope === 'global';
// #2870: `scope` above is already the module-owned `InstallScope` value
// (`layout.scope ?? 'global'`, defaulted before this point, so it is never
// `undefined` here) — `isGlobalScope` projects it to the boolean
// `_computePathPrefix`'s existing `isGlobal: boolean` API requires.
const isGlobal = isGlobalScope(scope);
const isOpencode = layout.runtime === 'opencode';
const isWindowsHost = (platform ?? process.platform) === 'win32';
const pathPrefix = conversionExports._computePathPrefix({ isGlobal, isOpencode, isWindowsHost, resolvedTarget, homeDir });

View File

@@ -30,6 +30,11 @@ const conversionExports = runtimeArtifactConversion as Record<string, unknown> &
readGsdCommandNames?: () => string[];
};
import { posixNormalize } from './shell-command-projection.cjs';
// #2870: `isGlobalScope` centralizes the `scope === 'global'` boolean
// projection both kind-builder closures below need at the converters'
// positional `isGlobal` boundary (see its doc comment in install-scope.cts
// for why the projection is centralized rather than eliminated).
import { isGlobalScope } from './install-scope.cjs';
// In .cts (CommonJS output) files, `require` is available as a global.
const _require: NodeRequire = require;
@@ -272,6 +277,11 @@ function convertedAgentsKind(
// choose global-home vs workspace-relative paths; converters that only take
// (content) ignore the extra positional arg. Mirrors skillsKind's scope
// threading (#1173).
// #2870: `scope` is this function's own parameter (default `'global'`,
// so it is never undefined here), sourced upstream from the Install
// Scope Module's resolved id. `isGlobalScope` projects it to the
// boolean `stageAgentsForRuntimeWithConverter`'s positional API
// requires — see its doc comment in install-scope.cts.
const converter = conversionExports[converterName] as (content: string, isGlobal?: boolean) => string;
// ADR-1235 §1: when agentCtx is provided (by createRuntimeArtifactInstallPlan
// for descriptor-driven runtimes), thread it through so stageAgentsForRuntimeWithConverter
@@ -280,7 +290,7 @@ function convertedAgentsKind(
findAgentsSourceRoot(configDir),
resolved,
converter,
scope === 'global',
isGlobalScope(scope),
agentCtx,
);
},
@@ -380,7 +390,11 @@ function skillsKind(
const cmdNames = conversionExports.readGsdCommandNames
? conversionExports.readGsdCommandNames()
: [];
const isGlobal = scope === 'global';
// #2870: same judgment as convertedAgentsKind above — `scope` is this
// function's own parameter (default `'global'`, so it is never
// undefined here); `isGlobalScope` projects it to the boolean
// `realConverter`'s positional `isGlobal` arg requires.
const isGlobal = isGlobalScope(scope);
const wrappedConverter = (content: string, skillName: string): string =>
realConverter(content, skillName, runtime, cmdNames, isGlobal);
return stageSkillsForRuntimeAsSkills(findInstallSourceRoot(configDir), resolved, wrappedConverter, prefix, nested, capabilityRegistry);
@@ -540,7 +554,11 @@ function dispatchKindEntry(entry: ArtifactKindDescriptor, runtime: string, confi
);
}
if (scope === 'global' && typeof entry.home === 'string' && entry.home !== '') {
// scope is guaranteed 'local' | 'global' here: resolveRuntimeArtifactLayoutFromRegistry
// (the only caller of dispatchKindEntry) throws TypeError before this point if scope is
// anything else (see the `scope !== 'local' && scope !== 'global'` guard above its
// dispatchKindEntry call), so isGlobalScope's throw-on-invalid-input never fires here.
if (isGlobalScope(scope) && typeof entry.home === 'string' && entry.home !== '') {
result.home = path.join(os.homedir(), entry.home);
}

View File

@@ -45,6 +45,11 @@ const {
} = installProfiles;
import { CLUSTERS } from './clusters.cjs';
import type { ClusterMap } from './clusters.cjs';
// #2870: `isGlobalScope` centralizes the `scope === 'global'` boolean
// projection `applySurface` needs at `_computePathPrefix`'s `isGlobal:
// boolean` boundary (see its doc comment in install-scope.cts for why the
// projection is centralized rather than eliminated).
import { isGlobalScope } from './install-scope.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import runtimeArtifactLayout = require('./runtime-artifact-layout.cjs');
const { findInstallSourceRoot } = runtimeArtifactLayout;
@@ -369,7 +374,17 @@ function applySurface(runtimeConfigDir: string, layout: Layout, manifest: Map<st
const _homedirFn: () => string = opts?.homedir ?? (() => os.homedir());
const _resolvedTarget = posixNormalize(path.resolve(layout.configDir));
const _homeDir = posixNormalize(_homedirFn());
const _isGlobal = (layout.scope ?? 'global') === 'global';
// #2870: same judgment as createRuntimeArtifactInstallPlan's identical
// line — `layout.scope` is already the resolved scope value on the
// `Layout` this function received. `layout.scope` is optional, so the
// pre-existing `?? 'global'` default is kept ahead of the call: it must
// run BEFORE `isGlobalScope`, because `isGlobalScope(undefined)` throws
// (unlike the old inline `undefined === 'global'`, which silently
// evaluated to `false`) — the default is what makes an undefined scope
// resolve to `'global'` here, exactly as it did before. `isGlobalScope`
// then projects the defaulted value to the boolean `_computePathPrefix`'s
// existing `isGlobal: boolean` API requires.
const _isGlobal = isGlobalScope(layout.scope ?? 'global');
const _isOpencode = layout.runtime === 'opencode';
const _isWindowsHost = (opts?.platform ?? process.platform) === 'win32';
const _pathPrefix = runtimeArtifactConversion._computePathPrefix({ isGlobal: _isGlobal, isOpencode: _isOpencode, isWindowsHost: _isWindowsHost, resolvedTarget: _resolvedTarget, homeDir: _homeDir });