Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 79 additions & 1 deletion packages/cli/src/__tests__/setup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { getGithubWorkflow, syncPackageManifest } from '../commands/setup';
import { detectStack, getGithubWorkflow, loadPackageContexts, syncPackageManifest } from '../commands/setup';

const originalCwd = process.cwd();
const tempDirs: string[] = [];
Expand All @@ -17,6 +17,84 @@ afterEach(() => {
}
});

describe('loadPackageContexts + detectStack (npm workspaces)', () => {
it('discovers packages listed via npm workspaces array glob', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'charter-setup-ws-'));
tempDirs.push(tmp);
process.chdir(tmp);

fs.writeFileSync(
'package.json',
JSON.stringify({ name: 'my-monorepo', version: '0.1.0', private: true, workspaces: ['packages/*'] }, null, 2),
);
fs.mkdirSync(path.join(tmp, 'packages', 'alpha'), { recursive: true });
fs.writeFileSync(
path.join(tmp, 'packages', 'alpha', 'package.json'),
JSON.stringify({ name: '@mono/alpha', version: '1.0.0', dependencies: { hono: '^4.0.0' } }, null, 2),
);
fs.mkdirSync(path.join(tmp, 'packages', 'beta'), { recursive: true });
fs.writeFileSync(
path.join(tmp, 'packages', 'beta', 'package.json'),
JSON.stringify({ name: '@mono/beta', version: '1.0.0' }, null, 2),
);

const contexts = loadPackageContexts();
const sources = contexts.map((c) => c.source);
expect(sources).toContain('packages/alpha/package.json');
expect(sources).toContain('packages/beta/package.json');
});

it('discovers packages via npm workspaces object form { packages: [...] }', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'charter-setup-ws-obj-'));
tempDirs.push(tmp);
process.chdir(tmp);

fs.writeFileSync(
'package.json',
JSON.stringify({
name: 'obj-monorepo',
version: '0.1.0',
private: true,
workspaces: { packages: ['apps/*'], nohoist: ['**/react'] },
}, null, 2),
);
fs.mkdirSync(path.join(tmp, 'apps', 'web'), { recursive: true });
fs.writeFileSync(
path.join(tmp, 'apps', 'web', 'package.json'),
JSON.stringify({ name: 'web', version: '0.0.1', dependencies: { react: '^18.0.0' } }, null, 2),
);

const contexts = loadPackageContexts();
const sources = contexts.map((c) => c.source);
expect(sources).toContain('apps/web/package.json');
});

it('sets monorepo=true and detects correct preset for npm workspace repo', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'charter-setup-ws-detect-'));
tempDirs.push(tmp);
process.chdir(tmp);

fs.writeFileSync(
'package.json',
JSON.stringify({ name: 'hono-mono', version: '0.1.0', private: true, workspaces: ['packages/*'] }, null, 2),
);
fs.mkdirSync(path.join(tmp, 'packages', 'api'), { recursive: true });
fs.writeFileSync(
path.join(tmp, 'packages', 'api', 'package.json'),
JSON.stringify({
name: '@mono/api',
version: '1.0.0',
dependencies: { hono: '^4.0.0', wrangler: '^3.0.0' },
}, null, 2),
);

const contexts = loadPackageContexts();
const result = detectStack(contexts);
expect(result.monorepo).toBe(true);
expect(result.suggestedPreset).toBe('worker');
});
});

describe('syncPackageManifest', () => {
it('adds ongoing governance scripts during setup sync', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'charter-setup-test-'));
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/commands/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { analyze as analyzeBlast, BlastInputSchema } from '@stackbilt/blast';
import { analyze as analyzeSurface, SurfaceInputSchema } from '@stackbilt/surface';
import { parseAdf, parseManifest } from '@stackbilt/adf';
import { detectTsconfigAliases } from './blast';
import { detectStack, loadPackageContexts } from './setup';
import type { CLIOptions } from '../index';
import { EXIT_CODE } from '../index';

Expand Down Expand Up @@ -592,6 +593,15 @@ export async function generateBrief(options?: BriefOptions): Promise<BriefResult
if ((stack === 'unknown' || stack.length === 0) && preset !== 'default') {
stack = preset;
}
if (stack === 'unknown' || stack.length === 0) {
try {
const detection = detectStack(loadPackageContexts());
if (preset === 'default') preset = detection.suggestedPreset;
stack = detection.suggestedPreset;
} catch {
// detection unavailable — stack stays 'unknown'
}
}
const sensitivityTags = [...sensitivityTagSet];

// ---- Build model ----
Expand Down
46 changes: 45 additions & 1 deletion packages/cli/src/commands/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,9 @@ export function detectStack(contexts: PackageContext[]): DetectionResult {
const hasPnpm = contexts.some((ctx) => !!ctx.engines?.pnpm)
|| contexts.some((ctx) => typeof ctx.packageManager === 'string' && ctx.packageManager.toLowerCase().startsWith('pnpm@'))
|| fs.existsSync(path.resolve('pnpm-lock.yaml'));
const monorepo = contexts.length > 1 || fs.existsSync(path.resolve('pnpm-workspace.yaml'));
const monorepo = contexts.length > 1
|| fs.existsSync(path.resolve('pnpm-workspace.yaml'))
|| hasWorkspacesField();
const agentStandards = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']
.filter((filename) => fs.existsSync(path.resolve(filename)));

Expand Down Expand Up @@ -669,6 +671,9 @@ export function loadPackageContexts(): PackageContext[] {
for (const workspaceManifest of resolvePnpmWorkspacePackageJsons()) {
candidates.add(workspaceManifest);
}
for (const workspaceManifest of resolveNpmWorkspacePackageJsons()) {
candidates.add(workspaceManifest);
}

const contexts: PackageContext[] = [];
for (const relativePath of candidates) {
Expand Down Expand Up @@ -724,6 +729,45 @@ function resolvePnpmWorkspacePackageJsons(): string[] {
return [...resolved];
}

function resolveNpmWorkspacePackageJsons(): string[] {
const rootPkgPath = path.resolve('package.json');
if (!fs.existsSync(rootPkgPath)) return [];
let pkg: { workspaces?: unknown };
try {
pkg = JSON.parse(fs.readFileSync(rootPkgPath, 'utf-8')) as { workspaces?: unknown };
} catch {
return [];
}
const raw = pkg.workspaces;
const globs: string[] = Array.isArray(raw)
? (raw as unknown[]).filter((g): g is string => typeof g === 'string')
: Array.isArray((raw as { packages?: unknown })?.packages)
? ((raw as { packages: unknown[] }).packages).filter((g): g is string => typeof g === 'string')
: [];
const resolved = new Set<string>();
for (const glob of globs) {
for (const match of expandWorkspacePackageJsonGlob(glob)) {
resolved.add(match);
}
}
return [...resolved];
}

function hasWorkspacesField(): boolean {
try {
const pkg = JSON.parse(fs.readFileSync(path.resolve('package.json'), 'utf-8')) as { workspaces?: unknown };
const ws = pkg.workspaces;
if (Array.isArray(ws)) return ws.length > 0;
if (ws && typeof ws === 'object') {
const pkgs = (ws as { packages?: unknown[] }).packages;
return Array.isArray(pkgs) && pkgs.length > 0;
}
return false;
} catch {
return false;
}
}

function parsePnpmWorkspaceGlobs(content: string): string[] {
const lines = content.split(/\r?\n/);
const globs: string[] = [];
Expand Down
Loading