From 1a08dbe9be007ca41817145cb3aafe4dc1564d35 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:57:48 +0000 Subject: [PATCH 1/2] feat!: ValidationResult is a list of issues, each with its severity validateSpace returned per-check arrays (nodeErrors, refErrors, duplicateErrors, hierarchyViolations, ruleViolations, unresolvedContentLinks, parseIssues), and only some carried a severity. nodeIssues() then derived a second, node-keyed shape with severities for validateFile and validate --json, which every consumer read instead. ValidationResult now has one `issues` list. Each ValidationIssue has a kind, key, severity and message, the node or file it is about, and its kind's own fields (a rule's ruleId and category, a duplicate's sources, a broken link's ref). Core decides severity once, as it builds the list. validate --json prints the result as it is, plus space/valid/errorCount, and validateFile returns one node's issues in the same shape. Removed: nodeIssues, FileValidationIssue, ValidationResult's per-check arrays and nodeErrorCount. `orphans` is now { nodeId, title }[]. 'parse' joins VALIDATION_ISSUE_KINDS. The map pane converts the list for structured-context-map-views 0.5's annotationsFrom until a map-views release takes the list itself. Closes #198 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Xphpde5yiQF1dWi3KfETS --- docs/api.md | 9 +- docs/concepts.md | 6 +- docs/rules.md | 4 +- hook-test/unit/mod-bridge.test.ts | 17 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/hooks/map-pane.test.tsx | 36 +++- plugin/hooks/map-pane.tsx | 30 ++- plugin/scripts/mod-bridge.ts | 6 +- plugin/scripts/state.ts | 29 +-- .../structured-context/references/commands.md | 4 +- plugin/types/index.d.ts | 104 ++++++++-- scripts/mod-contract.ts | 8 +- src/api.ts | 4 +- src/commands/validate-file.ts | 8 +- src/commands/validate.ts | 148 ++++++-------- src/types.ts | 58 ++++-- src/validate.ts | 185 +++++++++--------- tests/helpers/issues.ts | 13 ++ tests/load-space-graph.test.ts | 9 +- tests/plugins/markdown/folder-index.test.ts | 12 +- tests/validate/content-links.test.ts | 10 +- tests/validate/gating.test.ts | 38 ++-- tests/validate/issues-of.test.ts | 71 +++++++ tests/validate/node-issues.test.ts | 54 ----- tests/validate/okf.test.ts | 25 ++- tests/validate/rule-severity.test.ts | 19 +- tests/validate/semantic-rule-shape.test.ts | 27 ++- tests/validate/semantic-validation.test.ts | 13 +- tests/validate/validate-views.test.ts | 49 ++--- 29 files changed, 569 insertions(+), 429 deletions(-) create mode 100644 tests/helpers/issues.ts create mode 100644 tests/validate/issues-of.test.ts delete mode 100644 tests/validate/node-issues.test.ts diff --git a/docs/api.md b/docs/api.md index 04b5325..4602901 100644 --- a/docs/api.md +++ b/docs/api.md @@ -22,18 +22,17 @@ see [architecture.md](architecture.md#information-flow) for that flow. | `spaceGraphFrom(data, options?)` | Build a `SpaceGraph` from that JSON. `options.hierarchy` names the hierarchy that structures it (default: the main hierarchy). | | `validateSpace(context, options?)` | Run full validation (schema, references, rules, duplicates) over a space. Semantic rules run only when `semantic` is passed; it takes the same values as `sctx validate --semantic`, with the provider coming from config and the environment. | | `validateFile(filePath, config)` | Validate a single file within its space. | -| `nodeIssues(result, options?)` | Each node's issues from a `ValidationResult`, by node id: the per-node view `validateFile` and `sctx validate --json` give. | | `listSchemas(options?)` | List the schemas available to a config: bundled, plugin-contributed and configured. | | `formatWikilink(target, alias?)` | Format a target into an Obsidian wikilink (`[[target]]` or `[[target|alias]]`). | | `parseWikilink(link)` | Parse a wikilink or target string into `{ target, anchor?, displayText? }`. | | `wikilinkToTarget(link)` | Extract the plain target lookup key from a wikilink string. | | `buildTargetIndex(nodes)` | Build a fast lookup index mapping link target strings to nodes (marking ambiguous targets as `null`). | -`ValidationResult.ruleViolations` carries each violation's effective `severity` (`error`, `warning` or `info`). Only `error` severity violations should be treated as failures. +`ValidationResult.issues` lists every issue the run found: parse, schema, duplicate id, broken link, hierarchy, rule, gated and unresolved content link issues. Each `ValidationIssue` has a `kind`, a `key`, a `severity` (`error`, `warning` or `info`) and a one-line `message`. Only `error` issues are failures. Read `severity` rather than deriving it from `kind`. `kind` is a `ValidationIssueKind`, and `VALIDATION_ISSUE_KINDS` lists every kind at runtime. Each kind adds its own fields, such as a rule's `ruleId` and `category`, or a duplicate's `sources`. -`nodeIssues(result)` gathers every result about a node into one map per node: schema, duplicate id, broken link, hierarchy, rule, gated and unresolved content link issues, each keyed by a composite id such as `rule:` and carrying its `kind`, `message` and `severity`. `kind` is a `ValidationIssueKind`, and `VALIDATION_ISSUE_KINDS` lists every kind at runtime. Read `severity` rather than deriving it from `kind`. Pass `{ includeGated }` as validation ran, so a gated node's note says whether its rules were evaluated. Rule violations without a node and parse issues stay in their own parts of the result. `validateFile` returns one node's map as `issues`. +An issue about a node carries its `nodeId` and, where known, the node's `source` (`{ file, line?, column? }`). A parse issue has a `source` and no `nodeId`; so does a global rule's violation, without a `source`. `key` names the issue within its node, or its file for a parse issue, stably across runs (for example `rule:`). Group by `nodeId` for a per-node view. `validateFile` returns one node's issues. See [Validation results and nodes](concepts.md#validation-results-and-nodes). -Each `ValidationResult` entry about a node carries its `nodeId`, and, where the entry is tied to a location, an optional `source` (`{ file, line?, column? }`). `duplicateErrors` lists a `sources` location for each node that shares the `id`. See [Validation results and nodes](concepts.md#validation-results-and-nodes). +The rest of `ValidationResult` describes the run rather than reporting issues: `validCount`, `orphans`, `coverageGates`, `contextTrimmed`, `skippedByDepth` and `depthLimit`. A `SpaceGraph` classifies nodes against one hierarchy, and indexes child nodes and typed edges in both directions. @@ -112,7 +111,7 @@ const validation = await validateSpace(context, { readResult }); `loadSpaceGraph` keeps every node whose type the schema defines, including nodes with field errors such as an invalid enum value. Nodes of an unknown type are left out. The graph is *not* a validation pass: use `validateSpace` (or `validateFile`) for field errors, broken references, rule violations and -duplicates. Each entry in its `nodeErrors` lists the node's `issues`, one formatted message per problem. +duplicates. A node with field errors has one `schema` issue per problem. ## Hand-assembled config diff --git a/docs/concepts.md b/docs/concepts.md index c5eb085..5cda68c 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -119,9 +119,11 @@ A wikilink is looked up in `linkTargets`, and the result is stored as the target ### Validation results and nodes -A validation result refers to a node by its `id`, in a `nodeId` field. Where the node is defined is a separate `source` (`file`, and `line` / `column` where available). A result may copy a node's identity and location, but not its content. A node can lack a `source` (for example when a plugin reads from a service rather than files), so treat `source` as optional. +A validation run reports a list of **validation issues**. Each issue has a **kind** (the check that found it, such as `schema`, `rule` or `hierarchy`), a **severity** (`error`, `warning` or `info`) and a message. Core decides the severity; consumers read it. Only `error` issues fail validation. -Rule violations on a global rule have no `nodeId`. +A validation issue refers to a node by its `id`, in a `nodeId` field. Where the node is defined is a separate `source` (`file`, and `line` / `column` where available). A result may copy a node's identity and location, but not its content. A node can lack a `source` (for example when a plugin reads from a service rather than files), so treat `source` as optional. + +Parse issues (files that produced no nodes) and violations of a global rule have no `nodeId`. ### Folder index diff --git a/docs/rules.md b/docs/rules.md index 83baaff..b4d99ad 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -235,8 +235,8 @@ the next). Excluded nodes are reported under `skippedByDepth`, separate from gat ## Output - **`sctx validate`** — the summary counts rule violations per severity, and details are grouped by severity with each line showing the rule's category and id. -- **`sctx validate --json`** — `issues` holds each node's issues of every severity, keyed by node id and then by a composite id such as `rule:`. Each issue has a `kind`, `message` and `severity`. A `ruleViolations` array lists every violation with `file`, `ruleId`, `category`, `severity` and `description` (`file` is empty for global rules). A violation from a failed `expression` has the evidence `expression failed: ` when the rule also has a `semantic` part, and no verdict. -- **`sctx validate-file --json`** — `issues` holds the file's issues of every severity, each with a `severity` field. `errorCount` counts the `error` ones. +- **`sctx validate --json`** — prints the run's `ValidationResult` (see [the API](api.md#main-building-blocks)) with `space`, `valid` and `errorCount`. `issues` lists every issue of every severity, each with a `kind`, `key`, `severity` and `message`. A `rule` issue also has `ruleId`, `category` and `description`, and `nodeId` unless the rule is global. A violation from a failed `expression` has the evidence `expression failed: ` when the rule also has a `semantic` part, and no verdict. +- **`sctx validate-file --json`** — `issues` lists the file's issues of every severity, in the same shape. `errorCount` counts the `error` ones. Gated files: see [Single-file validation](#single-file-validation). diff --git a/hook-test/unit/mod-bridge.test.ts b/hook-test/unit/mod-bridge.test.ts index ceca538..309adba 100644 --- a/hook-test/unit/mod-bridge.test.ts +++ b/hook-test/unit/mod-bridge.test.ts @@ -88,28 +88,31 @@ describe('paneData', () => { const dir = resultsDirPath(stateFilePath(sessionId, opts())); const kept = loadResult(dir, 'test-space')!; const marker = { + kind: 'rule', + key: 'rule:kept', + message: '[kept] from the kept result', nodeId: 'valid.md', ruleId: 'kept', category: 'coherence', severity: 'warning', description: 'from the kept result', - } as PaneData['validation']['ruleViolations'][number]; - saveResult({ dir, hash: kept.hash }, 'test-space', { ruleViolations: [marker] }); + } as PaneData['validation']['issues'][number]; + saveResult({ dir, hash: kept.hash }, 'test-space', { issues: [marker] }); const reused = await paneData(sessionId, 'test-space', { ...opts(), cwd: fixtures.fixtureDir }); - expect(reused.validation).toEqual({ issues: {}, ruleViolations: [marker], parseIssues: [] }); + expect(reused.validation).toEqual({ issues: [marker] }); expect(reused.graph.nodes.length).toBeGreaterThan(0); expect(reused.graph.nodes.every((node) => !('content' in (node as object)))).toBe(true); writeFileSync(join(fixtures.vaultDir, 'valid.md'), '---\ntype: mission\nstatus: identified\n---\n\n# Changed\n'); const fresh = await paneData(sessionId, 'test-space', { ...opts(), cwd: fixtures.fixtureDir }); - expect(fresh.validation.ruleViolations).not.toContainEqual(marker); + expect(fresh.validation.issues).not.toContainEqual(marker); writeFileSync(join(fixtures.vaultDir, 'valid.md'), '---\ntype: mission\n---\n\n# No status\n'); const failing = await paneData(sessionId, 'test-space', { ...opts(), cwd: fixtures.fixtureDir }); - const kinds = Object.values(failing.validation.issues['valid.md'] ?? {}).map( - ({ kind, severity }) => `${kind}:${severity}`, - ); + const kinds = failing.validation.issues + .filter((issue) => issue.nodeId === 'valid.md') + .map(({ kind, severity }) => `${kind}:${severity}`); expect(kinds).toContain('schema:error'); expect(loadResult(dir, 'test-space')!.hash).not.toBe(kept.hash); }); diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 9c6a686..d3632ce 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.22.5", + "version": "0.22.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/hooks/map-pane.test.tsx b/plugin/hooks/map-pane.test.tsx index d97f096..8f7e6c9 100644 --- a/plugin/hooks/map-pane.test.tsx +++ b/plugin/hooks/map-pane.test.tsx @@ -1,7 +1,7 @@ import type { On } from 'claude-code'; import { type Engine, expect, test } from 'claude-code/testing'; -import type { CwdContext, ModStatus, PaneData } from '../types'; +import type { CwdContext, ModStatus, NodeId, PaneData } from '../types'; import { fit } from './map-pane'; const level = (type: string) => ({ type, field: 'parent', fieldOn: 'child', multiple: false, selfRef: false }); @@ -36,13 +36,33 @@ const DATA: PaneData = { ], }, validation: { - issues: { - 'Broken.md': { 'schema:type': { kind: 'schema', message: 'type is not allowed', severity: 'error' } }, - 'Opp A.md': { 'rule:summary': { kind: 'rule', message: '[summary] missing summary', severity: 'warning' } }, - }, - // Rule results on a node are in `issues`; `ruleViolations` adds only those without one - ruleViolations: [], - parseIssues: [{ file: 'Bad.md', severity: 'error', type: 'yaml', message: 'bad frontmatter' }], + issues: [ + { + kind: 'parse', + key: 'parse:yaml', + severity: 'error', + message: 'bad frontmatter', + source: { file: 'Bad.md' }, + type: 'yaml', + }, + { + kind: 'schema', + key: 'schema:type', + severity: 'error', + message: 'type is not allowed', + nodeId: 'Broken.md' as NodeId, + }, + { + kind: 'rule', + key: 'rule:summary', + severity: 'warning', + message: '[summary] missing summary', + nodeId: 'Opp A.md' as NodeId, + ruleId: 'summary', + category: 'coherence', + description: 'missing summary', + }, + ], }, }; diff --git a/plugin/hooks/map-pane.tsx b/plugin/hooks/map-pane.tsx index a70a8f2..01eb19b 100644 --- a/plugin/hooks/map-pane.tsx +++ b/plugin/hooks/map-pane.tsx @@ -126,11 +126,33 @@ function findOccurrence(occurrences: Occurrence[], key: string): Occurrence | un return undefined; } +type Issue = PaneData['validation']['issues'][number]; + +// PROTOTYPE: structured-context-map-views 0.5 takes issues by node plus the global rule violations. +// Drop this once a map-views release takes the issue list itself. +function byNode(list: Issue[]): Parameters[0] { + const issues: Record< + string, + Record & { line?: number; column?: number }> + > = {}; + const ruleViolations: { ruleId: string; severity: Issue['severity']; description: string }[] = []; + for (const issue of list) { + if (issue.kind === 'parse') continue; + if (issue.nodeId === undefined) { + if (issue.kind === 'rule') ruleViolations.push(issue); + continue; + } + const { kind, message, severity, source } = issue; + issues[issue.nodeId] ??= {}; + issues[issue.nodeId]![issue.key] = { kind, message, severity, line: source?.line, column: source?.column }; + } + return { issues, ruleViolations } as Parameters[0]; +} + function project(data: PaneData, hierarchy?: string): { graph: Graph; tree: Tree; annotations: Annotations } { const graph = spaceGraphFrom(data.graph as Parameters[0], { hierarchy }); const tree = buildTree(graph, 'pane'); - const { issues, ruleViolations } = data.validation; - const annotations = annotationsFrom({ issues, ruleViolations }, graph); + const annotations = annotationsFrom(byNode(data.validation.issues), graph); return { graph, tree, annotations }; } @@ -244,7 +266,7 @@ export function registerMapPane(on: On): void { const counts = { error: 0, warning: 0, info: 0 }; for (const results of annotations.annotations.values()) for (const a of results) counts[a.severity]++; for (const a of annotations.unattached) counts[a.severity]++; - const parseIssues = data.validation.parseIssues; + const parseIssues = data.validation.issues.filter((issue) => issue.kind === 'parse'); for (const issue of parseIssues) counts[issue.severity]++; const toggle = (key: string) => @@ -355,7 +377,7 @@ export function registerMapPane(on: On): void { {parseIssues.slice(0, UNATTACHED_LIMIT).map((issue) => ( {' '} - {issue.file}: {issue.severity}: {issue.message ?? issue.type} + {issue.source?.file}: {issue.severity}: {issue.message} ))} {parseIssues.length > UNATTACHED_LIMIT && ( diff --git a/plugin/scripts/mod-bridge.ts b/plugin/scripts/mod-bridge.ts index cbc0fe2..065d5f9 100644 --- a/plugin/scripts/mod-bridge.ts +++ b/plugin/scripts/mod-bridge.ts @@ -107,11 +107,7 @@ export async function paneData(sessionId: string, space: string, options: HookOp space, path: info.path, graph: { ...graph, nodes }, - validation: { - issues: output.issues ?? {}, - ruleViolations: output.ruleViolations ?? [], - parseIssues: output.parseIssues ?? [], - }, + validation: { issues: output.issues ?? [] }, }; } diff --git a/plugin/scripts/state.ts b/plugin/scripts/state.ts index d9512ab..34170f7 100644 --- a/plugin/scripts/state.ts +++ b/plugin/scripts/state.ts @@ -106,7 +106,7 @@ export interface SpacesOutput { } /** The parts of `validate --json` the hooks read */ -type ValidateOutput = Partial>; +type ValidateOutput = Partial>; export function stateFilePath(sessionId: string | undefined, options?: HookOptions): string { const dir = options?.stateDir ?? process.env.SCTX_STATE_DIR ?? '/tmp'; @@ -289,26 +289,13 @@ export async function validateSpace( return byFile[label]; }; - for (const [label, issues] of Object.entries(output.issues ?? {})) { - for (const [key, issue] of Object.entries(issues)) { - if (issue.severity === 'error') issuesFor(label).errors[key] = issue; - else if (issue.severity === 'warning') issuesFor(label).warnings[key] = issue; - } - } - for (const issue of output.parseIssues ?? []) { - if (issue.severity === 'error') { - issuesFor(issue.file).errors[`parse:${issue.type}`] = { - kind: 'parse', - message: issue.message ?? `Could not parse (${issue.type})`, - }; - } - } - // Rule violations without a node aren't in `issues` - for (const v of output.ruleViolations ?? []) { - if (v.nodeId || v.severity === 'info') continue; - const issue = { kind: 'rule', message: `[${v.ruleId}] ${v.description}`, severity: v.severity }; - const bucket = v.severity === 'error' ? issuesFor('').errors : issuesFor('').warnings; - bucket[`rule:${v.ruleId}`] = issue; + for (const issue of output.issues ?? []) { + // A file excluded from the space without a parse failure (such as a note with no type) is not worth a turn + if (issue.kind === 'parse' && issue.severity !== 'error') continue; + const label = issue.nodeId ?? (issue.kind === 'parse' ? issue.source.file : ''); + const { kind, message, severity } = issue; + if (severity === 'error') issuesFor(label).errors[issue.key] = { kind, message, severity }; + else if (severity === 'warning') issuesFor(label).warnings[issue.key] = { kind, message, severity }; } return byFile; } diff --git a/plugin/skills/structured-context/references/commands.md b/plugin/skills/structured-context/references/commands.md index 764c2a2..1292b3e 100644 --- a/plugin/skills/structured-context/references/commands.md +++ b/plugin/skills/structured-context/references/commands.md @@ -115,7 +115,7 @@ sctx dump [--filter ] [--hierarchy ] [--graph] ``` Outputs `{ nodes, source, diagnostics }` as strict JSON. Each node includes resolved fields: -- `id` — unique node key; for a page it is the path `validate --json` uses for its `issues` map +- `id` — unique node key; for a page it is the path; `validate --json` gives it as each issue's `nodeId` - `title`, `resolvedType` — display title and type after alias resolution - `resolvedParents` — parent refs after link resolution, with the edge field and kind @@ -134,7 +134,7 @@ sctx dump | jq '.nodes[] | select(.title == "My Node Title")' # Join nodes with their validation errors sctx validate --json > v.json -sctx dump | jq --slurpfile v v.json '.nodes[] | {id, resolvedType, issues: $v[0].issues[.id]}' +sctx dump | jq --slurpfile v v.json '.nodes[] | .id as $id | {id, resolvedType, issues: [$v[0].issues[] | select(.nodeId == $id)]}' ``` ## diagram diff --git a/plugin/types/index.d.ts b/plugin/types/index.d.ts index 5912ecc..b11737b 100644 --- a/plugin/types/index.d.ts +++ b/plugin/types/index.d.ts @@ -16,10 +16,32 @@ export type SchemaDigest = { space: string; text: string }; export type CwdContext = { spaces: string[]; digests: SchemaDigest[] }; // BEGIN generated from scripts/mod-contract.ts by `bun run build:mod-projection`; do not edit +/** + * Records one cascade: a node whose failure or blocking rule violation suppressed + * rule evaluation for itself (if schema/hierarchy caused it) and/or its hierarchy subtree. + */ +export type CoverageGate = { + /** Id of the blocking node. */ + nodeId: NodeId; + /** What kind of check triggered the gate. */ + reason: 'schema' | 'hierarchy' | 'rule'; + /** Rule id responsible, when `reason` is `'rule'`. */ + ruleId?: string; + /** Ids of nodes whose rule evaluation was suppressed as a result of this gate. */ + gatedNodeIds: NodeId[]; +}; /** Unique key of a node within a space. Supplied by the plugin that produced the node. */ export type NodeId = string & { readonly __brand: 'NodeId'; }; +export type SourceLocation = { + /** File path relative to the space root. */ + file: string; + /** 1-indexed starting line number in the source file, if available. */ + line?: number; + /** 1-indexed starting column number in the source file, if available. */ + column?: number; +}; export type ParseIssue = { /** Source identifier of the file or item (filename or heading title). */ file: string; @@ -57,7 +79,17 @@ export type RuleViolation = { /** User-facing guidance declared for that verdict (semantic rules). */ guidance?: string; }; +export type GraphViolation = { + /** Id of the node whose parent link breaks the hierarchy. */ + nodeId: NodeId; + nodeType: string; + nodeTitle: string; + parentType: string; + parentTitle: string; + description: string; +}; export type ValidationIssueKind = (readonly [ + 'parse', 'schema', 'duplicate', 'broken-link', @@ -66,22 +98,68 @@ export type ValidationIssueKind = (readonly [ 'gated', 'content-link', ])[number]; -export interface FileValidationIssue { +/** What every validation issue has, whatever its kind. */ +export type IssueBase = { /** The check it came from. */ - kind: ValidationIssueKind; - message: string; - /** How serious the issue is; consumers read it rather than infer it from `kind`. */ + kind: K; + /** + * Names the issue within its node (or its file, for a parse issue, or the space, for a global rule), + * stably across runs, for example `rule:` or `schema:`. + */ + key: string; + /** How serious the issue is; only `error` fails validation. Read it rather than infer it from `kind`. */ severity: RuleSeverity; - /** 1-indexed line number in source file, if available. */ - line?: number; - /** 1-indexed column number in source file, if available. */ - column?: number; -} -/** The parts of `validate --json` the pane reads, as validate gives them */ + /** One line describing the issue. */ + message: string; + /** The node the issue is about. Absent for parse issues and global rules. */ + nodeId?: NodeId; + /** Where the issue is: the node's source, or the file a parse issue is about. */ + source?: SourceLocation; +}; +/** + * One finding of a validation run. `kind` says which check found it and which extra fields it carries. + */ +export type ValidationIssue = + /** A file that produced no nodes; `type` is the plugin's reason, such as `no-type` or `parse`. */ + | (IssueBase<'parse'> & { + source: SourceLocation; + type: ParseIssue['type']; + }) + /** A node that failed its type or its schema, one issue per field problem. */ + | (IssueBase<'schema'> & { + nodeId: NodeId; + }) + /** An id used by more than one node; `sources` lists where each is defined. */ + | (IssueBase<'duplicate'> & { + nodeId: NodeId; + sources: SourceLocation[]; + }) + /** A link in a field that does not resolve to a node; `ref` is the link as written. */ + | (IssueBase<'broken-link'> & { + nodeId: NodeId; + ref: string; + reason: string; + }) + /** A parent link that breaks the hierarchy. */ + | (IssueBase<'hierarchy'> & Omit) + /** A rule violation; `nodeId` is absent for a global rule. */ + | (IssueBase<'rule'> & RuleViolation) + /** A node whose rules a coverage gate suppressed (or, with `includeGated`, evaluated anyway). */ + | (IssueBase<'gated'> & { + nodeId: NodeId; + /** The node whose failure gated this one. */ + gatedBy: NodeId; + reason: CoverageGate['reason']; + ruleId?: string; + }) + /** A content link to a target outside the space's nodes. */ + | (IssueBase<'content-link'> & { + nodeId: NodeId; + target: string; + }); +/** The part of `validate --json` the pane reads, as validate gives it */ export type PaneValidation = { - issues: Record>; - ruleViolations: RuleViolation[]; - parseIssues: ParseIssue[]; + issues: ValidationIssue[]; }; // END generated diff --git a/scripts/mod-contract.ts b/scripts/mod-contract.ts index 5a87364..2aeb242 100644 --- a/scripts/mod-contract.ts +++ b/scripts/mod-contract.ts @@ -1,8 +1,6 @@ -import type { FileValidationIssue, ParseIssue, RuleViolation } from '../src/types'; +import type { ValidationIssue } from '../src/types'; -/** The parts of `validate --json` the pane reads, as validate gives them */ +/** The part of `validate --json` the pane reads, as validate gives it */ export type PaneValidation = { - issues: Record>; - ruleViolations: RuleViolation[]; - parseIssues: ParseIssue[]; + issues: ValidationIssue[]; }; diff --git a/src/api.ts b/src/api.ts index 1ca65f2..fe5148f 100644 --- a/src/api.ts +++ b/src/api.ts @@ -66,7 +66,6 @@ export type { ContentLink, EdgeDefinition, FileNotInSpaceResult, - FileValidationIssue, FileValidationResult, Hierarchy, HierarchyLevel, @@ -83,8 +82,9 @@ export type { SpaceContext, UnresolvedRef, ValidateFileOutput, + ValidationIssue, ValidationIssueKind, } from './types'; export { VALIDATION_ISSUE_KINDS } from './types'; export type { ValidationResult } from './validate'; -export { nodeIssues, validateFile, validateSpace } from './validate'; +export { validateFile, validateSpace } from './validate'; diff --git a/src/commands/validate-file.ts b/src/commands/validate-file.ts index 68f6e4a..c158e67 100644 --- a/src/commands/validate-file.ts +++ b/src/commands/validate-file.ts @@ -1,6 +1,6 @@ import { loadConfig } from '../config'; import { createSpaceContext } from '../space-context'; -import type { FileValidationIssue, FileValidationResult, ValidateFileOutput } from '../types'; +import type { FileValidationResult, ValidateFileOutput, ValidationIssue } from '../types'; import { fileNotInSpace, resolveFileSpace, type ValidateFileOptions, validateResolvedFile } from '../validate'; export { validateFile } from '../validate'; @@ -57,7 +57,7 @@ function printHumanReadable(result: FileValidationResult): void { if (result.errorCount > 0) { console.log(`\n${red}✗${reset} ${result.label} (space: ${result.space}) — ${result.errorCount} error(s)\n`); - for (const issue of Object.values(result.issues).filter((i) => i.severity === 'error')) { + for (const issue of result.issues.filter((i) => i.severity === 'error')) { console.log(` [${issueLabel(issue)}] ${issue.message}`); } } else { @@ -66,7 +66,7 @@ function printHumanReadable(result: FileValidationResult): void { if (result.warningCount > 0) { console.log(`\n ${yellow}${result.warningCount} warning(s):${reset}`); - for (const issue of Object.values(result.issues).filter((i) => i.severity !== 'error')) { + for (const issue of result.issues.filter((i) => i.severity !== 'error')) { console.log(` ${yellow}[${issueLabel(issue)}]${reset} ${issue.message}`); } } @@ -75,6 +75,6 @@ function printHumanReadable(result: FileValidationResult): void { } // A structural error (schema, hierarchy, broken link) is always an error, so its label leaves the severity out -function issueLabel({ kind, severity }: FileValidationIssue): string { +function issueLabel({ kind, severity }: ValidationIssue): string { return severity === 'error' && kind !== 'rule' ? kind : `${kind}:${severity}`; } diff --git a/src/commands/validate.ts b/src/commands/validate.ts index 9cd2b56..46c42a4 100644 --- a/src/commands/validate.ts +++ b/src/commands/validate.ts @@ -3,39 +3,20 @@ import chokidar from 'chokidar'; import { getConfigSourceFiles } from '../config'; import { resolveSpacePluginSchemas } from '../plugins/util'; import { bundledSchemasDir } from '../schema/schema'; -import type { RuleSeverity, SpaceContext } from '../types'; -import { formatSource, nodeIssues, type ValidateSpaceOptions, validateSpace } from '../validate'; +import type { RuleSeverity, SpaceContext, ValidationIssue } from '../types'; +import { formatSource, type ValidateSpaceOptions, type ValidationResult, validateSpace } from '../validate'; -/** What `validate --json` prints. The Claude Code plugin's scripts read it by this type. */ +/** What `validate --json` prints: the run's `ValidationResult` and a summary. The Claude Code plugin's scripts read it by this type. */ export type ValidateJsonOutput = ReturnType; -function validateJson( - context: SpaceContext, - result: Awaited>, - options: ValidateSpaceOptions, -) { - const issues = nodeIssues(result, options); - const nodeErrorCount = Object.values(issues) - .flatMap((byKey) => Object.values(byKey)) - .filter((issue) => issue.severity === 'error').length; - const globalRuleErrorCount = result.ruleViolations.filter((v) => !v.nodeId && v.severity === 'error').length; - const parseErrorCount = result.parseIssues.filter((i) => i.severity === 'error').length; - const errorCount = nodeErrorCount + parseErrorCount + globalRuleErrorCount; - return { - space: context.space.name, - valid: errorCount === 0, - validCount: result.validCount, - errorCount, - issues, - ruleViolations: result.ruleViolations, - orphanCount: result.orphans.length, - parseIssues: result.parseIssues, - unresolvedContentLinks: result.unresolvedContentLinks, - coverageGates: result.coverageGates, - contextTrimmed: result.contextTrimmed, - skippedByDepth: result.skippedByDepth, - depthLimit: result.depthLimit, - }; +function validateJson(context: SpaceContext, result: ValidationResult) { + const errorCount = result.issues.filter((issue) => issue.severity === 'error').length; + return { space: context.space.name, valid: errorCount === 0, errorCount, ...result }; +} + +/** The issues of one kind, narrowed to that kind's fields */ +function ofKind(result: ValidationResult, kind: K) { + return result.issues.filter((issue): issue is Extract => issue.kind === kind); } export async function validate( @@ -43,13 +24,11 @@ export async function validate( options: { json?: boolean } & ValidateSpaceOptions = {}, ): Promise { const result = await validateSpace(context, options); - const ruleCounts: Record = { error: 0, warning: 0, info: 0 }; - for (const v of result.ruleViolations) ruleCounts[v.severity]++; + const errorCount = result.issues.filter((issue) => issue.severity === 'error').length; if (options.json) { - const output = validateJson(context, result, options); - console.log(JSON.stringify(output, null, 2)); - return output.valid ? 0 : 1; + console.log(JSON.stringify(validateJson(context, result), null, 2)); + return errorCount === 0 ? 0 : 1; } // Human-readable output @@ -74,69 +53,65 @@ export async function validate( return `${label.padEnd(40)} ${color}${countStr}${reset}`; }; - const parseIssueErrorCount = result.parseIssues.filter((i) => i.severity === 'error').length; + const where = (issue: ValidationIssue) => (issue.source ? formatSource(issue.source) : (issue.nodeId ?? '')); + const parseIssues = ofKind(result, 'parse'); + const schemaIssues = ofKind(result, 'schema'); + const brokenLinks = ofKind(result, 'broken-link'); + const duplicates = ofKind(result, 'duplicate'); + const ruleViolations = ofKind(result, 'rule'); + const hierarchyViolations = ofKind(result, 'hierarchy'); + const contentLinks = ofKind(result, 'content-link'); + const ruleCounts: Record = { error: 0, warning: 0, info: 0 }; + for (const v of ruleViolations) ruleCounts[v.severity]++; if (result.orphans.length > 0) { console.log(`\nOrphans (hierarchy nodes - no parent):`); - for (const node of result.orphans) console.log(` ${node.id}`); + for (const { nodeId } of result.orphans) console.log(` ${nodeId}`); } - if (result.unresolvedContentLinks.length > 0) { + if (contentLinks.length > 0) { console.log(`\nUnresolved content links (may be outside-space or broken):`); - const byFile = new Map(); - for (const { nodeId, target } of result.unresolvedContentLinks) { - if (!byFile.has(nodeId)) byFile.set(nodeId, []); - byFile.get(nodeId)!.push(target); - } - for (const [nodeId, targets] of byFile) { + const byNode = Map.groupBy(contentLinks, (link) => link.nodeId); + for (const [nodeId, links] of byNode) { console.log(` ${nodeId}:`); - for (const target of targets) console.log(` ${target}`); + for (const { target } of links) console.log(` ${target}`); } } - if (result.parseIssues.length > 0) { + if (parseIssues.length > 0) { console.log(`\nExcluded during parsing:`); - for (const issue of result.parseIssues) { - const loc = - issue.line !== undefined ? `:${issue.line}${issue.column !== undefined ? `:${issue.column}` : ''}` : ''; - const detail = issue.message ? ` - ${issue.message}` : ''; - console.log(` ${issue.file}${loc}: ${issue.severity} - ${issue.type}${detail}`); + for (const issue of parseIssues) { + console.log(` ${formatSource(issue.source)}: ${issue.severity} - ${issue.type} - ${issue.message}`); } } - if (result.nodeErrors.length > 0) { + if (schemaIssues.length > 0) { console.log(`\nSchema validation errors:`); - result.nodeErrors.forEach(({ nodeId, source, issues }) => { - console.log(`\n ${source ? formatSource(source) : nodeId}:`); - issues.forEach(({ message }) => { - console.log(` ${message}`); - }); - }); + for (const [, issues] of Map.groupBy(schemaIssues, (issue) => issue.nodeId)) { + console.log(`\n ${where(issues[0]!)}:`); + for (const { message } of issues) console.log(` ${message}`); + } } - if (result.refErrors.length > 0) { + if (brokenLinks.length > 0) { console.log(`\nBroken links:`); - result.refErrors.forEach(({ nodeId, source, parent, error }) => { - console.log(` ${source ? formatSource(source) : nodeId}: ${parent} → ${error}`); - }); + for (const issue of brokenLinks) console.log(` ${where(issue)}: ${issue.message}`); } - if (result.duplicateErrors.length > 0) { + if (duplicates.length > 0) { console.log(`\nDuplicate ids (same id on multiple nodes):`); - result.duplicateErrors.forEach(({ id, sources }) => { - console.log(` "${id}":`); - for (const source of sources) { - console.log(` ${formatSource(source)}`); - } - }); + for (const { nodeId, sources } of duplicates) { + console.log(` "${nodeId}":`); + for (const source of sources) console.log(` ${formatSource(source)}`); + } } - if (result.ruleViolations.length > 0) { + if (ruleViolations.length > 0) { console.log(`\nRule violations:`); const severityColor: Record = { error: red, warning: yellow, info: reset }; for (const severity of ['error', 'warning', 'info'] as const) { - const violations = result.ruleViolations.filter((v) => v.severity === severity); + const violations = ruleViolations.filter((v) => v.severity === severity); if (violations.length === 0) continue; console.log(` ${severityColor[severity]}${severity.toUpperCase()}${reset} (${violations.length}):`); for (const v of violations) { @@ -151,10 +126,10 @@ export async function validate( } } - if (result.hierarchyViolations.length > 0) { + if (hierarchyViolations.length > 0) { console.log(`\nHierarchy violations:`); - for (const v of result.hierarchyViolations) { - console.log(` ${v.nodeId}: ${v.description}`); + for (const v of hierarchyViolations) { + console.log(` ${v.nodeId}: ${v.message}`); } } @@ -183,16 +158,17 @@ export async function validate( console.log(`━`.repeat(45)); console.log('Content and structure'); console.log(fmt(' Valid', result.validCount)); - console.log(fmt(' Schema validation errors', result.nodeErrorCount, true)); - console.log(fmt(' Broken links', result.refErrors.length, true)); - console.log(fmt(' Duplicate ids', result.duplicateErrors.length, true)); + console.log(fmt(' Schema validation errors', new Set(schemaIssues.map((issue) => issue.nodeId)).size, true)); + console.log(fmt(' Broken links', brokenLinks.length, true)); + console.log(fmt(' Duplicate ids', duplicates.length, true)); console.log(fmt(' Rule violations (error)', ruleCounts.error, true)); console.log(fmt(' Rule violations (warning)', ruleCounts.warning, true, true)); console.log(fmt(' Rule violations (info)', ruleCounts.info, true, true)); - console.log(fmt(' Hierarchy violations', result.hierarchyViolations.length, true)); + console.log(fmt(' Hierarchy violations', hierarchyViolations.length, true)); console.log(fmt(' Orphans (hierarchy nodes - no parent)', result.orphans.length, true, true)); - console.log(fmt(' Unresolved content links (info)', result.unresolvedContentLinks.length, true, true)); - console.log(fmt(' Excluded during parsing', result.parseIssues.length, true, parseIssueErrorCount === 0)); + console.log(fmt(' Unresolved content links (info)', contentLinks.length, true, true)); + const parseErrors = parseIssues.filter((issue) => issue.severity === 'error').length; + console.log(fmt(' Excluded during parsing', parseIssues.length, true, parseErrors === 0)); if (result.depthLimit !== undefined) { console.log(fmt(' Skipped by depth limit', result.skippedByDepth.length, true, true)); } @@ -201,17 +177,7 @@ export async function validate( console.log(`\n`); - if ( - result.nodeErrorCount > 0 || - result.refErrors.length > 0 || - result.duplicateErrors.length > 0 || - ruleCounts.error > 0 || - result.hierarchyViolations.length > 0 || - parseIssueErrorCount > 0 - ) { - return 1; - } - return 0; + return errorCount === 0 ? 0 : 1; } export async function watchValidate(context: SpaceContext): Promise { diff --git a/src/types.ts b/src/types.ts index d072e0f..040b4a0 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,5 +1,6 @@ import type { AnySchemaObject, SchemaObject, ValidateFunction } from 'ajv'; import type { Config, SpaceConfig } from './config'; +import type { CoverageGate } from './schema/gating'; import type { MetadataContractHierarchyLevel, MetadataContractRelationship, @@ -276,6 +277,7 @@ export type SpaceContext = { /** The checks a validation issue can come from. */ export const VALIDATION_ISSUE_KINDS = [ + 'parse', 'schema', 'duplicate', 'broken-link', @@ -287,24 +289,58 @@ export const VALIDATION_ISSUE_KINDS = [ export type ValidationIssueKind = (typeof VALIDATION_ISSUE_KINDS)[number]; -export interface FileValidationIssue { +/** What every validation issue has, whatever its kind. */ +type IssueBase = { /** The check it came from. */ - kind: ValidationIssueKind; - message: string; - /** How serious the issue is; consumers read it rather than infer it from `kind`. */ + kind: K; + /** + * Names the issue within its node (or its file, for a parse issue, or the space, for a global rule), + * stably across runs, for example `rule:` or `schema:`. + */ + key: string; + /** How serious the issue is; only `error` fails validation. Read it rather than infer it from `kind`. */ severity: RuleSeverity; - /** 1-indexed line number in source file, if available. */ - line?: number; - /** 1-indexed column number in source file, if available. */ - column?: number; -} + /** One line describing the issue. */ + message: string; + /** The node the issue is about. Absent for parse issues and global rules. */ + nodeId?: NodeId; + /** Where the issue is: the node's source, or the file a parse issue is about. */ + source?: SourceLocation; +}; + +/** + * One finding of a validation run. `kind` says which check found it and which extra fields it carries. + */ +export type ValidationIssue = + /** A file that produced no nodes; `type` is the plugin's reason, such as `no-type` or `parse`. */ + | (IssueBase<'parse'> & { source: SourceLocation; type: ParseIssue['type'] }) + /** A node that failed its type or its schema, one issue per field problem. */ + | (IssueBase<'schema'> & { nodeId: NodeId }) + /** An id used by more than one node; `sources` lists where each is defined. */ + | (IssueBase<'duplicate'> & { nodeId: NodeId; sources: SourceLocation[] }) + /** A link in a field that does not resolve to a node; `ref` is the link as written. */ + | (IssueBase<'broken-link'> & { nodeId: NodeId; ref: string; reason: string }) + /** A parent link that breaks the hierarchy. */ + | (IssueBase<'hierarchy'> & Omit) + /** A rule violation; `nodeId` is absent for a global rule. */ + | (IssueBase<'rule'> & RuleViolation) + /** A node whose rules a coverage gate suppressed (or, with `includeGated`, evaluated anyway). */ + | (IssueBase<'gated'> & { + nodeId: NodeId; + /** The node whose failure gated this one. */ + gatedBy: NodeId; + reason: CoverageGate['reason']; + ruleId?: string; + }) + /** A content link to a target outside the space's nodes. */ + | (IssueBase<'content-link'> & { nodeId: NodeId; target: string }); export interface FileValidationResult { file: string; label: string; space: string; - /** The file's issues of every severity, keyed by composite id (e.g. `schema:/status:enum:active`, `rule:my-rule-id`). */ - issues: Record; + /** The file's node's issues of every severity. */ + issues: ValidationIssue[]; /** Issues at `error` severity: only these fail validation. */ errorCount: number; /** Issues at `warning` or `info` severity. */ diff --git a/src/validate.ts b/src/validate.ts index 6b869f2..7c3ee04 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -16,7 +16,6 @@ import { buildSpaceGraph } from './space-graph'; import type { CoverageGate, FileNotInSpaceResult, - FileValidationIssue, FileValidationResult, GraphViolation, NodeId, @@ -29,6 +28,7 @@ import type { SpaceContext, SpaceNode, ValidateFileOutput, + ValidationIssue, } from './types'; export interface FormattedError { @@ -37,24 +37,12 @@ export interface FormattedError { } export interface ValidationResult { + /** Every issue the run found, of every severity. Only `error` issues fail validation. */ + issues: ValidationIssue[]; + /** Nodes that passed their type and schema checks. */ validCount: number; - nodeErrorCount: number; - nodeErrors: Array<{ - nodeId: NodeId; - source?: SourceLocation; - /** Formatted, deduplicated schema problems for the node, one per field problem. */ - issues: FormattedError[]; - }>; - refErrors: Array<{ nodeId: NodeId; source?: SourceLocation; parent: string; error: string }>; - /** Nodes that share an id; `sources` lists where each is defined (a node without a source adds no entry). */ - duplicateErrors: Array<{ id: NodeId; sources: SourceLocation[] }>; - /** All rule violations with their effective severity. Only `error` severity fails validation. */ - ruleViolations: RuleViolation[]; - hierarchyViolations: GraphViolation[]; - orphans: SpaceNode[]; - parseIssues: ParseIssue[]; - /** Content links that could not be resolved to a space node, at `info` severity: not counted in errors. */ - unresolvedContentLinks: Array<{ nodeId: NodeId; target: string; severity: 'info' }>; + /** Hierarchy nodes without a parent: informational, not issues. */ + orphans: Array<{ nodeId: NodeId; title: string }>; /** * Cascade gates: nodes whose schema/hierarchy failure or blocking rule violation * suppressed rule evaluation for themselves and/or their hierarchy subtree. @@ -280,27 +268,31 @@ interface NodeValidationFailure { export interface SpaceValidationResult { validCount: number; nodeFailures: NodeValidationFailure[]; - refErrors: ValidationResult['refErrors']; - duplicateErrors: ValidationResult['duplicateErrors']; + refErrors: Array<{ nodeId: NodeId; source?: SourceLocation; parent: string; error: string }>; + /** Nodes that share an id; `sources` lists where each is defined (a node without a source adds no entry). */ + duplicateErrors: DuplicateId[]; ruleViolations: RuleViolation[]; hierarchyViolations: GraphViolation[]; orphans: SpaceNode[]; - unresolvedContentLinks: ValidationResult['unresolvedContentLinks']; + /** Content links that could not be resolved to a space node. */ + unresolvedContentLinks: Array<{ nodeId: NodeId; target: string }>; coverageGates: CoverageGate[]; contextTrimmed: ValidationResult['contextTrimmed']; } +type DuplicateId = { id: NodeId; sources: SourceLocation[] }; + /** * Nodes that share an id, with where each is defined. A plugin should keep ids unique, so this guards that contract. * Display titles may repeat. */ -export function findDuplicateIds(nodes: SpaceNode[]): ValidationResult['duplicateErrors'] { +export function findDuplicateIds(nodes: SpaceNode[]): DuplicateId[] { const idToNodes = new Map(); for (const node of nodes) { if (!idToNodes.has(node.id)) idToNodes.set(node.id, []); idToNodes.get(node.id)!.push(node); } - const duplicates: ValidationResult['duplicateErrors'] = []; + const duplicates: DuplicateId[] = []; for (const [id, sameId] of idToNodes) { if (sameId.length > 1) duplicates.push({ id, sources: sameId.flatMap((n) => (n.source ? [n.source] : [])) }); } @@ -420,7 +412,7 @@ export async function validateNodes( const key = `${node.id}::${link.target}`; if (!seen.has(key)) { seen.add(key); - result.unresolvedContentLinks.push({ nodeId: node.id, target: link.target, severity: 'info' }); + result.unresolvedContentLinks.push({ nodeId: node.id, target: link.target }); } } } @@ -464,16 +456,9 @@ export async function validateSpace( const result = await validateNodes(context, nodes, readResult, runOptions); return { + issues: issuesOf(result, readResult.parseIssues, runOptions), validCount: result.validCount, - nodeErrorCount: result.nodeFailures.length, - nodeErrors: toNodeErrors(result.nodeFailures), - refErrors: result.refErrors, - duplicateErrors: result.duplicateErrors, - ruleViolations: result.ruleViolations, - hierarchyViolations: result.hierarchyViolations, - orphans: result.orphans, - parseIssues: readResult.parseIssues, - unresolvedContentLinks: result.unresolvedContentLinks, + orphans: result.orphans.map((node) => ({ nodeId: node.id, title: node.title })), coverageGates: result.coverageGates, contextTrimmed: result.contextTrimmed, skippedByDepth, @@ -500,84 +485,102 @@ export interface ValidateFileOptions extends CommonValidateOptions { configDir?: string; } -/** The parts of a validation result that `nodeIssues` reads. */ -type NodeIssueSources = Pick< - ValidationResult, - | 'nodeErrors' - | 'refErrors' - | 'duplicateErrors' - | 'hierarchyViolations' - | 'ruleViolations' - | 'coverageGates' - | 'unresolvedContentLinks' ->; - /** - * Every result that belongs to a node, by node id, each keyed by a composite id (e.g. - * `schema:/status:enum:active`, `rule:my-rule-id`) and carrying its severity. Rule violations without - * a node (global scope) and parse issues are not per node, so they stay in their own parts of the result. - * `includeGated` words the note on a gated node as it was validated. + * The run's findings as issues, each with its severity. This is the one place severity is decided for + * the checks that have no severity of their own. An issue repeated within its node (or file) is kept once. */ -export function nodeIssues( - result: NodeIssueSources, - options: { includeGated?: boolean } = {}, -): Record> { - const byNode: Record> = {}; - const add = (nodeId: NodeId, key: string, issue: FileValidationIssue) => { - byNode[nodeId] ??= {}; - byNode[nodeId][key] = issue; +export function issuesOf( + result: SpaceValidationResult, + parseIssues: ParseIssue[], + options: { includeGated?: boolean }, +): ValidationIssue[] { + const issues = new Map(); + const add = (issue: ValidationIssue) => { + const scope = issue.nodeId ?? (issue.kind === 'parse' ? issue.source.file : ''); + issues.set(`${scope}\0${issue.key}`, issue); }; + const at = (source: SourceLocation | undefined) => (source ? { source } : {}); - for (const { nodeId, source, issues } of result.nodeErrors) { - const position = { - ...(source?.line !== undefined ? { line: source.line } : {}), - ...(source?.column !== undefined ? { column: source.column } : {}), - }; - for (const { message, dedupeKey } of issues) { - add(nodeId, `schema:${dedupeKey}`, { kind: 'schema', message, severity: 'error', ...position }); + for (const { file, severity, type, message, line, column } of parseIssues) { + add({ + kind: 'parse', + key: `parse:${type}`, + severity, + message: message ?? (type === 'no-type' ? 'No type field' : `Excluded during parsing (${type})`), + source: { file, ...(line !== undefined && { line }), ...(column !== undefined && { column }) }, + type, + }); + } + for (const { node, issues: problems } of result.nodeFailures) { + for (const { message, dedupeKey } of problems) { + add({ + kind: 'schema', + key: `schema:${dedupeKey}`, + severity: 'error', + message, + nodeId: node.id, + ...at(node.source), + }); } } for (const { id, sources } of result.duplicateErrors) { const where = sources.length > 0 ? `: ${sources.map(formatSource).join(', ')}` : ''; - add(id, `duplicate:${id}`, { + add({ kind: 'duplicate', - message: `Duplicate id "${id}" is used by ${sources.length} nodes${where}`, + key: `duplicate:${id}`, severity: 'error', + message: `Duplicate id "${id}" is used by ${sources.length} nodes${where}`, + nodeId: id, + sources, }); } - for (const { nodeId, parent, error } of result.refErrors) { - add(nodeId, `broken-link:${parent}`, { kind: 'broken-link', message: `${parent} → ${error}`, severity: 'error' }); + for (const { nodeId, source, parent, error } of result.refErrors) { + add({ + kind: 'broken-link', + key: `broken-link:${parent}`, + severity: 'error', + message: `${parent} → ${error}`, + nodeId, + ...at(source), + ref: parent, + reason: error, + }); } - for (const { nodeId, description } of result.hierarchyViolations) { - add(nodeId, `hierarchy:${description}`, { kind: 'hierarchy', message: description, severity: 'error' }); + for (const { description, ...violation } of result.hierarchyViolations) { + add({ kind: 'hierarchy', key: `hierarchy:${description}`, severity: 'error', message: description, ...violation }); } for (const v of result.ruleViolations) { - if (v.nodeId) - add(v.nodeId, `rule:${v.ruleId}`, { kind: 'rule', message: ruleViolationMessage(v), severity: v.severity }); + add({ kind: 'rule', key: `rule:${v.ruleId}`, message: ruleViolationMessage(v), ...v }); } // A gated node with no violations would otherwise look clean: say that its rules were not checked for (const gate of result.coverageGates) { const cause = gate.reason === 'rule' ? `blocking rule "${gate.ruleId}"` : `${gate.reason} failure`; const message = `Rule checks ${options.includeGated ? 'evaluated anyway' : 'not evaluated'}: gated by ${cause} on ${gate.nodeId}`; - for (const id of gate.gatedNodeIds) add(id, `gated:${gate.nodeId}`, { kind: 'gated', message, severity: 'info' }); + for (const nodeId of gate.gatedNodeIds) { + add({ + kind: 'gated', + key: `gated:${gate.nodeId}`, + severity: 'info', + message, + nodeId, + gatedBy: gate.nodeId, + reason: gate.reason, + ...(gate.ruleId !== undefined && { ruleId: gate.ruleId }), + }); + } } - for (const { nodeId, target, severity } of result.unresolvedContentLinks) { - add(nodeId, `content-link:${target}`, { + for (const { nodeId, target } of result.unresolvedContentLinks) { + // Info: a target outside the space is often valid elsewhere + add({ kind: 'content-link', + key: `content-link:${target}`, + severity: 'info', message: `Unresolved content link: ${target}`, - severity, + nodeId, + target, }); } - return byNode; -} - -/** `ValidationResult['nodeErrors']` from the failures `validateNodes` collects */ -function toNodeErrors(failures: NodeValidationFailure[]): ValidationResult['nodeErrors'] { - return failures.map(({ node, issues }) => ({ - nodeId: node.id, - ...(node.source !== undefined && { source: node.source }), - issues, - })); + return [...issues.values()]; } /** The result for a file that belongs to no configured space. */ @@ -614,12 +617,8 @@ export async function validateResolvedFileWith( ...runOptions, judgeTarget: label, }); - const byNode = nodeIssues( - { ...result, nodeErrors: toNodeErrors(result.nodeFailures) }, - { includeGated: runOptions.includeGated }, - ); - const issues = byNode[label] ?? {}; - const errorCount = Object.values(issues).filter((issue) => issue.severity === 'error').length; + const issues = issuesOf(result, [], runOptions).filter((issue) => issue.nodeId === label); + const errorCount = issues.filter((issue) => issue.severity === 'error').length; return { file: isAbsolute(filePath) ? filePath : resolve(process.cwd(), filePath), @@ -627,7 +626,7 @@ export async function validateResolvedFileWith( space: context.space.name, issues, errorCount, - warningCount: Object.keys(issues).length - errorCount, + warningCount: issues.length - errorCount, inSpace: true, }; } diff --git a/tests/helpers/issues.ts b/tests/helpers/issues.ts new file mode 100644 index 0000000..81656b5 --- /dev/null +++ b/tests/helpers/issues.ts @@ -0,0 +1,13 @@ +import type { ValidationIssue } from '../../src/types'; + +/** The issues of one kind, narrowed to that kind's fields */ +export function ofKind(issues: readonly ValidationIssue[], kind: K) { + return issues.filter((issue): issue is Extract => issue.kind === kind); +} + +/** The issue with this key, if any */ +export const withKey = (issues: readonly ValidationIssue[], key: string) => issues.find((issue) => issue.key === key); + +/** How many nodes failed their type or schema */ +export const schemaFailures = (issues: readonly ValidationIssue[]) => + new Set(ofKind(issues, 'schema').map((issue) => issue.nodeId)).size; diff --git a/tests/load-space-graph.test.ts b/tests/load-space-graph.test.ts index 689f7be..bbbe28c 100644 --- a/tests/load-space-graph.test.ts +++ b/tests/load-space-graph.test.ts @@ -8,6 +8,7 @@ import { bundledSchemasDir } from '../src/schema/schema'; import { createSpaceContext } from '../src/space-context'; import { validateSpace } from '../src/validate'; import { makeSpaceContext } from './helpers/context'; +import { ofKind } from './helpers/issues'; const VALID_DIR = join(import.meta.dir, 'fixtures/general/valid-ost'); const SCHEMA_PATH = join(bundledSchemasDir, 'strategy_general.json'); @@ -43,9 +44,9 @@ describe('assembleSpaceGraph', () => { it('reports one issue for the node', async () => { const result = await validateSpace(makeSpaceContext(dir, SCHEMA_PATH)); - const mission = result.nodeErrors.find((e) => e.nodeId === 'Mission.md'); - expect(mission?.issues).toHaveLength(1); - expect(mission?.issues[0]?.message).toStartWith('status: "exploding" is not valid'); + const mission = ofKind(result.issues, 'schema').filter((e) => e.nodeId === 'Mission.md'); + expect(mission).toHaveLength(1); + expect(mission[0]?.message).toStartWith('status: "exploding" is not valid'); }); it('keeps the node in the graph, with its children beneath it', async () => { @@ -89,7 +90,7 @@ describe('validateSpace with shared readResult', () => { const shared = await validateSpace(context, { readResult }); const fresh = await validateSpace(context); expect(shared.validCount).toBe(fresh.validCount); - expect(shared.nodeErrorCount).toBe(fresh.nodeErrorCount); + expect(shared.issues).toEqual(fresh.issues); }); }); diff --git a/tests/plugins/markdown/folder-index.test.ts b/tests/plugins/markdown/folder-index.test.ts index 72dd729..0c504c7 100644 --- a/tests/plugins/markdown/folder-index.test.ts +++ b/tests/plugins/markdown/folder-index.test.ts @@ -9,6 +9,7 @@ import { bundledSchemasDir, loadMetadata } from '../../../src/schema/schema'; import type { NodeId, SpaceNode, UnresolvedRef } from '../../../src/types'; import { validateSpace } from '../../../src/validate'; import { makePluginContext, makeSpaceContext } from '../../helpers/context'; +import { ofKind } from '../../helpers/issues'; const PAGES: Record = { 'Vision.md': 'type: vision', @@ -144,7 +145,7 @@ describe('folderIndex off', () => { describe('validation', () => { it('does not report same-named pages as duplicates', async () => { const result = await validateSpace(makeSpaceContext(DIR)); - expect(result.duplicateErrors).toEqual([]); + expect(ofKind(result.issues, 'duplicate')).toEqual([]); }); it('reports a duplicate when two nodes share an id', async () => { @@ -159,7 +160,7 @@ describe('validation', () => { return { nodes, parseIssues: [], diagnostics: {}, source: 'test', unresolvedRefs }; })(), }); - expect(result.duplicateErrors.map((d) => d.id as string)).toEqual(['alpha/Overview.md']); + expect(ofKind(result.issues, 'duplicate').map((d) => d.nodeId as string)).toEqual(['alpha/Overview.md']); }); }); @@ -170,10 +171,9 @@ describe('non-string title', () => { writeFileSync(join(dir, 'Numeric.md'), '---\ntype: goal\ntitle: 42\n---\n'); writeFileSync(join(dir, 'Empty.md'), '---\ntype: goal\ntitle:\n---\n'); const result = await validateSpace(makeSpaceContext(dir)); - expect(result.nodeErrors.map((e) => e.nodeId as string).sort()).toEqual(['Empty.md', 'Numeric.md']); - for (const { issues } of result.nodeErrors) { - expect(issues.some((i) => i.message.startsWith('title:'))).toBe(true); - } + const schema = ofKind(result.issues, 'schema'); + expect([...new Set(schema.map((e) => e.nodeId as string))].sort()).toEqual(['Empty.md', 'Numeric.md']); + expect(schema.every((i) => i.message.startsWith('title:'))).toBe(true); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/tests/validate/content-links.test.ts b/tests/validate/content-links.test.ts index bddd805..06c3cb5 100644 --- a/tests/validate/content-links.test.ts +++ b/tests/validate/content-links.test.ts @@ -6,6 +6,7 @@ import type { Config } from '../../src/config'; import { createSpaceContext } from '../../src/space-context'; import type { FileValidationResult } from '../../src/types'; import { validateFile, validateSpace } from '../../src/validate'; +import { ofKind, withKey } from '../helpers/issues'; const META = 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; @@ -42,13 +43,14 @@ describe('unresolved content links', () => { it('resolves links to files the space read but excluded, and reports missing targets', async () => { const result = await validateSpace(createSpaceContext('links', config, { configDir: dir })); - expect(result.unresolvedContentLinks.map((l) => l.target).sort()).toEqual(['Missing', 'gone.md']); - expect(result.unresolvedContentLinks.every((l) => l.severity === 'info')).toBe(true); + const links = ofKind(result.issues, 'content-link'); + expect(links.map((l) => l.target).sort()).toEqual(['Missing', 'gone.md']); + expect(links.every((l) => l.severity === 'info')).toBe(true); }); it('reports the same for a single file', async () => { const result = (await validateFile(join(space, 'A.md'), config, { configDir: dir })) as FileValidationResult; - expect(Object.keys(result.issues).sort()).toEqual(['content-link:Missing', 'content-link:gone.md']); - expect(result.issues['content-link:Missing']?.severity).toBe('info'); + expect(result.issues.map((issue) => issue.key).sort()).toEqual(['content-link:Missing', 'content-link:gone.md']); + expect(withKey(result.issues, 'content-link:Missing')?.severity).toBe('info'); }); }); diff --git a/tests/validate/gating.test.ts b/tests/validate/gating.test.ts index 65525f1..42a03e8 100644 --- a/tests/validate/gating.test.ts +++ b/tests/validate/gating.test.ts @@ -5,6 +5,7 @@ import type { Config } from '../../src/config'; import { bundledSchemasDir } from '../../src/schema/schema'; import { validateFile, validateSpace } from '../../src/validate'; import { makeSpaceContext } from '../helpers/context'; +import { ofKind, schemaFailures, withKey } from '../helpers/issues'; const SCHEMA_PATH = join(bundledSchemasDir, 'strict_ost.json'); const VALID_DIR = join(import.meta.dir, '../fixtures/strict_ost/valid-directory'); @@ -16,11 +17,11 @@ describe('validateSpace cascade gating', () => { const result = await validateSpace(context); // Bad Outcome fails schema validation (missing required "metric"). - expect(result.nodeErrors.some((e) => e.nodeId === 'Bad Outcome.md')).toBe(true); + expect(ofKind(result.issues, 'schema').some((e) => e.nodeId === 'Bad Outcome.md')).toBe(true); // Child Opportunity would otherwise violate solution-quantity (only one solution below), // but its rule evaluation is gated by the ancestor's schema failure. - expect(result.ruleViolations.some((v) => v.nodeId === 'Child Opportunity.md')).toBe(false); + expect(ofKind(result.issues, 'rule').some((v) => v.nodeId === 'Child Opportunity.md')).toBe(false); const gate = result.coverageGates.find((g) => g.nodeId === 'Bad Outcome.md'); expect(gate).toBeDefined(); @@ -35,7 +36,9 @@ describe('validateSpace cascade gating', () => { const result = await validateSpace(context, { includeGated: true }); expect( - result.ruleViolations.some((v) => v.nodeId === 'Child Opportunity.md' && v.ruleId === 'solution-quantity'), + ofKind(result.issues, 'rule').some( + (v) => v.nodeId === 'Child Opportunity.md' && v.ruleId === 'solution-quantity', + ), ).toBe(true); const gate = result.coverageGates.find((g) => g.nodeId === 'Bad Outcome.md'); @@ -49,8 +52,8 @@ describe('validateSpace cascade gating', () => { const context = makeSpaceContext(VALID_DIR, SCHEMA_PATH); const result = await validateSpace(context); - expect(result.nodeErrorCount).toBe(0); - expect(result.ruleViolations.some((v) => v.ruleId === 'solution-quantity')).toBe(true); + expect(schemaFailures(result.issues)).toBe(0); + expect(ofKind(result.issues, 'rule').some((v) => v.ruleId === 'solution-quantity')).toBe(true); expect(result.coverageGates).toEqual([]); }); }); @@ -62,8 +65,8 @@ describe('validateSpace depth limiting', () => { const shallow = await validateSpace(context, { depth: 1 }); expect(shallow.skippedByDepth.length).toBeGreaterThan(0); - expect(shallow.skippedByDepth.length + shallow.validCount + shallow.nodeErrorCount).toBe( - full.validCount + full.nodeErrorCount, + expect(shallow.skippedByDepth.length + shallow.validCount + schemaFailures(shallow.issues)).toBe( + full.validCount + schemaFailures(full.issues), ); expect(shallow.depthLimit).toBe(1); // Only the outcome (root) node remains. @@ -80,8 +83,8 @@ describe('validateSpace depth limiting', () => { ); const result = await validateSpace(context, { depth: 1 }); expect(result.skippedByDepth.map((s) => s.title)).toEqual(['Opp A']); - expect(result.refErrors).toEqual([]); - expect(result.hierarchyViolations).toEqual([]); + expect(ofKind(result.issues, 'broken-link')).toEqual([]); + expect(ofKind(result.issues, 'hierarchy')).toEqual([]); }); it('does not affect validation when depth is unset', async () => { @@ -106,17 +109,16 @@ describe('validateFile matches validateSpace', () => { const result = await validateFile(join(dir, file), config, { includeGated, configDir: import.meta.dir }); if (!result.inSpace) throw new Error(`expected ${file} to be in space`); - const fileRules = Object.keys(result.issues) - .filter((k) => k.startsWith('rule:')) - .map((k) => k.slice('rule:'.length)) + const fileRules = ofKind(result.issues, 'rule') + .map((v) => v.ruleId) .sort(); - const spaceRules = space.ruleViolations + const spaceRules = ofKind(space.issues, 'rule') .filter((v) => v.nodeId === file) .map((v) => v.ruleId) .sort(); expect(fileRules).toEqual(spaceRules); - const fileGated = Object.keys(result.issues).some((k) => k.startsWith('gated:')); + const fileGated = result.issues.some((issue) => issue.kind === 'gated'); const spaceGated = space.coverageGates.some((g) => g.gatedNodeIds.some((id) => id === file)); expect(fileGated).toBe(spaceGated); } @@ -128,15 +130,15 @@ describe('validateFile matches validateSpace', () => { const config: Config = { spaces: [{ name: 'space', path: GATING_DIR, schema: SCHEMA_PATH }] }; const result = await validateFile(join(GATING_DIR, 'Child Opportunity.md'), config, { configDir: import.meta.dir }); if (!result.inSpace) throw new Error('expected file to be in space'); - expect(result.issues['gated:Bad Outcome.md']?.message).toContain('not evaluated'); - expect(result.issues['rule:solution-quantity']).toBeUndefined(); + expect(withKey(result.issues, 'gated:Bad Outcome.md')?.message).toContain('not evaluated'); + expect(withKey(result.issues, 'rule:solution-quantity')).toBeUndefined(); const forced = await validateFile(join(GATING_DIR, 'Child Opportunity.md'), config, { includeGated: true, configDir: import.meta.dir, }); if (!forced.inSpace) throw new Error('expected file to be in space'); - expect(forced.issues['gated:Bad Outcome.md']?.message).toContain('evaluated anyway'); - expect(forced.issues['rule:solution-quantity']).toBeDefined(); + expect(withKey(forced.issues, 'gated:Bad Outcome.md')?.message).toContain('evaluated anyway'); + expect(withKey(forced.issues, 'rule:solution-quantity')).toBeDefined(); }); }); diff --git a/tests/validate/issues-of.test.ts b/tests/validate/issues-of.test.ts new file mode 100644 index 0000000..37b5cff --- /dev/null +++ b/tests/validate/issues-of.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'bun:test'; +import type { NodeId, SpaceNode } from '../../src/types'; +import { issuesOf, type SpaceValidationResult } from '../../src/validate'; + +const id = (value: string) => value as NodeId; + +const empty: SpaceValidationResult = { + validCount: 0, + nodeFailures: [], + refErrors: [], + duplicateErrors: [], + ruleViolations: [], + hierarchyViolations: [], + orphans: [], + unresolvedContentLinks: [], + coverageGates: [], + contextTrimmed: { nodeCount: 0, ruleIds: [] }, +}; + +const summary = (issues: ReturnType) => + issues.map(({ kind, key, severity, nodeId }) => ({ kind, key, severity, nodeId })); + +describe('issuesOf', () => { + it('gives every finding a kind, a key and a severity', () => { + const node = { id: id('a.md'), source: { file: 'a.md', line: 3 } } as SpaceNode; + const issues = issuesOf( + { + ...empty, + nodeFailures: [{ node, issues: [{ message: 'bad', dedupeKey: 'k' }] }], + refErrors: [{ nodeId: id('a.md'), parent: '[[Gone]]', error: 'not found' }], + hierarchyViolations: [{ nodeId: id('b.md'), description: 'wrong parent' } as never], + ruleViolations: [ + { nodeId: id('b.md'), ruleId: 'r1', category: 'coherence', severity: 'warning', description: 'soft' }, + { ruleId: 'global', category: 'validation', severity: 'error', description: 'no node' }, + ], + unresolvedContentLinks: [{ nodeId: id('b.md'), target: 'Missing' }], + }, + [{ file: 'x.md', severity: 'warning', type: 'no-type', line: 1 }], + {}, + ); + + expect(summary(issues)).toEqual([ + { kind: 'parse', key: 'parse:no-type', severity: 'warning', nodeId: undefined }, + { kind: 'schema', key: 'schema:k', severity: 'error', nodeId: id('a.md') }, + { kind: 'broken-link', key: 'broken-link:[[Gone]]', severity: 'error', nodeId: id('a.md') }, + { kind: 'hierarchy', key: 'hierarchy:wrong parent', severity: 'error', nodeId: id('b.md') }, + { kind: 'rule', key: 'rule:r1', severity: 'warning', nodeId: id('b.md') }, + { kind: 'rule', key: 'rule:global', severity: 'error', nodeId: undefined }, + { kind: 'content-link', key: 'content-link:Missing', severity: 'info', nodeId: id('b.md') }, + ]); + expect(issues[0]).toMatchObject({ source: { file: 'x.md', line: 1 }, type: 'no-type' }); + expect(issues[1]).toMatchObject({ message: 'bad', source: { file: 'a.md', line: 3 } }); + expect(issues[2]).toMatchObject({ message: '[[Gone]] → not found', ref: '[[Gone]]', reason: 'not found' }); + }); + + it('keeps an issue repeated on the same node once', () => { + const v = { nodeId: id('a.md'), ruleId: 'r', category: 'coherence', severity: 'error', description: 'd' } as const; + expect(issuesOf({ ...empty, ruleViolations: [v, v] }, [], {})).toHaveLength(1); + }); + + it('notes each gated node at info, worded by includeGated', () => { + const gated = { + ...empty, + coverageGates: [{ nodeId: id('a.md'), reason: 'schema' as const, gatedNodeIds: [id('a.md'), id('c.md')] }], + }; + const issue = issuesOf(gated, [], {}).find((one) => one.nodeId === 'c.md'); + expect(issue).toMatchObject({ kind: 'gated', key: 'gated:a.md', severity: 'info', gatedBy: 'a.md' }); + expect(issue?.message).toContain('not evaluated'); + expect(issuesOf(gated, [], { includeGated: true })[0]?.message).toContain('evaluated anyway'); + }); +}); diff --git a/tests/validate/node-issues.test.ts b/tests/validate/node-issues.test.ts deleted file mode 100644 index 71f68fd..0000000 --- a/tests/validate/node-issues.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import type { NodeId } from '../../src/types'; -import { nodeIssues } from '../../src/validate'; - -const id = (value: string) => value as NodeId; - -const empty = { - nodeErrors: [], - refErrors: [], - duplicateErrors: [], - hierarchyViolations: [], - ruleViolations: [], - coverageGates: [], - unresolvedContentLinks: [], -}; - -describe('nodeIssues', () => { - it('gathers each kind of result by node, with its severity', () => { - const issues = nodeIssues({ - ...empty, - nodeErrors: [ - { nodeId: id('a.md'), source: { file: 'a.md', line: 3 }, issues: [{ message: 'bad', dedupeKey: 'k' }] }, - ], - refErrors: [{ nodeId: id('a.md'), parent: '[[Gone]]', error: 'not found' }], - hierarchyViolations: [{ nodeId: id('b.md'), description: 'wrong parent' } as never], - ruleViolations: [ - { nodeId: id('b.md'), ruleId: 'r1', severity: 'warning', description: 'soft' } as never, - { ruleId: 'global', severity: 'error', description: 'no node' } as never, - ], - unresolvedContentLinks: [{ nodeId: id('b.md'), target: 'Missing', severity: 'info' }], - }); - - expect(issues['a.md']).toEqual({ - 'schema:k': { kind: 'schema', message: 'bad', severity: 'error', line: 3 }, - 'broken-link:[[Gone]]': { kind: 'broken-link', message: '[[Gone]] → not found', severity: 'error' }, - }); - expect(Object.fromEntries(Object.entries(issues['b.md']!).map(([key, { severity }]) => [key, severity]))).toEqual({ - 'hierarchy:wrong parent': 'error', - 'rule:r1': 'warning', - 'content-link:Missing': 'info', - }); - expect(Object.keys(issues)).toEqual(['a.md', 'b.md']); - }); - - it('notes each gated node at info, worded by includeGated', () => { - const gated = { - ...empty, - coverageGates: [{ nodeId: id('a.md'), reason: 'schema', gatedNodeIds: [id('a.md'), id('c.md')] } as never], - }; - expect(nodeIssues(gated)['c.md']?.['gated:a.md']).toMatchObject({ severity: 'info', kind: 'gated' }); - expect(nodeIssues(gated)['c.md']?.['gated:a.md']?.message).toContain('not evaluated'); - expect(nodeIssues(gated, { includeGated: true })['c.md']?.['gated:a.md']?.message).toContain('evaluated anyway'); - }); -}); diff --git a/tests/validate/okf.test.ts b/tests/validate/okf.test.ts index 77e1746..885f305 100644 --- a/tests/validate/okf.test.ts +++ b/tests/validate/okf.test.ts @@ -3,6 +3,7 @@ import { join } from 'node:path'; import { bundledSchemasDir, createValidator } from '../../src/schema/schema'; import { validateSpace } from '../../src/validate'; import { makeSpaceContext } from '../helpers/context'; +import { ofKind } from '../helpers/issues'; const OKF_SCHEMA_PATH = join(bundledSchemasDir, 'okf.json'); const BUNDLE_DIR = join(import.meta.dir, '../fixtures/okf/bundle'); @@ -80,17 +81,27 @@ describe('OKF schema', () => { describe('OKF bundle validation', () => { it('validates the sample bundle as a markdown space, excluding the reserved index.md and log.md', async () => { const result = await validateSpace(makeSpaceContext(BUNDLE_DIR, OKF_SCHEMA_PATH)); - expect(result.nodeErrors).toEqual([]); + expect(ofKind(result.issues, 'schema')).toEqual([]); expect(result.validCount).toBe(4); - expect(result.parseIssues.map((i) => i.file).sort()).toEqual(['index.md', 'log.md']); + expect( + ofKind(result.issues, 'parse') + .map((i) => i.source.file) + .sort(), + ).toEqual(['index.md', 'log.md']); // playbooks/bare.md has only `type`: the description best-practice rule is the sole finding - expect(result.ruleViolations.map((v) => [v.nodeId, v.ruleId])).toEqual([['playbooks/bare.md', 'okf-description']]); + expect(ofKind(result.issues, 'rule').map((v) => [v.nodeId, v.ruleId])).toEqual([ + ['playbooks/bare.md', 'okf-description'], + ]); }); it('flags coherence and contract rule violations', async () => { const result = await validateSpace(makeSpaceContext(RULE_VIOLATIONS_DIR, OKF_SCHEMA_PATH)); - expect(result.nodeErrors).toEqual([]); - expect(result.ruleViolations.map((v) => `${v.nodeId}:${v.ruleId}`).sort()).toEqual([ + expect(ofKind(result.issues, 'schema')).toEqual([]); + expect( + ofKind(result.issues, 'rule') + .map((v) => `${v.nodeId}:${v.ruleId}`) + .sort(), + ).toEqual([ 'body-without-computation.md:okf-computation-present', 'no-computation.md:okf-computation-present', 'stale-before-generated.md:okf-stale-after-generated', @@ -101,7 +112,7 @@ describe('OKF bundle validation', () => { it('passes okf-computation-present on a `# Computation` line inside a code fence (known limitation)', async () => { // The rule matches the heading text with a regex, so it cannot tell a fenced comment from a real heading. const result = await validateSpace(makeSpaceContext(KNOWN_LIMITATIONS_DIR, OKF_SCHEMA_PATH)); - expect(result.nodeErrors).toEqual([]); - expect(result.ruleViolations).toEqual([]); + expect(ofKind(result.issues, 'schema')).toEqual([]); + expect(ofKind(result.issues, 'rule')).toEqual([]); }); }); diff --git a/tests/validate/rule-severity.test.ts b/tests/validate/rule-severity.test.ts index 696002f..3aca49d 100644 --- a/tests/validate/rule-severity.test.ts +++ b/tests/validate/rule-severity.test.ts @@ -4,6 +4,7 @@ import { validate } from '../../src/commands/validate'; import type { Config } from '../../src/config'; import { validateFile, validateSpace } from '../../src/validate'; import { makeSpaceContext } from '../helpers/context'; +import { ofKind, withKey } from '../helpers/issues'; const FIXTURES_DIR = join(import.meta.dir, '..', 'fixtures/rule-severity'); const SCHEMA_PATH = join(FIXTURES_DIR, 'schema.json'); @@ -26,7 +27,7 @@ describe('rule severity', () => { describe('validateSpace', () => { it('reports the effective severity of each violation', async () => { const result = await validateSpace(makeSpaceContext(FAILING_DIR, SCHEMA_PATH)); - const severities = Object.fromEntries(result.ruleViolations.map((v) => [v.ruleId, v.severity])); + const severities = Object.fromEntries(ofKind(result.issues, 'rule').map((v) => [v.ruleId, v.severity])); expect(severities).toEqual({ 'always-info': 'info', 'always-warning': 'warning', 'not-blocked': 'error' }); }); }); @@ -50,22 +51,24 @@ describe('rule severity', () => { const clean = JSON.parse((await runValidate(CLEAN_DIR, true)).output); expect(clean.valid).toBe(true); expect(clean.errorCount).toBe(0); - expect(clean.ruleViolations).toHaveLength(2); + expect(ofKind(clean.issues, 'rule')).toHaveLength(2); const { exitCode, output } = await runValidate(FAILING_DIR, true); const failing = JSON.parse(output); expect(exitCode).toBe(1); expect(failing.valid).toBe(false); expect(failing.errorCount).toBe(1); - expect(failing.issues['Blocked goal.md']['rule:not-blocked'].severity).toBe('error'); - expect(failing.issues['Blocked goal.md']['rule:always-warning'].severity).toBe('warning'); - expect(failing.ruleViolations).toContainEqual({ + expect(failing.issues).toContainEqual({ + kind: 'rule', + key: 'rule:not-blocked', + message: '[not-blocked] Goals must not be blocked (workflow rule overridden to error)', nodeId: 'Blocked goal.md', ruleId: 'not-blocked', category: 'workflow', severity: 'error', description: 'Goals must not be blocked (workflow rule overridden to error)', }); + expect(withKey(failing.issues, 'rule:always-warning')?.severity).toBe('warning'); }); }); @@ -81,15 +84,15 @@ describe('rule severity', () => { const result = await validateFile(join(CLEAN_DIR, 'Clean goal.md'), config, { configDir: FIXTURES_DIR }); if (!result.inSpace) throw new Error('expected file to be in space'); expect(result.errorCount).toBe(0); - expect(result.issues['rule:always-info']?.severity).toBe('info'); - expect(result.issues['rule:always-warning']?.severity).toBe('warning'); + expect(withKey(result.issues, 'rule:always-info')?.severity).toBe('info'); + expect(withKey(result.issues, 'rule:always-warning')?.severity).toBe('warning'); }); it('reports error severity rule violations as errors', async () => { const result = await validateFile(join(FAILING_DIR, 'Blocked goal.md'), config, { configDir: FIXTURES_DIR }); if (!result.inSpace) throw new Error('expected file to be in space'); expect(result.errorCount).toBe(1); - expect(result.issues['rule:not-blocked']).toEqual({ + expect(withKey(result.issues, 'rule:not-blocked')).toMatchObject({ kind: 'rule', message: '[not-blocked] Goals must not be blocked (workflow rule overridden to error)', severity: 'error', diff --git a/tests/validate/semantic-rule-shape.test.ts b/tests/validate/semantic-rule-shape.test.ts index c14189b..9eb817a 100644 --- a/tests/validate/semantic-rule-shape.test.ts +++ b/tests/validate/semantic-rule-shape.test.ts @@ -3,6 +3,7 @@ import { FakeJudgeProvider } from '../../src/judge/provider/fake'; import { createSpaceContext } from '../../src/space-context'; import type { FileValidationResult, NodeId } from '../../src/types'; import { validateSpace } from '../../src/validate'; +import { ofKind, withKey } from '../helpers/issues'; import { makeTempSpace } from '../helpers/temp-space'; import { validateFileWith, validateSpaceWith } from '../helpers/validate-run'; @@ -87,7 +88,7 @@ describe('semantic rules: verdict severity, ignore and guidance', () => { judge: new FakeJudgeProvider({ 'step-fit': { verdict: 'minor' } }), configDir: space.dir, })) as FileValidationResult; - expect(result.issues['rule:step-fit']?.message).toContain('Guidance: Tighten the wording.'); + expect(withKey(result.issues, 'rule:step-fit')?.message).toContain('Guidance: Tighten the wording.'); }); it('--rule-filter severity matches any severity a verdict map can report', async () => { @@ -114,7 +115,11 @@ describe('rule `when` precondition', () => { }; const { context } = setup([rule], { frontmatter: { T: 'status: ready', S: 'status: draft' } }); const result = await validateSpace(context()); - expect(result.ruleViolations.map((v) => v.nodeId as string).sort()).toEqual(['T.md']); + expect( + ofKind(result.issues, 'rule') + .map((v) => v.nodeId as string) + .sort(), + ).toEqual(['T.md']); }); it('does not call the judge for nodes where `when` is not true', async () => { @@ -136,7 +141,7 @@ describe('judge option', () => { it('evaluates no semantic rules without a judge', async () => { const { context } = setup([stepRule]); const result = await validateSpace(context(), {}); - expect(result.ruleViolations).toEqual([]); + expect(ofKind(result.issues, 'rule')).toEqual([]); }); it('judges with the judge it is given', async () => { @@ -162,7 +167,7 @@ describe('rule expression errors', () => { it('reports a failing check or when as an error violation instead of passing silently', async () => { const { context } = setup([broken, brokenWhen]); const result = await validateSpace(context(), {}); - const byId = (id: string) => result.ruleViolations.filter((v) => v.ruleId === id); + const byId = (id: string) => ofKind(result.issues, 'rule').filter((v) => v.ruleId === id); expect(byId('broken').length).toBeGreaterThan(0); expect(byId('broken')[0]).toMatchObject({ severity: 'error' }); expect(byId('broken')[0]?.description).toContain('Rule error'); @@ -262,15 +267,15 @@ describe('semantic rule check precondition', () => { })) as FileValidationResult; // T.md's failing check gates S.md, so S.md is not judged and only reports the gate. expect(judgedLabels(judge)).toEqual([]); - expect(Object.keys(result.issues)).toEqual(['gated:T.md']); - expect(result.issues['gated:T.md']?.message).toContain('task-fit'); + expect(result.issues.map((issue) => issue.key)).toEqual(['gated:T.md']); + expect(withKey(result.issues, 'gated:T.md')?.message).toContain('task-fit'); }); describe('without a judge', () => { it('reports a failing check, marked as an expression check failure', async () => { const { context } = setup([gated]); const result = await validateSpace(context(), {}); - expect(result.ruleViolations).toEqual([ + expect(ofKind(result.issues, 'rule')).toEqual([ expect.objectContaining({ ruleId: 'step-fit', nodeId: 'S.md' as NodeId, @@ -282,12 +287,12 @@ describe('semantic rule check precondition', () => { it('reports nothing when the check passes', async () => { const { context } = setup([gated], { frontmatter: { S: 'owner: sam' } }); const result = await validateSpace(context(), {}); - expect(result.ruleViolations).toEqual([]); + expect(ofKind(result.issues, 'rule')).toEqual([]); }); it('still skips a semantic-only rule', async () => { const { context } = setup([stepRule]); - expect((await validateSpace(context(), {})).ruleViolations).toEqual([]); + expect(ofKind((await validateSpace(context(), {})).issues, 'rule')).toEqual([]); }); it('honours --rule-filter', async () => { @@ -307,7 +312,9 @@ describe('semantic rule check precondition', () => { }; const { context } = setup([rule]); const result = await validateSpace(context(), {}); - expect(result.ruleViolations).toEqual([expect.objectContaining({ ruleId: 'step-fit', severity: 'warning' })]); + expect(ofKind(result.issues, 'rule')).toEqual([ + expect.objectContaining({ ruleId: 'step-fit', severity: 'warning' }), + ]); }); it('evaluates when before check', async () => { diff --git a/tests/validate/semantic-validation.test.ts b/tests/validate/semantic-validation.test.ts index 4c651b4..39c88ad 100644 --- a/tests/validate/semantic-validation.test.ts +++ b/tests/validate/semantic-validation.test.ts @@ -8,6 +8,7 @@ import { bundledSchemasDir } from '../../src/schema/schema'; import { createSpaceContext } from '../../src/space-context'; import type { FileValidationResult } from '../../src/types'; import { validateFile, validateSpace } from '../../src/validate'; +import { ofKind, withKey } from '../helpers/issues'; import { makeTempSpace, type TempSpace } from '../helpers/temp-space'; import { validateFileWith, validateSpaceWith } from '../helpers/validate-run'; @@ -31,7 +32,7 @@ describe('Semantic rule evaluation integration (validateSpace & validateFile)', describe('validateSpace', () => { it('skips semantic rules without a judge (deterministic & free)', async () => { const result = await validateSpace(validContext); - expect(result.ruleViolations.some((v) => v.ruleId === 'opportunity-customer-voice')).toBe(false); + expect(ofKind(result.issues, 'rule').some((v) => v.ruleId === 'opportunity-customer-voice')).toBe(false); }); it('evaluates semantic rules when a judge is passed', async () => { @@ -107,7 +108,7 @@ describe('Semantic rule evaluation integration (validateSpace & validateFile)', })) as FileValidationResult; expect(result.inSpace).toBe(true); - expect(result.issues['rule:opportunity-customer-voice']).toBeUndefined(); + expect(withKey(result.issues, 'rule:opportunity-customer-voice')).toBeUndefined(); }); it('evaluates semantic rule and reports evidence on violation when semantic: true', async () => { @@ -123,7 +124,7 @@ describe('Semantic rule evaluation integration (validateSpace & validateFile)', expect(result.inSpace).toBe(true); // best-practice rules default to non-error severity, so they land in warnings - const ruleError = result.issues['rule:opportunity-customer-voice']; + const ruleError = withKey(result.issues, 'rule:opportunity-customer-voice'); expect(ruleError).toBeDefined(); expect(ruleError?.kind).toBe('rule'); expect(ruleError?.message).toContain('Evidence: Opportunity is framed in solution space.'); @@ -169,15 +170,15 @@ describe('validateFile judges only the target and its gate-capable ancestor rule it('still lets a failing ancestor rule gate the target', async () => { const judge = new FakeJudgeProvider({ 'goal-sound': { verdict: 'fail' } }); const result = await run(judge, 'S.md'); - expect(result.issues['rule:step-sound']).toBeUndefined(); - expect(Object.keys(result.issues).some((k) => k.startsWith('gated:'))).toBe(true); + expect(withKey(result.issues, 'rule:step-sound')).toBeUndefined(); + expect(result.issues.some((issue) => issue.kind === 'gated')).toBe(true); expect(judge.callHistory.some((c) => c.node.id === 'S.md')).toBe(false); }); it('with includeGated judges the target even when an ancestor fails', async () => { const judge = new FakeJudgeProvider({ 'goal-sound': { verdict: 'fail' }, 'step-sound': { verdict: 'fail' } }); const result = await run(judge, 'S.md', { includeGated: true }); - expect(result.issues['rule:step-sound']).toBeDefined(); + expect(withKey(result.issues, 'rule:step-sound')).toBeDefined(); }); it('judges nothing when the filter excludes every semantic rule', async () => { diff --git a/tests/validate/validate-views.test.ts b/tests/validate/validate-views.test.ts index 0d540e5..bc28c33 100644 --- a/tests/validate/validate-views.test.ts +++ b/tests/validate/validate-views.test.ts @@ -14,10 +14,6 @@ const META = 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; const STRICT_SCHEMA_PATH = join(bundledSchemasDir, 'strict_ost.json'); -/** An invalid `type` is keyed differently in the two views (the view lists the types in schema order). */ -const normaliseKey = (key: string) => - key.startsWith('schema:type:') || key.startsWith('schema:/type:enum:') ? 'schema:invalid-type' : key; - describe('validateFile is a view over the validateSpace core', () => { const config: Config = { spaces: [ @@ -28,36 +24,17 @@ describe('validateFile is a view over the validateSpace core', () => { it('reports for each file exactly the issues validateSpace reports for it', async () => { const space = await validateSpace(context); - const files = new Set([ - ...space.nodeErrors.map((e) => e.nodeId), - ...space.refErrors.map((e) => e.nodeId), - ...space.duplicateErrors.map((e) => e.id), - ...space.ruleViolations.map((v) => v.nodeId ?? ''), - ...space.hierarchyViolations.map((v) => v.nodeId ?? ''), - ...space.unresolvedContentLinks.map((l) => l.nodeId), - ...space.coverageGates.flatMap((g) => g.gatedNodeIds), - ]); - files.delete(''); - expect(files.size).toBeGreaterThan(1); - - for (const file of files) { - const expected = [ - ...space.nodeErrors - .filter((e) => e.nodeId === file) - .flatMap((e) => e.issues.map((f) => `schema:${f.dedupeKey}`)), - ...space.duplicateErrors.filter((d) => d.id === file).map((d) => `duplicate:${d.id}`), - ...space.refErrors.filter((r) => r.nodeId === file).map((r) => `broken-link:${r.parent}`), - ...space.hierarchyViolations.filter((v) => v.nodeId === file).map((v) => `hierarchy:${v.description}`), - ...space.ruleViolations.filter((v) => v.nodeId === file).map((v) => `rule:${v.ruleId}`), - ...space.coverageGates.filter((g) => g.gatedNodeIds.some((id) => id === file)).map((g) => `gated:${g.nodeId}`), - ...space.unresolvedContentLinks.filter((l) => l.nodeId === file).map((l) => `content-link:${l.target}`), - ].map(normaliseKey); + const byNode = Map.groupBy( + space.issues.filter((issue) => issue.nodeId !== undefined), + (issue) => issue.nodeId!, + ); + expect(byNode.size).toBeGreaterThan(1); + for (const [file, expected] of byNode) { const result = (await validateFile(join(context.space.path, file), config, { configDir: import.meta.dir, })) as FileValidationResult; - const actual = Object.keys({ ...result.issues, ...result.issues }).map(normaliseKey); - expect(actual.sort()).toEqual([...new Set(expected)].sort()); + expect(result.issues).toEqual(expected); } }); }); @@ -122,7 +99,7 @@ describe('judging a node with an expression rule violation', () => { const { config, dir, file } = setup(hierarchy, 'error'); const judge = new FakeJudgeProvider({ pass: true }); const result = (await validateFileWith(file, config, { judge, configDir: dir })) as FileValidationResult; - expect(result.issues['rule:never-holds']).toBeDefined(); + expect(result.issues.some((issue) => issue.key === 'rule:never-holds')).toBe(true); expect(judgedRules(judge)).toEqual([]); }); @@ -130,7 +107,7 @@ describe('judging a node with an expression rule violation', () => { const { config, dir, file } = setup(hierarchy, 'info'); const judge = new FakeJudgeProvider({ pass: true }); const result = (await validateFileWith(file, config, { judge, configDir: dir })) as FileValidationResult; - expect(result.issues['rule:never-holds']).toBeDefined(); + expect(result.issues.some((issue) => issue.key === 'rule:never-holds')).toBe(true); expect(judgedRules(judge)).toEqual(['sound']); }); } @@ -145,11 +122,11 @@ describe('invalid node type', () => { const context = createSpaceContext('invalid', config, { configDir: import.meta.dir }); it('reports one issue that lists the allowed types alphabetically', async () => { - const { nodeErrors } = await validateSpace(context); - const invalid = nodeErrors.filter((e) => e.issues.some((i) => i.message.startsWith('Invalid type "vision"'))); + const { issues } = await validateSpace(context); + const invalid = issues.filter((issue) => issue.message.startsWith('Invalid type "vision"')); const sorted = ['assumption_test', 'opportunity', 'outcome', 'solution']; expect(invalid).toHaveLength(1); - expect(invalid[0]?.issues).toHaveLength(1); - expect(invalid[0]?.issues[0]?.message).toEndWith(`Valid types are: ${sorted.join(', ')}`); + expect(invalid[0]).toMatchObject({ kind: 'schema', severity: 'error' }); + expect(invalid[0]?.message).toEndWith(`Valid types are: ${sorted.join(', ')}`); }); }); From 6f5b2dc5a63a208e3da9752cb89539fc9acd1831 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:42:17 +0000 Subject: [PATCH 2/2] docs: trim the validation issue docs to what the types don't say Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Xphpde5yiQF1dWi3KfETS --- docs/api.md | 8 ++------ docs/concepts.md | 6 +----- docs/rules.md | 4 ++-- plugin/.claude-plugin/plugin.json | 2 +- .../skills/structured-context/references/commands.md | 2 +- plugin/types/index.d.ts | 12 +++--------- src/types.ts | 12 +++--------- 7 files changed, 13 insertions(+), 33 deletions(-) diff --git a/docs/api.md b/docs/api.md index 4602901..b7170b8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -28,11 +28,7 @@ see [architecture.md](architecture.md#information-flow) for that flow. | `wikilinkToTarget(link)` | Extract the plain target lookup key from a wikilink string. | | `buildTargetIndex(nodes)` | Build a fast lookup index mapping link target strings to nodes (marking ambiguous targets as `null`). | -`ValidationResult.issues` lists every issue the run found: parse, schema, duplicate id, broken link, hierarchy, rule, gated and unresolved content link issues. Each `ValidationIssue` has a `kind`, a `key`, a `severity` (`error`, `warning` or `info`) and a one-line `message`. Only `error` issues are failures. Read `severity` rather than deriving it from `kind`. `kind` is a `ValidationIssueKind`, and `VALIDATION_ISSUE_KINDS` lists every kind at runtime. Each kind adds its own fields, such as a rule's `ruleId` and `category`, or a duplicate's `sources`. - -An issue about a node carries its `nodeId` and, where known, the node's `source` (`{ file, line?, column? }`). A parse issue has a `source` and no `nodeId`; so does a global rule's violation, without a `source`. `key` names the issue within its node, or its file for a parse issue, stably across runs (for example `rule:`). Group by `nodeId` for a per-node view. `validateFile` returns one node's issues. See [Validation results and nodes](concepts.md#validation-results-and-nodes). - -The rest of `ValidationResult` describes the run rather than reporting issues: `validCount`, `orphans`, `coverageGates`, `contextTrimmed`, `skippedByDepth` and `depthLimit`. +`ValidationResult.issues` lists every [validation issue](concepts.md#validation-results-and-nodes) the run found, and `validateFile` returns one node's issues. Only `error` issues are failures. Read each issue's `severity` rather than deriving it from `kind`. `VALIDATION_ISSUE_KINDS` lists the kinds at runtime. A `SpaceGraph` classifies nodes against one hierarchy, and indexes child nodes and typed edges in both directions. @@ -111,7 +107,7 @@ const validation = await validateSpace(context, { readResult }); `loadSpaceGraph` keeps every node whose type the schema defines, including nodes with field errors such as an invalid enum value. Nodes of an unknown type are left out. The graph is *not* a validation pass: use `validateSpace` (or `validateFile`) for field errors, broken references, rule violations and -duplicates. A node with field errors has one `schema` issue per problem. +duplicates. ## Hand-assembled config diff --git a/docs/concepts.md b/docs/concepts.md index 5cda68c..476b382 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -119,11 +119,7 @@ A wikilink is looked up in `linkTargets`, and the result is stored as the target ### Validation results and nodes -A validation run reports a list of **validation issues**. Each issue has a **kind** (the check that found it, such as `schema`, `rule` or `hierarchy`), a **severity** (`error`, `warning` or `info`) and a message. Core decides the severity; consumers read it. Only `error` issues fail validation. - -A validation issue refers to a node by its `id`, in a `nodeId` field. Where the node is defined is a separate `source` (`file`, and `line` / `column` where available). A result may copy a node's identity and location, but not its content. A node can lack a `source` (for example when a plugin reads from a service rather than files), so treat `source` as optional. - -Parse issues (files that produced no nodes) and violations of a global rule have no `nodeId`. +A validation run reports a list of **validation issues**. Each has a **kind**, the check that found it, and a **severity**. An issue about a node refers to it by `nodeId`. A node can lack a `source`, for example when a plugin reads from a service rather than files. ### Folder index diff --git a/docs/rules.md b/docs/rules.md index b4d99ad..d8ba7f4 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -235,8 +235,8 @@ the next). Excluded nodes are reported under `skippedByDepth`, separate from gat ## Output - **`sctx validate`** — the summary counts rule violations per severity, and details are grouped by severity with each line showing the rule's category and id. -- **`sctx validate --json`** — prints the run's `ValidationResult` (see [the API](api.md#main-building-blocks)) with `space`, `valid` and `errorCount`. `issues` lists every issue of every severity, each with a `kind`, `key`, `severity` and `message`. A `rule` issue also has `ruleId`, `category` and `description`, and `nodeId` unless the rule is global. A violation from a failed `expression` has the evidence `expression failed: ` when the rule also has a `semantic` part, and no verdict. -- **`sctx validate-file --json`** — `issues` lists the file's issues of every severity, in the same shape. `errorCount` counts the `error` ones. +- **`sctx validate --json`** — prints the run's [`ValidationResult`](api.md#main-building-blocks), with `space`, `valid` and `errorCount`. A violation from a failed `expression` has the evidence `expression failed: ` when the rule also has a `semantic` part, and no verdict. +- **`sctx validate-file --json`** — prints the file's issues, with `errorCount`. Gated files: see [Single-file validation](#single-file-validation). diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index d3632ce..4cdb8f1 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.22.6", + "version": "0.22.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/references/commands.md b/plugin/skills/structured-context/references/commands.md index 1292b3e..e7d2bf0 100644 --- a/plugin/skills/structured-context/references/commands.md +++ b/plugin/skills/structured-context/references/commands.md @@ -115,7 +115,7 @@ sctx dump [--filter ] [--hierarchy ] [--graph] ``` Outputs `{ nodes, source, diagnostics }` as strict JSON. Each node includes resolved fields: -- `id` — unique node key; for a page it is the path; `validate --json` gives it as each issue's `nodeId` +- `id` — unique node key (for a page, its path); `validate --json` issues name it as `nodeId` - `title`, `resolvedType` — display title and type after alias resolution - `resolvedParents` — parent refs after link resolution, with the edge field and kind diff --git a/plugin/types/index.d.ts b/plugin/types/index.d.ts index b11737b..0a75992 100644 --- a/plugin/types/index.d.ts +++ b/plugin/types/index.d.ts @@ -102,23 +102,17 @@ export type ValidationIssueKind = (readonly [ export type IssueBase = { /** The check it came from. */ kind: K; - /** - * Names the issue within its node (or its file, for a parse issue, or the space, for a global rule), - * stably across runs, for example `rule:` or `schema:`. - */ + /** Names the issue within its node (or file, or space), stably across runs, e.g. `rule:`. */ key: string; /** How serious the issue is; only `error` fails validation. Read it rather than infer it from `kind`. */ severity: RuleSeverity; - /** One line describing the issue. */ message: string; /** The node the issue is about. Absent for parse issues and global rules. */ nodeId?: NodeId; - /** Where the issue is: the node's source, or the file a parse issue is about. */ + /** The node's source, or the file a parse issue is about. */ source?: SourceLocation; }; -/** - * One finding of a validation run. `kind` says which check found it and which extra fields it carries. - */ +/** One finding of a validation run. `kind` also selects the fields the issue carries. */ export type ValidationIssue = /** A file that produced no nodes; `type` is the plugin's reason, such as `no-type` or `parse`. */ | (IssueBase<'parse'> & { diff --git a/src/types.ts b/src/types.ts index 040b4a0..8471163 100644 --- a/src/types.ts +++ b/src/types.ts @@ -293,24 +293,18 @@ export type ValidationIssueKind = (typeof VALIDATION_ISSUE_KINDS)[number]; type IssueBase = { /** The check it came from. */ kind: K; - /** - * Names the issue within its node (or its file, for a parse issue, or the space, for a global rule), - * stably across runs, for example `rule:` or `schema:`. - */ + /** Names the issue within its node (or file, or space), stably across runs, e.g. `rule:`. */ key: string; /** How serious the issue is; only `error` fails validation. Read it rather than infer it from `kind`. */ severity: RuleSeverity; - /** One line describing the issue. */ message: string; /** The node the issue is about. Absent for parse issues and global rules. */ nodeId?: NodeId; - /** Where the issue is: the node's source, or the file a parse issue is about. */ + /** The node's source, or the file a parse issue is about. */ source?: SourceLocation; }; -/** - * One finding of a validation run. `kind` says which check found it and which extra fields it carries. - */ +/** One finding of a validation run. `kind` also selects the fields the issue carries. */ export type ValidationIssue = /** A file that produced no nodes; `type` is the plugin's reason, such as `no-type` or `parse`. */ | (IssueBase<'parse'> & { source: SourceLocation; type: ParseIssue['type'] })