From a9ec6768bc718b569371b2e550d581332d67e278 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Wed, 28 Oct 2026 00:08:06 +1100 Subject: [PATCH] fix(spaces): report the config only; no path or schema checks on listing sctx spaces ran a per-space audit that assumed every path is a local file, so a space whose path is a URL turned the SessionStart hooks off for the whole config. spaces now loads the config once and reports config-level problems only. checkConfig becomes inspectConfig, which no longer looks at spaces. Hooks no longer treat a validate run that produced no output (for example a schema that fails to load) as clean: validateSpace throws, so the hook reports it once as E_HOOK_FAILED. --- hook-test/unit/preflight.test.ts | 34 +++++++-- plugin/.claude-plugin/plugin.json | 2 +- plugin/scripts/state.ts | 15 ++-- plugin/skills/setup-space/SKILL.md | 2 +- .../references/troubleshooting.md | 6 +- src/commands/spaces.ts | 8 +-- src/config/health.ts | 70 +++---------------- tests/commands/spaces-config-only.test.ts | 58 +++++++++++++++ tests/config/health.test.ts | 34 ++++++--- 9 files changed, 140 insertions(+), 89 deletions(-) create mode 100644 tests/commands/spaces-config-only.test.ts diff --git a/hook-test/unit/preflight.test.ts b/hook-test/unit/preflight.test.ts index a272c63..1471d6b 100644 --- a/hook-test/unit/preflight.test.ts +++ b/hook-test/unit/preflight.test.ts @@ -67,14 +67,22 @@ describe('runPreflight', () => { } }); - it('reports a moved space path with its code and a fix', async () => { - rmSync(fixtures.vaultDir, { recursive: true, force: true }); + it('does not switch hooks off for a space whose path is not a local file', async () => { + const remote = 'https://example.atlassian.net/wiki/spaces/X/pages/1/Page'; + writeFileSync( + fixtures.configPath, + JSON.stringify({ + spaces: [ + { name: 'remote', path: remote, schema: 'strategy_general.json' }, + { name: 'test-space', path: fixtures.vaultDir, schema: 'strategy_general.json' }, + ], + }), + ); const result = await runPreflight({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); - expect(result.systemMessage).toContain('E_SPACE_PATH_MISSING'); - expect(result.additionalContext).toContain('Fix:'); - expect(result.additionalContext).toContain('Troubleshooting'); + expect(result.systemMessage).toBeUndefined(); + expect(result.additionalContext).toContain('test-space'); }); it('reports an unreadable config', async () => { @@ -125,6 +133,22 @@ describe('other hooks stay quiet when setup is broken', () => { }); }); +describe('a space that cannot be validated is not reported as clean', () => { + it('on-prompt fails with the reason when the schema does not load', async () => { + const schema = join(fixtures.fixtureDir, 'bad.json'); + writeFileSync(schema, '{ not json'); + writeFileSync( + fixtures.configPath, + JSON.stringify({ spaces: [{ name: 'test-space', path: fixtures.vaultDir, schema }] }), + ); + + await expect(runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts())).rejects.toThrow( + 'E_SCHEMA_INVALID', + ); + expect(loadState(stateFilePath(sessionId, opts())).baseline).toEqual({}); + }); +}); + describe('runSafely', () => { it('turns an error into one message per session and does not rethrow', async () => { const saved = process.env.SCTX_STATE_DIR; diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index c0054df..c618d76 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.16.5", + "version": "0.16.6", "description": "Structured content authoring for Obsidian — automatic validation hooks, slash commands, and agent skills to keep markdown files compliant with your schema.", "homepage": "https://github.com/mindsocket/structured-context", "repository": "https://github.com/mindsocket/structured-context", diff --git a/plugin/scripts/state.ts b/plugin/scripts/state.ts index f96a2ca..db3787f 100644 --- a/plugin/scripts/state.ts +++ b/plugin/scripts/state.ts @@ -156,10 +156,6 @@ export async function runSctx(args: string[], options?: HookOptions): Promise { - return (await runSctx(args, options)).stdout; -} - /** Parse `sctx spaces --json` output, or undefined when it isn't usable. */ export function parseSpacesOutput(text: string): SpacesOutput | undefined { try { @@ -207,11 +203,16 @@ export function hashSpace(space: SpaceInfo, configFiles: string[]): string { /** * Validate a whole space and group its errors and warnings by file label. * Info-level rule violations are left out: they are not worth another turn from Claude. + * Throws when validation could not run (for example a schema that fails to load), so the hook reports + * that once instead of treating the space as clean. */ export async function validateSpace(name: string, options?: HookOptions): Promise> { - const text = await sctx(['validate', name, '--json'], options); - if (!text) return {}; - const output = JSON.parse(text) as ValidateOutput; + const run = await runSctx(['validate', name, '--json'], options); + if (!run.stdout.trim()) { + const detail = run.stderr.trim().split('\n')[0] || `exit code ${run.exitCode}`; + throw new Error(`validating space "${name}" produced no result: ${detail}`); + } + const output = JSON.parse(run.stdout) as ValidateOutput; const byFile: Record = {}; const issuesFor = (label: string): FileIssues => { diff --git a/plugin/skills/setup-space/SKILL.md b/plugin/skills/setup-space/SKILL.md index 42fee42..c1fe39f 100644 --- a/plugin/skills/setup-space/SKILL.md +++ b/plugin/skills/setup-space/SKILL.md @@ -15,7 +15,7 @@ at the content, not from asking. ## 1. Check the setup ```bash -sctx spaces --json # config found, spaces valid, problems with codes +sctx spaces --json # config found and loads, spaces listed, problems with codes ``` If `sctx` is not installed: `bun install -g structured-context` (needs Bun). For any error in `problems`, use diff --git a/plugin/skills/structured-context/references/troubleshooting.md b/plugin/skills/structured-context/references/troubleshooting.md index 2ce8b54..2ee09a8 100644 --- a/plugin/skills/structured-context/references/troubleshooting.md +++ b/plugin/skills/structured-context/references/troubleshooting.md @@ -13,9 +13,11 @@ empty or `info` only. Hooks pick up a fixed config on the next prompt. A missing | `E_TARGET_REQUIRED` | Ask where the config belongs. Usually `--config /.sctx.json`; `--global` only if the user asks | | `E_HOOK_FAILED` | A hook crashed and was skipped. Set `SCTX_DEBUG=1` for the session, or run the same `sctx` command by hand. Usually a problem with its own code above | -Other codes (`E_CONFIG_INVALID`, `E_INCLUDE_NOT_FOUND`, `E_NO_SPACES`, `E_SPACE_PATH_MISSING`, `E_SCHEMA_*`, +Other codes (`E_CONFIG_INVALID`, `E_INCLUDE_NOT_FOUND`, `E_SPACE_PATH_MISSING`, `E_SCHEMA_*`, `E_SPACE_EXISTS`, `E_CONFIG_NEEDS_MANUAL_EDIT`) carry their fix in the message. Do not edit the user's files to -get around a setup problem. +get around a setup problem. `sctx spaces` and the session start check cover the config only. A space's schema +is checked when it is loaded, so a broken schema first shows as `E_SCHEMA_*` from `sctx validate`, or as an +`E_HOOK_FAILED` message from a hook. If edits are not being checked and nothing says why, run `sctx spaces --json` from the session's folder. A config that is only in a folder below it will not be found. diff --git a/src/commands/spaces.ts b/src/commands/spaces.ts index 362abea..ae6416f 100644 --- a/src/commands/spaces.ts +++ b/src/commands/spaces.ts @@ -1,6 +1,5 @@ import { basename, resolve } from 'node:path'; -import { loadConfig } from '../config'; -import { checkConfig, hasBlockingProblem } from '../config/health'; +import { hasBlockingProblem, inspectConfig } from '../config/health'; import { addSpace } from '../config/write'; import { SctxError } from '../errors'; @@ -10,7 +9,7 @@ function renderConfigValue(v: unknown): string { } export function listSpaces(options: { json?: boolean } = {}): void { - const health = checkConfig(); + const { health, config } = inspectConfig(); if (options.json) { console.log(JSON.stringify(health)); if (hasBlockingProblem(health)) process.exitCode = 1; @@ -25,9 +24,8 @@ export function listSpaces(options: { json?: boolean } = {}): void { } console.log(''); if (hasBlockingProblem(health)) process.exitCode = 1; - if (!health.config.exists) return; } - const config = loadConfig(); + if (!config) return; if (health.problems.length === 0) console.log(`Config: ${path} (${health.config.source})\n`); for (const space of config.spaces) { console.log(`${space.name}`); diff --git a/src/config/health.ts b/src/config/health.ts index 9a4c0c2..02fcd66 100644 --- a/src/config/health.ts +++ b/src/config/health.ts @@ -1,8 +1,7 @@ -import { existsSync, readFileSync } from 'node:fs'; -import JSON5 from 'json5'; +import { existsSync } from 'node:fs'; import { LOCAL_CONFIG_FILE } from '../constants'; import { SctxError, type SctxErrorCode } from '../errors'; -import { getConfigSourceFiles, loadConfig, type ResolvedConfigPath, resolveConfigPath, resolveSchema } from '.'; +import { type Config, getConfigSourceFiles, loadConfig, type ResolvedConfigPath, resolveConfigPath } from '.'; export type ConfigProblem = { code: SctxErrorCode; @@ -45,10 +44,11 @@ function problem( } /** - * Check that the config for the working directory can be found and loaded, and that each space's - * path and schema exist. Never throws: every failure becomes a problem with a stable code. + * Find and load the config for the working directory, reporting failures as problems with stable + * codes instead of throwing. It reports on the config only: what a space's `path` means belongs to + * the plugin that reads it, and a schema is checked when it is loaded. */ -export function checkConfig(options: { startDir?: string } = {}): ConfigHealth { +export function inspectConfig(options: { startDir?: string } = {}): { health: ConfigHealth; config?: Config } { const resolved = resolveConfigPath(options.startDir); const exists = existsSync(resolved.path); const health: ConfigHealth = { config: { ...resolved, exists }, configFiles: [], spaces: [], problems: [] }; @@ -59,71 +59,23 @@ export function checkConfig(options: { startDir?: string } = {}): ConfigHealth { ? `No ${LOCAL_CONFIG_FILE} found from the working directory upward, and no global config at ${resolved.path}` : `Config file not found: ${resolved.path}`; health.problems.push(problem('E_CONFIG_NOT_FOUND', resolved.source === 'none' ? 'info' : 'error', detail)); - return health; + return { health }; } - let config: ReturnType; + let config: Config; try { config = loadConfig({ startDir: options.startDir }); } catch (err) { const code = err instanceof SctxError ? err.code : 'E_CONFIG_INVALID'; health.problems.push(problem(code, 'error', (err as Error).message)); - return health; + return { health }; } health.configFiles = [...getConfigSourceFiles()]; health.spaces = config.spaces.map((s) => ({ name: s.name, path: s.path, schema: s.schema ?? config.schema })); - - if (config.spaces.length === 0) { - health.problems.push(problem('E_NO_SPACES', 'warning', `Config ${resolved.path} defines no spaces`)); - } - - for (const space of config.spaces) { - if (!existsSync(space.path)) { - health.problems.push( - problem( - 'E_SPACE_PATH_MISSING', - 'error', - `Space "${space.name}" path does not exist: ${space.path}`, - space.name, - ), - ); - } - const schemaRef = space.schema ?? config.schema; - if (!schemaRef) { - health.problems.push(problem('E_SCHEMA_MISSING', 'error', `Space "${space.name}" has no schema`, space.name)); - continue; - } - let schemaPath: string; - try { - schemaPath = resolveSchema(config, space); - } catch (err) { - health.problems.push(problem('E_SCHEMA_NOT_FOUND', 'error', (err as Error).message, space.name)); - continue; - } - if (/^https?:\/\//i.test(schemaPath)) continue; - if (!existsSync(schemaPath)) { - health.problems.push( - problem('E_SCHEMA_NOT_FOUND', 'error', `Space "${space.name}" schema not found: ${schemaPath}`, space.name), - ); - continue; - } - try { - JSON5.parse(readFileSync(schemaPath, 'utf-8')); - } catch (err) { - health.problems.push( - problem( - 'E_SCHEMA_INVALID', - 'error', - `Space "${space.name}" schema ${schemaPath} is not valid: ${(err as Error).message}`, - space.name, - ), - ); - } - } - return health; + return { health, config }; } -/** True when the health check found something that stops validation from running. */ +/** True when the config problems stop validation from running. */ export function hasBlockingProblem(health: ConfigHealth): boolean { return health.problems.some((p) => p.severity === 'error'); } diff --git a/tests/commands/spaces-config-only.test.ts b/tests/commands/spaces-config-only.test.ts new file mode 100644 index 0000000..d818f2f --- /dev/null +++ b/tests/commands/spaces-config-only.test.ts @@ -0,0 +1,58 @@ +import { afterAll, describe, expect, it } from 'bun:test'; +import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const ROOT = join(import.meta.dir, '..', '..'); +const dir = realpathSync(mkdtempSync(join(tmpdir(), 'sctx-spaces-'))); +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +function spaces(config: unknown, ...args: string[]) { + writeFileSync(join(dir, '.sctx.json'), typeof config === 'string' ? config : JSON.stringify(config)); + const { SCTX_CONFIG: _config, SCTX_BIN: _bin, ...env } = process.env; + const result = Bun.spawnSync(['bun', 'run', join(ROOT, 'src/index.ts'), 'spaces', ...args], { + cwd: dir, + env: { ...env, XDG_CONFIG_HOME: dir, HOME: dir }, + stdout: 'pipe', + stderr: 'pipe', + }); + return { code: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() }; +} + +describe('spaces reports the config, not the spaces', () => { + const odd = { + spaces: [ + { + name: 'remote', + path: 'https://example.atlassian.net/wiki/spaces/X/pages/1/Page', + schema: 'strategy_general.json', + }, + { name: 'moved', path: 'nowhere', schema: 'strategy_general.json' }, + { name: 'unset', path: '.' }, + ], + }; + + it('lists every space without problems or a failing exit code', () => { + const r = spaces(odd, '--json'); + const out = JSON.parse(r.stdout); + + expect(r.code).toBe(0); + expect(out.problems).toEqual([]); + expect(out.spaces.map((s: { name: string }) => s.name)).toEqual(['remote', 'moved', 'unset']); + }); + + it('prints the same in text mode', () => { + const r = spaces(odd); + + expect(r.code).toBe(0); + expect(r.stdout).toContain('remote'); + expect(r.stdout).not.toContain('E_'); + }); + + it('still fails with a code when the config itself is invalid', () => { + const r = spaces('{ not json', '--json'); + + expect(r.code).toBe(1); + expect(JSON.parse(r.stdout).problems[0].code).toBe('E_CONFIG_INVALID'); + }); +}); diff --git a/tests/config/health.test.ts b/tests/config/health.test.ts index 9f84b1b..4b2e93e 100644 --- a/tests/config/health.test.ts +++ b/tests/config/health.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'bun:test'; import { readFileSync, symlinkSync } from 'node:fs'; import { join } from 'node:path'; import { setConfigPath } from '../../src/config'; -import { checkConfig, hasBlockingProblem } from '../../src/config/health'; +import { hasBlockingProblem, inspectConfig } from '../../src/config/health'; import { addSpace, resolveWriteTarget } from '../../src/config/write'; import { LOCAL_CONFIG_FILE } from '../../src/constants'; import { SctxError } from '../../src/errors'; @@ -10,9 +10,9 @@ import { useConfigEnv, writeJson as write } from '../helpers/config-env'; const env = useConfigEnv(); -describe('checkConfig', () => { +describe('inspectConfig', () => { it('reports "not set up" as info, not as a failure', () => { - const health = checkConfig({ startDir: env.vault }); + const { health } = inspectConfig({ startDir: env.vault }); expect(health.config.source).toBe('none'); expect(health.problems.map((p) => [p.code, p.severity])).toEqual([['E_CONFIG_NOT_FOUND', 'info']]); @@ -22,7 +22,7 @@ describe('checkConfig', () => { it('reports a missing explicit config as an error', () => { setConfigPath(join(env.root, 'missing.json')); - const health = checkConfig(); + const { health } = inspectConfig(); expect(health.problems[0]).toMatchObject({ code: 'E_CONFIG_NOT_FOUND', severity: 'error' }); expect(hasBlockingProblem(health)).toBe(true); @@ -31,30 +31,46 @@ describe('checkConfig', () => { it('reports invalid JSON with a code and a fix', () => { write(join(env.vault, LOCAL_CONFIG_FILE), '{ not json'); - const health = checkConfig({ startDir: env.vault }); + const { health, config } = inspectConfig({ startDir: env.vault }); expect(health.problems[0]).toMatchObject({ code: 'E_CONFIG_INVALID', severity: 'error' }); expect(health.problems[0]?.fix).not.toBe(''); + expect(config).toBeUndefined(); }); - it('reports a moved space path and a missing schema per space', () => { + it('reports a missing include', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { includeSpacesFrom: ['./nope.json'], spaces: [] }); + + const { health } = inspectConfig({ startDir: env.vault }); + + expect(health.problems[0]).toMatchObject({ code: 'E_INCLUDE_NOT_FOUND', severity: 'error' }); + }); + + it('leaves what a space is to the plugin and the schema loader: path and schema are not checked', () => { write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [ + { + name: 'remote', + path: 'https://example.atlassian.net/wiki/spaces/X/pages/1/Page', + schema: 'knowledge_wiki.json', + }, { name: 'gone', path: 'nope', schema: 'knowledge_wiki.json' }, { name: 'noschema', path: '.' }, { name: 'badschema', path: '.', schema: 'does_not_exist.json' }, ], }); - const codes = checkConfig({ startDir: env.vault }).problems.map((p) => `${p.space}:${p.code}`); + const { health, config } = inspectConfig({ startDir: env.vault }); - expect(codes).toEqual(['gone:E_SPACE_PATH_MISSING', 'noschema:E_SCHEMA_MISSING', 'badschema:E_SCHEMA_NOT_FOUND']); + expect(health.problems).toEqual([]); + expect(health.spaces.map((s) => s.name)).toEqual(['remote', 'gone', 'noschema', 'badschema']); + expect(config?.spaces).toHaveLength(4); }); it('is clean for a healthy space', () => { write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [{ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }] }); - const health = checkConfig({ startDir: env.vault }); + const { health } = inspectConfig({ startDir: env.vault }); expect(health.problems).toEqual([]); expect(health.spaces[0]?.name).toBe('wiki');