import { readFileSync, readdirSync, statSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { SHIPPED_PROFILES } from '../../src/taxonomy/profiles.js'; /** * Turns the spec's "exactly one place" and "exactly one primitive" * requirements into failing checks instead of a convention someone has to * remember: store-lifecycle's shipped-taxonomy-profiles requirement, * Reporter's sole ownership of stdout, and GitRunner's sole ownership of * spawning git. */ const SRC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../src'); function listTsFiles(dir: string): string[] { const files: string[] = []; for (const entry of readdirSync(dir)) { const full = path.join(dir, entry); if (statSync(full).isDirectory()) { files.push(...listTsFiles(full)); } else if (entry.endsWith('.ts')) { files.push(full); } } return files; } function relativeToSrc(file: string): string { return path.relative(SRC_DIR, file).split(path.sep).join('/'); } const ALL_FILES = listTsFiles(SRC_DIR); function filesContainingQuotedLiteral(literal: string, allow: readonly string[]): string[] { const needles = [`'${literal}'`, `"${literal}"`]; const hits: string[] = []; for (const file of ALL_FILES) { const rel = relativeToSrc(file); if (allow.includes(rel)) continue; const content = readFileSync(file, 'utf8'); if (needles.some((n) => content.includes(n))) hits.push(rel); } return hits; } function filesContainingSubstring(substring: string, allow: readonly string[]): string[] { const hits: string[] = []; for (const file of ALL_FILES) { const rel = relativeToSrc(file); if (allow.includes(rel)) continue; if (readFileSync(file, 'utf8').includes(substring)) hits.push(rel); } return hits; } /** Source with comments removed, so a guard matches code rather than prose about code. */ function codeOf(file: string): string { return readFileSync(file, 'utf8') .replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\/\/.*$/gm, ''); } function filesReadingInCode(substring: string, allow: readonly string[]): string[] { return ALL_FILES.filter((file) => !allow.includes(relativeToSrc(file)) && codeOf(file).includes(substring)).map( relativeToSrc, ); } describe('single-source-literals guard', () => { it('every shipped profile/layer name appears only in taxonomy/profiles.ts', () => { const names = new Set(); for (const profile of SHIPPED_PROFILES) { names.add(profile.name); for (const layer of profile.layers) names.add(layer.name); } expect(names.size).toBeGreaterThan(0); // anti-vacuity: there is something to check for (const name of names) { const hits = filesContainingQuotedLiteral(name, ['taxonomy/profiles.ts']); expect(hits, `literal "${name}" leaked outside taxonomy/profiles.ts: ${hits.join(', ')}`).toEqual([]); } }); /** * config-defaults-as-the-convention (D1): the schema and `renderStoreConfig` * both have to mean the same thing by "the shipped default". They can only * be guaranteed to agree by reading the same object, so a `.default(...)` * carrying its own literal is the drift this catches — the schema would * resolve one value while the renderer omitted a key believing it was * another. */ it('every schema default is sourced from SHIPPED_DEFAULTS, never from its own literal', () => { const schema = readFileSync(path.join(SRC_DIR, 'config/schema.ts'), 'utf8') .replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\/\/.*$/gm, ''); const defaults = [...schema.matchAll(/\.(?:default|prefault)\(([^()]*(?:\([^()]*\)[^()]*)*)\)/g)].map((m) => m[1]!.trim()); expect(defaults.length).toBeGreaterThan(0); // anti-vacuity: there is something to check // `prefault({})` carries no value of its own — it re-runs the block's own // per-key defaults, each of which this same check covers. const unsourced = defaults.filter((argument) => argument !== '{}' && !argument.includes('SHIPPED_DEFAULTS')); expect(unsourced, `schema default(s) not read from SHIPPED_DEFAULTS: ${unsourced.join(' | ')}`).toEqual([]); }); /** * publish-names-where-the-page-is-served (D1): the two addresses the * browsing surface answers for a published page now have three readers — * the serve handler that slices them, the navigation that builds hrefs from * them, and the publish commands that report them. A route spelled in three * places is the guessing this change exists to end, one level down. */ it('the published-page route prefixes appear only in core/browse/page-url.ts', () => { const prefixes = ['/publish/', '/preview/', '/review/']; expect(prefixes.length).toBeGreaterThan(0); // anti-vacuity: there is something to check for (const prefix of prefixes) { const hits = filesContainingQuotedLiteral(prefix, ['core/browse/page-url.ts']); expect(hits, `route prefix "${prefix}" leaked outside core/browse/page-url.ts: ${hits.join(', ')}`).toEqual([]); } }); it('no file outside core/reporter.ts writes to process.stdout directly', () => { expect(filesContainingSubstring('process.stdout', ['core/reporter.ts', 'core/env.ts'])).toEqual([]); }); /** * isolate-the-portability-test (task 5.1): `--portable` argues its isolation * from the fact that nothing outside `core/env.ts` reaches for process state * — every other module takes the environment it is given. That was a header * comment; this makes it a failing test. * * Matched against code with comments stripped: several modules *document* * that they never touch `process.env`, and a guard that its own rationale * trips is not a guard. */ it('no module outside core/env.ts reads process.env', () => { expect(filesReadingInCode('process.env', ['core/env.ts'])).toEqual([]); }); it('each external CLI tool has exactly one call site that spawns it', () => { // git and node --check are two different external tools with two // different single homes — core/git/exec.ts for git (behind the // GitRunner interface every other module depends on instead), // core/publish/script-check.ts for node --check (publish check's // embedded-script syntax pass). gh came back with // approve-from-the-review-page, and core/forge/github.ts is its one home // (design.md D10) — as core code, not the forge adapter // session-keeps-only-what-git-cannot-do removed. The store's configured // conflict resolver is spawned only from core/approval/resolver.ts, and // serve's own landing runs (`ctxr land --pending`) only from // core/store-update-runner.ts, with `ctxr sync` (serve-lands-approved-changes D2, // serve-keeps-its-clone-current D1). The // invariant this guards is "no ad hoc, scattered subprocess spawning," // not "only one file in the whole codebase may ever spawn anything." const allow = [ 'core/git/exec.ts', 'core/publish/script-check.ts', 'core/harness/isolated-run.ts', 'core/forge/github.ts', 'core/approval/resolver.ts', 'core/store-update-runner.ts', // serve-the-store-over-mcp D12: ripgrep, for the MCP surface's Grep and Glob. 'core/mcp/ripgrep.ts', // serve-the-session-lifecycle-to-chat-apps D4: the server's own CLI, for the MCP surface's ctxr and ctxr_write. 'core/mcp/cli-runner.ts', // run-the-second-opinion-from-the-cli D1: the model CLIs, from the one command that invokes them. 'core/second-opinion/launch.ts', // install-tools-in-the-home D4: `npm prefix -g`, where `npm install -g` writes. 'core/npm-prefix.ts', ]; const hits = new Set([ ...filesContainingSubstring("'node:child_process'", allow), ...filesContainingSubstring('"node:child_process"', allow), ]); expect([...hits]).toEqual([]); }); });