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
38 changes: 38 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,44 @@ With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json`

- **`path`** — directory or single `.json`/`.json5`/`.jsonl` file to read instead of the space's `path` (relative paths resolve from the config root).

## Validation severity overrides

Set `validation.severity` per space to change how validation checks and rules are reported. Each value is `error`, `warning`, `info`, or `ignore` (`ignore` omits the issue from reported output).

```json
{
"spaces": [
{
"name": "mixed-kb",
"path": "/path/to/kb",
"schema": "knowledge_wiki.json",
"validation": {
"severity": {
"no-type": "info",
"invalid-type": "info",
"content-link": "ignore",
"rules": {
"opportunity-has-outcome": "info",
"solution-quantity": "ignore",
"outcome-is-behavioural": {
"output-framed": "warning",
"missing-context": "ignore"
}
}
}
}
}
]
}
```

Supported keys under `validation.severity`:

- **Check keys:** `parse`, `no-type`, `invalid-type`, `schema`, `duplicate`, `broken-link`, `hierarchy`, `content-link`, `gated`. `no-type` overrides untyped files (falling back to `parse`), and `invalid-type` overrides unknown `type` values (falling back to `schema`).
- **`rules`:** maps a rule id to a severity level, `ignore`, or (for semantic rules) a per-verdict map that merges onto the rule's `semantic.severity`.

Only `error` issues fail validation and trigger cascade gating. Downgrading a check or rule below `error` lets validation pass and stops it from gating descendants.

## Filter views

Named filter expressions can be defined per space under `views`. Each view has an `expression` field:
Expand Down
2 changes: 1 addition & 1 deletion docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Prefer choosing the right category and relying on its default. Set `severity` on
}
```

`sctx schemas show` lists each category with its default severity and marks rules that override it.
`sctx schemas show` lists each category with its default severity and marks rules that override it. To adjust severities per space without editing the schema, set `validation.severity` in config (see [config.md](config.md#validation-severity-overrides)).

## Selecting nodes

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.27.6",
"version": "0.27.7",
"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
2 changes: 1 addition & 1 deletion plugin/skills/structured-context/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ These defaults apply unless the project's instructions say what you may change w

- **Fix gates first.** A `gated` issue names the node whose failure suppressed its rules (`gatedBy`). Fix that node and re-validate, rather than working on the nodes it gated.
- **Fix mechanical issues** (`parse`, `schema`, `duplicate`, `broken-link`, `hierarchy`) when the schema and the content make the correct value clear. Ask when they don't, for example when a node could take more than one parent or enum value.
- **Bring rule violations to the user.** Read the rule's category and description in `schemas show --space <name>`. Offer the remedies that fit: edit the content, change the schema, or leave it.
- **Bring rule violations to the user.** Read the rule's category and description in `schemas show --space <name>`. Offer the remedies that fit: edit the content, lower or ignore the rule in space config (`validation.severity`, see `sctx docs config`), change the schema, or leave it.
- **Re-validate** after each change.

When one run reports many issues, follow `references/fix-loop.md`.
Expand Down
3 changes: 2 additions & 1 deletion plugin/skills/structured-context/references/fix-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ Use this loop when one run reports many issues at once. This happens after setti
## Fix the cause, not each file

- **Other field or type names:** when many files fail because they use another field name or type name, map the names before rewriting files. Use `fieldMap` or `typeInference` in the space config (`sctx docs config`), or type `aliases` in the schema. Rewrite the files only when the user wants the content itself to change.
- **Broad class of issues or strict rule:** when a check (such as `no-type` or `invalid-type` in a mixed knowledge base) or a rule fires across many nodes and the user agrees to relax it temporarily or permanently, lower its severity by one or two levels (or set it to `ignore`) under `validation.severity` in space config (`sctx docs config`).
- **A schema that does not fit:** when a constraint or rule fails on most nodes of a type, the schema may be wrong rather than the content. Check what the rule sees with `sctx dump`, then propose a schema change. Change a local schema (in `.sctx/schemas/`), not a bundled one.

## Presenting decisions

Group decisions by cause, such as one rule or one missing field, not by file. For each group, give:

- What fails, how many nodes, and two or three examples.
- The remedies that fit: edit the content (say how), change the schema (say what), or leave it.
- The remedies that fit: edit the content (say how), lower or ignore the check/rule in space config (`validation.severity`), change the schema (say what), or leave it.
- A recommended remedy.

The user can then answer each group in one line, for example "fix group 1 as recommended, change the schema for group 2, leave group 3".
50 changes: 50 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
resolveSpacePluginSchemas,
shortenPluginName,
} from '../plugins/util';
import { type RuleSemantic, VERDICT_SEVERITY_SCHEMA } from '../schema/metadata-contract';
import { bundledSchemasDir } from '../schema/schema';
import { configFileIn, configRoot, globalConfigPath, resourceDir, SCHEMAS_RESOURCE } from './layout';

Expand All @@ -36,6 +37,36 @@ const SEMANTIC_CONFIG_SCHEMA = {
additionalProperties: false,
} as const;

const VALIDATION_SEVERITY_SCHEMA = {
type: 'object',
properties: {
parse: VERDICT_SEVERITY_SCHEMA,
'no-type': VERDICT_SEVERITY_SCHEMA,
'invalid-type': VERDICT_SEVERITY_SCHEMA,
schema: VERDICT_SEVERITY_SCHEMA,
duplicate: VERDICT_SEVERITY_SCHEMA,
'broken-link': VERDICT_SEVERITY_SCHEMA,
hierarchy: VERDICT_SEVERITY_SCHEMA,
'content-link': VERDICT_SEVERITY_SCHEMA,
gated: VERDICT_SEVERITY_SCHEMA,
rules: {
type: 'object',
additionalProperties: {
oneOf: [VERDICT_SEVERITY_SCHEMA, { type: 'object', additionalProperties: VERDICT_SEVERITY_SCHEMA }],
},
},
},
additionalProperties: false,
} as const;

const VALIDATION_CONFIG_SCHEMA = {
type: 'object',
properties: {
severity: VALIDATION_SEVERITY_SCHEMA,
},
additionalProperties: false,
} as const;

const CONFIG_SCHEMA = {
type: 'object',
properties: {
Expand All @@ -58,6 +89,7 @@ const CONFIG_SCHEMA = {
},
},
semantic: SEMANTIC_CONFIG_SCHEMA,
validation: VALIDATION_CONFIG_SCHEMA,
},
required: ['name', 'path'],
additionalProperties: false,
Expand All @@ -72,6 +104,22 @@ const CONFIG_SCHEMA = {
additionalProperties: false,
};

type SeverityOverrideValue = NonNullable<RuleSemantic['severity']>[string];
type ValidationConfig = {
severity?: {
parse?: SeverityOverrideValue;
'no-type'?: SeverityOverrideValue;
'invalid-type'?: SeverityOverrideValue;
schema?: SeverityOverrideValue;
duplicate?: SeverityOverrideValue;
'broken-link'?: SeverityOverrideValue;
hierarchy?: SeverityOverrideValue;
'content-link'?: SeverityOverrideValue;
gated?: SeverityOverrideValue;
rules?: Record<string, SeverityOverrideValue | Record<string, SeverityOverrideValue>>;
};
};

export type SpaceConfig = {
name: string;
path: string;
Expand All @@ -82,6 +130,8 @@ export type SpaceConfig = {
views?: Record<string, { expression: string }>;
/** Model provider for this space's semantic rules; overrides the top-level `semantic`. */
semantic?: JudgeConfig;
/** Per-space validation settings (such as severity overrides). */
validation?: ValidationConfig;
/**
* Root of the config file that defined this space (see `configRoot`), used to anchor relative
* plugin-config paths and find plugins. Set by loadConfig; absent for a hand-assembled Config, whose callers must pass an
Expand Down
2 changes: 1 addition & 1 deletion src/judge/verdicts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function resolveSemanticRule(rule: Rule): ResolvedSemanticRule {
}
mapping = semantic.severity;
} else {
mapping = { ...semantic.severity, fail: ruleSeverity(rule) };
mapping = { fail: ruleSeverity(rule), ...semantic.severity };
}

const reserved: readonly string[] = RESERVED_VERDICTS;
Expand Down
2 changes: 1 addition & 1 deletion src/schema/metadata-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const RESERVED_VERDICTS = ['missing-context'] as const;
/** Related-node kinds a semantic rule's `scope` can add: main-hierarchy edges only. `branch` is ancestors plus descendants. */
export const SEMANTIC_SCOPES = ['parent', 'siblings', 'children', 'ancestors', 'descendants', 'branch'] as const;

const VERDICT_SEVERITY_SCHEMA = { enum: ['error', 'warning', 'info', 'ignore'] } as const;
export const VERDICT_SEVERITY_SCHEMA = { enum: ['error', 'warning', 'info', 'ignore'] } as const;

/** The semantic part of a rule: a model evaluates the node against a rubric and returns a verdict. */
const SEMANTIC_SCHEMA = {
Expand Down
76 changes: 52 additions & 24 deletions src/validate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
ValidationIssue,
} from '../types';
import { formatErrors, resolveIssueLocation } from './format-errors';
import { applyIssueSeverity, applyRuleSeverityOverrides } from './severity-overrides';
import { validateGraph } from './validate-graph';

// ============================================================================
Expand Down Expand Up @@ -118,9 +119,10 @@ export async function validateSpace(
}

const result = await validateNodes(context, nodes, readResult, runOptions);
const overrides = context.space.validation?.severity;
// Parse issues enter after node validation, but share the same run-wide dedupe contract.
const allIssues = new IssueCollector();
allIssues.addAll(parseIssuesOf(readResult.parseIssues));
allIssues.addAll(parseIssuesOf(readResult.parseIssues, overrides));
allIssues.addAll(result.issues);
result.issues = allIssues.issues;
result.skippedByDepth = skippedByDepth;
Expand Down Expand Up @@ -195,8 +197,9 @@ export async function validateNodes(

// Pre-extract valid types for early type validation
const validTypes = Array.isArray(schema.oneOf) ? extractEntityInfo(schema, schemaRefRegistry).map((e) => e.type) : [];
const overrides = context.space.validation?.severity;

const collected = new IssueCollector();
const collected = new IssueCollector(overrides);
let validCount = 0;

for (const node of nodes) {
Expand Down Expand Up @@ -254,9 +257,6 @@ export async function validateNodes(
// Validate all hierarchy constraints (field references and structure)
const hierarchyIssues = validateGraph(nodes, metadata, unresolvedRefs, fieldSources);
collected.addAll(hierarchyIssues);
const hierarchyFailureNodes = hierarchyIssues
.filter((issue) => issue.kind === 'hierarchy')
.map((issue) => issue.nodeId);

// Calculate orphans across every hierarchy (informational, not a validation error)
const orphans: SpaceNode[] = [];
Expand All @@ -270,9 +270,13 @@ export async function validateNodes(
options.cacheMode === 'only' ? [] : undefined;
if (metadata.rules) {
const failedNodes: FailedNodes = new Map();
for (const { nodeId } of collected.ofKind('schema')) failedNodes.set(nodeId, 'schema');
for (const nodeId of hierarchyFailureNodes) if (!failedNodes.has(nodeId)) failedNodes.set(nodeId, 'hierarchy');
const evaluation = await evaluateSpaceRules(nodes, context, failedNodes, options);
for (const issue of collected.ofKind('schema')) {
if (issue.severity === 'error') failedNodes.set(issue.nodeId, 'schema');
}
for (const issue of collected.ofKind('hierarchy')) {
if (issue.severity === 'error' && !failedNodes.has(issue.nodeId)) failedNodes.set(issue.nodeId, 'hierarchy');
}
const evaluation = await evaluateSpaceRules(nodes, context, failedNodes, options, overrides?.rules);
collected.addAll(evaluation.issues);
if (evaluation.trimReport) contextTrimmed = summariseTrim(evaluation.trimReport);
if (evaluation.uncachedSemantic.length > 0) uncachedSemantic = evaluation.uncachedSemantic;
Expand Down Expand Up @@ -312,15 +316,24 @@ async function evaluateSpaceRules(
schemaContext: Pick<SpaceContext, 'schema' | 'schemaRefRegistry'>,
failedNodes: FailedNodes,
options: ValidationOptions = {},
ruleOverrides?: Parameters<typeof applyRuleSeverityOverrides>[1],
): Promise<RuleEvaluationResult> {
const { metadata } = schemaContext.schema;
const rules = metadata.rules && filterRules(metadata.rules, options.ruleFilter);
if (!rules) return { issues: [], uncachedSemantic: [] };
if (!metadata.rules) return { issues: [], uncachedSemantic: [] };
const { rules: adjusted, ignoredExpressionRuleIds } = applyRuleSeverityOverrides(metadata.rules, ruleOverrides);
const rules = filterRules(adjusted, options.ruleFilter);
const graph = buildSpaceGraph(nodes, metadata.hierarchy);
return evaluateRules(nodes, rules, graph, failedNodes, {
const result = await evaluateRules(nodes, rules, graph, failedNodes, {
...options,
judge: options.judge && { ...options.judge, schemaContext },
});
if (ignoredExpressionRuleIds.size === 0) return result;
return {
...result,
issues: result.issues.filter(
(issue) => !(issue.kind === 'rule' && issue.verdict === undefined && ignoredExpressionRuleIds.has(issue.ruleId)),
),
};
}

// ============================================================================
Expand Down Expand Up @@ -390,8 +403,9 @@ export async function validateResolvedFileWith(
...validationOptions,
judge: validationOptions.judge && { ...validationOptions.judge, targets: fileNodeIds },
});
const overrides = context.space.validation?.severity;
const issues = [
...parseIssuesOf(readResult.parseIssues).filter((issue) => issue.source?.file === label),
...parseIssuesOf(readResult.parseIssues, overrides).filter((issue) => issue.source?.file === label),
...result.issues.filter((issue) => issue.nodeId !== undefined && fileNodeIds.has(issue.nodeId)),
];
const errorCount = issues.filter((issue) => issue.severity === 'error').length;
Expand Down Expand Up @@ -425,12 +439,15 @@ const summariseTrim = (
class IssueCollector {
private readonly seen = new Set<string>();
readonly issues: ValidationIssue[] = [];
constructor(private readonly overrides?: NonNullable<SpaceConfig['validation']>['severity']) {}
add(issue: ValidationIssue): void {
const scope = issue.nodeId ?? (issue.kind === 'parse' ? issue.source.file : '');
const dedupe = `${scope}\0${issue.key}`;
const adjusted = applyIssueSeverity(issue, this.overrides);
if (!adjusted) return;
const scope = adjusted.nodeId ?? (adjusted.kind === 'parse' ? adjusted.source.file : '');
const dedupe = `${scope}\0${adjusted.key}`;
if (this.seen.has(dedupe)) return;
this.seen.add(dedupe);
this.issues.push(issue);
this.issues.push(adjusted);
}
addAll(issues: Iterable<ValidationIssue>): void {
for (const issue of issues) this.add(issue);
Expand Down Expand Up @@ -466,13 +483,24 @@ export function findDuplicateIds(nodes: SpaceNode[]): Extract<ValidationIssue, {
}

/** The issues for the files a plugin excluded or could not parse. */
function parseIssuesOf(parseIssues: ParseIssue[]): ValidationIssue[] {
return parseIssues.map(({ message, source, severity, type }) => ({
kind: 'parse' as const,
key: `parse:${type}`,
severity,
message: message ?? (type === 'no-type' ? 'No type field' : `Excluded during parsing (${type})`),
source,
type,
}));
function parseIssuesOf(
parseIssues: ParseIssue[],
overrides?: NonNullable<SpaceConfig['validation']>['severity'],
): ValidationIssue[] {
const issues: ValidationIssue[] = [];
for (const { message, source, severity, type } of parseIssues) {
const issue = applyIssueSeverity(
{
kind: 'parse' as const,
key: `parse:${type}`,
severity,
message: message ?? (type === 'no-type' ? 'No type field' : `Excluded during parsing (${type})`),
source,
type,
},
overrides,
);
if (issue) issues.push(issue);
}
return issues;
}
Loading