From 33050ed2e78ad2a7863bc91aa7272b3be22ffba4 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 09:59:13 +1100 Subject: [PATCH] Allow config overrides of validation severity --- docs/config.md | 38 +++ docs/rules.md | 2 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/skills/structured-context/SKILL.md | 2 +- .../structured-context/references/fix-loop.md | 3 +- src/config/index.ts | 50 ++++ src/judge/verdicts.ts | 2 +- src/schema/metadata-contract.ts | 2 +- src/validate/index.ts | 76 ++++-- src/validate/severity-overrides.ts | 100 +++++++ tests/validate/severity-overrides.test.ts | 248 ++++++++++++++++++ 11 files changed, 495 insertions(+), 30 deletions(-) create mode 100644 src/validate/severity-overrides.ts create mode 100644 tests/validate/severity-overrides.test.ts diff --git a/docs/config.md b/docs/config.md index 69b41671..32aac0d8 100644 --- a/docs/config.md +++ b/docs/config.md @@ -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: diff --git a/docs/rules.md b/docs/rules.md index 6d8ffa64..819c25cf 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -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 diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 5fabea0d..7cf9b856 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -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", diff --git a/plugin/skills/structured-context/SKILL.md b/plugin/skills/structured-context/SKILL.md index a21e0325..af50ff72 100644 --- a/plugin/skills/structured-context/SKILL.md +++ b/plugin/skills/structured-context/SKILL.md @@ -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 `. 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 `. 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`. diff --git a/plugin/skills/structured-context/references/fix-loop.md b/plugin/skills/structured-context/references/fix-loop.md index 2f102381..d6695ae5 100644 --- a/plugin/skills/structured-context/references/fix-loop.md +++ b/plugin/skills/structured-context/references/fix-loop.md @@ -19,6 +19,7 @@ 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 @@ -26,7 +27,7 @@ Use this loop when one run reports many issues at once. This happens after setti 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". diff --git a/src/config/index.ts b/src/config/index.ts index 5f3e5297..a7c88b67 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -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'; @@ -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: { @@ -58,6 +89,7 @@ const CONFIG_SCHEMA = { }, }, semantic: SEMANTIC_CONFIG_SCHEMA, + validation: VALIDATION_CONFIG_SCHEMA, }, required: ['name', 'path'], additionalProperties: false, @@ -72,6 +104,22 @@ const CONFIG_SCHEMA = { additionalProperties: false, }; +type SeverityOverrideValue = NonNullable[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>; + }; +}; + export type SpaceConfig = { name: string; path: string; @@ -82,6 +130,8 @@ export type SpaceConfig = { views?: Record; /** 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 diff --git a/src/judge/verdicts.ts b/src/judge/verdicts.ts index 732cc78b..4311b5b3 100644 --- a/src/judge/verdicts.ts +++ b/src/judge/verdicts.ts @@ -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; diff --git a/src/schema/metadata-contract.ts b/src/schema/metadata-contract.ts index 1cb90645..89605266 100644 --- a/src/schema/metadata-contract.ts +++ b/src/schema/metadata-contract.ts @@ -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 = { diff --git a/src/validate/index.ts b/src/validate/index.ts index 2f05bd90..4a80611a 100644 --- a/src/validate/index.ts +++ b/src/validate/index.ts @@ -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'; // ============================================================================ @@ -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; @@ -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) { @@ -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[] = []; @@ -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; @@ -312,15 +316,24 @@ async function evaluateSpaceRules( schemaContext: Pick, failedNodes: FailedNodes, options: ValidationOptions = {}, + ruleOverrides?: Parameters[1], ): Promise { 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)), + ), + }; } // ============================================================================ @@ -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; @@ -425,12 +439,15 @@ const summariseTrim = ( class IssueCollector { private readonly seen = new Set(); readonly issues: ValidationIssue[] = []; + constructor(private readonly overrides?: NonNullable['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): void { for (const issue of issues) this.add(issue); @@ -466,13 +483,24 @@ export function findDuplicateIds(nodes: SpaceNode[]): Extract ({ - 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['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; } diff --git a/src/validate/severity-overrides.ts b/src/validate/severity-overrides.ts new file mode 100644 index 00000000..7cfca286 --- /dev/null +++ b/src/validate/severity-overrides.ts @@ -0,0 +1,100 @@ +import type { SpaceConfig } from '../config'; +import { ruleSemantic } from '../rule/rule-severity'; +import type { Rule, RuleSemantic } from '../schema/metadata-contract'; +import type { ValidationIssue } from '../types'; + +type SeverityOverrides = NonNullable['severity']>; +type SeverityValue = NonNullable[string]; + +function overrideForIssue(issue: ValidationIssue, overrides: SeverityOverrides): SeverityValue | undefined { + switch (issue.kind) { + case 'parse': + return issue.type === 'no-type' ? (overrides['no-type'] ?? overrides.parse) : overrides.parse; + case 'schema': + return issue.key.startsWith('schema:type:') ? (overrides['invalid-type'] ?? overrides.schema) : overrides.schema; + case 'duplicate': + return overrides.duplicate; + case 'broken-link': + return overrides['broken-link']; + case 'hierarchy': + return overrides.hierarchy; + case 'content-link': + return overrides['content-link']; + case 'gated': + return overrides.gated; + case 'rule': + return undefined; + } +} + +/** Apply non-rule severity overrides to an issue. Returns null when overridden to `ignore`. */ +export function applyIssueSeverity( + issue: ValidationIssue, + overrides: SeverityOverrides | undefined, +): ValidationIssue | null { + if (!overrides) return issue; + const override = overrideForIssue(issue, overrides); + if (override === undefined) return issue; + if (override === 'ignore') return null; + return { ...issue, severity: override }; +} + +/** + * Apply config `validation.severity.rules` overrides to schema rules before filtering and evaluation. + * Returns the adjusted rules and the set of rule ids whose expression violations should be suppressed (`ignore`). + */ +export function applyRuleSeverityOverrides( + rules: Rule[], + ruleOverrides: SeverityOverrides['rules'], +): { rules: Rule[]; ignoredExpressionRuleIds: Set } { + const ignoredExpressionRuleIds = new Set(); + if (!ruleOverrides || Object.keys(ruleOverrides).length === 0) { + return { rules, ignoredExpressionRuleIds }; + } + + const adjusted = rules.map((rule) => { + const override = ruleOverrides[rule.id]; + if (override === undefined) return rule; + + const semantic = ruleSemantic(rule); + if (semantic) { + if (typeof override === 'string') { + const nextSemanticSeverity: Record = { ...semantic.severity }; + if (semantic.verdicts) { + for (const [verdict, sev] of Object.entries(nextSemanticSeverity)) { + if (sev !== 'ignore') nextSemanticSeverity[verdict] = override; + } + } else { + nextSemanticSeverity.fail = override; + } + if (override === 'ignore' && rule.expression !== undefined) { + ignoredExpressionRuleIds.add(rule.id); + } + return { + ...rule, + ...(override !== 'ignore' ? { severity: override } : {}), + semantic: { ...semantic, severity: nextSemanticSeverity }, + }; + } + + // Verdict map override: merge onto semantic.severity. + return { + ...rule, + semantic: { ...semantic, severity: { ...semantic.severity, ...override } }, + }; + } + + // Deterministic rule (no semantic part) + if (typeof override === 'string') { + if (override === 'ignore') { + ignoredExpressionRuleIds.add(rule.id); + return { ...rule, gatesDescendants: false }; + } + return { ...rule, severity: override }; + } + + return rule; + }); + + return { rules: adjusted, ignoredExpressionRuleIds }; +} diff --git a/tests/validate/severity-overrides.test.ts b/tests/validate/severity-overrides.test.ts new file mode 100644 index 00000000..b06692fe --- /dev/null +++ b/tests/validate/severity-overrides.test.ts @@ -0,0 +1,248 @@ +import { afterAll, describe, expect, it } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { type Config, loadConfig, setConfigPath } from '../../src/config'; +import type { SemanticJudgeProvider } from '../../src/judge/types'; +import { readSpace } from '../../src/read/read-space'; +import { createSpaceContext } from '../../src/space-context'; +import type { FileValidationResult } from '../../src/types'; +import { validateFile, validateNodes, validateSpace } from '../../src/validate'; +import { ofKind } from '../helpers/issues'; + +const META = + 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; + +describe('config validation.severity overrides', () => { + const dir = mkdtempSync(join(tmpdir(), 'sctx-severity-overrides-')); + afterAll(() => { + setConfigPath(undefined); + rmSync(dir, { recursive: true, force: true }); + }); + + const schemaPath = join(dir, 'schema.json'); + writeFileSync( + schemaPath, + JSON.stringify({ + $schema: META, + $id: 'sctx://severity-overrides.test', + $metadata: { + hierarchy: { + levels: [{ type: 'goal' }, { type: 'task' }], + }, + rules: [ + { + id: 'goal-must-have-owner', + category: 'validation', + description: 'Goal must declare owner', + type: 'goal', + expression: '$exists(current.owner)', + }, + { + id: 'task-has-estimate', + category: 'workflow', + description: 'Task should have an estimate', + type: 'task', + expression: '$exists(current.estimate)', + }, + { + id: 'goal-quality', + category: 'coherence', + description: 'Goal should be clear', + type: 'goal', + semantic: { + verdicts: { + clear: 'Goal is clear.', + vague: 'Goal is vague.', + unbounded: 'Goal has no scope.', + }, + severity: { + vague: 'warning', + unbounded: 'error', + }, + }, + }, + { + id: 'task-tone', + category: 'coherence', + description: 'Task tone check', + type: 'task', + semantic: true, + }, + ], + }, + oneOf: [ + { + type: 'object', + properties: { type: { const: 'goal' }, title: { type: 'string' }, owner: { type: 'string' } }, + required: ['type', 'title'], + }, + { + type: 'object', + properties: { + type: { const: 'task' }, + title: { type: 'string' }, + parent: { type: 'string' }, + estimate: { type: 'number' }, + }, + required: ['type', 'title'], + }, + ], + }), + ); + + const space = join(dir, 'space'); + mkdirSync(space, { recursive: true }); + writeFileSync(join(space, 'Untyped.md'), 'Plain markdown without frontmatter.\n'); + writeFileSync(join(space, 'OtherSchema.md'), ['---', 'type: opportunity', '---', ''].join('\n')); + writeFileSync(join(space, 'Goal.md'), ['---', 'type: goal', '---', 'See [[MissingContent]].\n'].join('\n')); + writeFileSync(join(space, 'Task.md'), ['---', 'type: task', 'parent: "[[Goal]]"', '---', ''].join('\n')); + + it('overrides non-rule checks (no-type, invalid-type, content-link) in both validateSpace and validateFile', async () => { + const config: Config = { + spaces: [ + { + name: 'kb', + path: space, + schema: schemaPath, + validation: { + severity: { + 'no-type': 'info', + 'invalid-type': 'info', + 'content-link': 'ignore', + rules: { + 'goal-must-have-owner': 'ignore', + 'task-has-estimate': 'ignore', + }, + }, + }, + }, + ], + }; + + const ctx = createSpaceContext('kb', config, { configDir: dir }); + const result = await validateSpace(ctx); + + const parseIssues = ofKind(result.issues, 'parse'); + expect(parseIssues).toHaveLength(1); + expect(parseIssues[0]?.severity).toBe('info'); + + const schemaIssues = ofKind(result.issues, 'schema'); + expect(schemaIssues).toHaveLength(1); + expect(schemaIssues[0]?.severity).toBe('info'); + + expect(ofKind(result.issues, 'content-link')).toHaveLength(0); + expect(result.issues.filter((i) => i.severity === 'error')).toHaveLength(0); + + // validateFile applies the same parse and schema overrides + const untypedFile = (await validateFile(join(space, 'Untyped.md'), ctx)) as FileValidationResult; + expect(untypedFile.issues[0]?.severity).toBe('info'); + expect(untypedFile.errorCount).toBe(0); + + const otherFile = (await validateFile(join(space, 'OtherSchema.md'), ctx)) as FileValidationResult; + expect(otherFile.issues[0]?.severity).toBe('info'); + expect(otherFile.errorCount).toBe(0); + }); + + it('overrides deterministic rule severities and updates cascade gating accordingly', async () => { + // Baseline: goal-must-have-owner (error) gates Task.md's task-has-estimate rule + const baseConfig: Config = { spaces: [{ name: 'kb', path: space, schema: schemaPath }] }; + const baseResult = await validateSpace(createSpaceContext('kb', baseConfig, { configDir: dir })); + expect(ofKind(baseResult.issues, 'gated').map((i) => String(i.nodeId))).toEqual(['Task.md']); + + // Lowering goal-must-have-owner to warning stops gating, and raising task-has-estimate to error fails Task.md + const overrideConfig: Config = { + spaces: [ + { + name: 'kb', + path: space, + schema: schemaPath, + validation: { + severity: { + rules: { + 'goal-must-have-owner': 'warning', + 'task-has-estimate': 'error', + }, + }, + }, + }, + ], + }; + + const result = await validateSpace(createSpaceContext('kb', overrideConfig, { configDir: dir })); + expect(ofKind(result.issues, 'gated')).toHaveLength(0); + const ruleIssues = ofKind(result.issues, 'rule'); + expect(ruleIssues.find((i) => i.ruleId === 'goal-must-have-owner')?.severity).toBe('warning'); + expect(ruleIssues.find((i) => i.ruleId === 'task-has-estimate')?.severity).toBe('error'); + }); + + it('merges semantic rule verdict overrides and runs ignored semantic rules without reporting', async () => { + const judgedRuleIds: string[] = []; + const provider: SemanticJudgeProvider = { + name: 'stub', + async evaluate(input) { + const out: Record = {}; + for (const rule of input.rules) { + judgedRuleIds.push(rule.id); + out[rule.id] = + rule.id === 'goal-quality' + ? { verdict: 'unbounded', evidence: 'No boundary stated.' } + : { verdict: 'fail', evidence: 'Too informal.' }; + } + return out; + }, + }; + + const config: Config = { + spaces: [ + { + name: 'kb', + path: space, + schema: schemaPath, + validation: { + severity: { + rules: { + 'goal-must-have-owner': 'warning', + 'goal-quality': { unbounded: 'info' }, + 'task-tone': 'ignore', + }, + }, + }, + }, + ], + }; + + const ctx = createSpaceContext('kb', config, { configDir: dir }); + const read = await readSpace(ctx); + const result = await validateNodes(ctx, read.nodes, read, { judge: { provider } }); + + const goalQuality = ofKind(result.issues, 'rule').find((i) => i.ruleId === 'goal-quality'); + expect(goalQuality?.verdict).toBe('unbounded'); + expect(goalQuality?.severity).toBe('info'); + + // task-tone ran (verdict recorded by judge) but was not reported + expect(judgedRuleIds).toContain('task-tone'); + expect(ofKind(result.issues, 'rule').find((i) => i.ruleId === 'task-tone')).toBeUndefined(); + }); + + it('validates per-space validation.severity config via loadConfig', () => { + const cfgPath = join(dir, 'sctx.json'); + writeFileSync( + cfgPath, + JSON.stringify({ + spaces: [ + { + name: 'kb', + path: space, + schema: schemaPath, + validation: { severity: { 'invalid-type': 'warning', rules: { r1: { bad: 'ignore' } } } }, + }, + ], + }), + ); + setConfigPath(cfgPath); + const loaded = loadConfig(); + expect(loaded.spaces[0]?.validation?.severity?.['invalid-type']).toBe('warning'); + expect(loaded.spaces[0]?.validation?.severity?.rules?.r1).toEqual({ bad: 'ignore' }); + }); +});