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
34 changes: 29 additions & 5 deletions hook-test/unit/preflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion plugin/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
15 changes: 8 additions & 7 deletions plugin/scripts/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,6 @@ export async function runSctx(args: string[], options?: HookOptions): Promise<Sc
}
}

async function sctx(args: string[], options?: HookOptions): Promise<string> {
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 {
Expand Down Expand Up @@ -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<Record<string, FileIssues>> {
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<string, FileIssues> = {};
const issuesFor = (label: string): FileIssues => {
Expand Down
2 changes: 1 addition & 1 deletion plugin/skills/setup-space/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <folder holding the files>/.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.
8 changes: 3 additions & 5 deletions src/commands/spaces.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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;
Expand All @@ -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}`);
Expand Down
70 changes: 11 additions & 59 deletions src/config/health.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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: [] };
Expand All @@ -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<typeof loadConfig>;
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');
}
58 changes: 58 additions & 0 deletions tests/commands/spaces-config-only.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
34 changes: 25 additions & 9 deletions tests/config/health.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ 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';
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']]);
Expand All @@ -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);
Expand All @@ -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');
Expand Down
Loading