Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ There are several places that need reviewing and updating with any new feature o
- **Simplicity first:** Strive for the simplest design that completely solves the problem. Prefer conventions and established filesystem patterns over adding new configuration, programmatic APIs, or abstractions.
- **Explicitly state alternatives:** When planning or making architectural decisions, do not anchor to the first familiar mechanism. Formulate and state at least one alternative approach, weighing trade-offs, complexity, and ergonomic impact.
- **Minimise blast radius:** Protect established boundaries and interfaces. Treat unnecessary ripple effects (such as making synchronous APIs asynchronous or adding dual APIs) as a design smell indicating the approach should be re-evaluated.
- **Public API surface:** Do not add exports to `src/api.ts`, `src/types.ts` or `src/testing.ts` (the `structured-context/api`, `/types` and `/testing` entry points), or add types or hooks to the plugin interface, without the maintainer's explicit agreement on that specific surface. Exporting something to make docs complete, to tidy up, or because a feature has a public-looking class is not a reason. Agreement on a function covers that function only: its option and result types are separate exports, so derive them in the consumer (`Parameters`, `ReturnType`) instead. If a change seems to need a new export, stop and propose it, with the consumer that needs it. Internal modules can change freely.
- **Public API surface:** Do not add exports to `src/api.ts`, `src/browser.ts`, `src/types.ts` or `src/testing.ts` (the `structured-context/api`, `/browser`, `/types` and `/testing` entry points), or add types or hooks to the plugin interface, without the maintainer's explicit agreement on that specific surface. Exporting something to make docs complete, to tidy up, or because a feature has a public-looking class is not a reason. Agreement on a function covers that function only: its option and result types are separate exports, so derive them in the consumer (`Parameters`, `ReturnType`) instead. If a change seems to need a new export, stop and propose it, with the consumer that needs it. Internal modules can change freely.
- **Where a setting lives:** Config says *what* to use, CLI flags override it for one run, and the environment holds secrets and the config location only (`apiKeyEnv` names a secret; `SCTX_CONFIG` locates the config). Do not add env vars that set config values, and never infer a choice (such as a judge provider) from a variable that happens to be set: a key present for another tool must not be spent silently. Config also never switches on costly or outward-facing behaviour (such as semantic judging): each run asks for it, through a flag or an API option.
- **Reuse types:** Derive a type from the real one (`Pick`, `Partial`) instead of restating its shape. Keep CLI wording (flags, commands) out of library errors and the public API; the CLI adds its own hint. Once a feature has many files, give it a directory. Comments explain why, never restate the code.
- **Failures are visible:** A rule or expression that cannot be evaluated is reported as a violation, never skipped or treated as a pass. Likewise a misconfiguration fails before any work or spend.
Expand All @@ -71,6 +71,8 @@ There are several places that need reviewing and updating with any new feature o
## Key Files

- `src/api.ts` — Public library entry point (`structured-context/api`). Re-exports the supported programmatic surface. Keep CLI-only concerns out of it. Do not extend it without agreement (see **Public API surface** above).
- `src/browser.ts` — Browser-safe entry point (`structured-context/browser`): rebuilding a graph from the space graph format. Nothing it imports may use Node built-ins; `/api` re-exports all of it.
- `src/space-graph-data.ts` — The space graph format: `SPACE_GRAPH_DATA_SCHEMA`, `SpaceGraphData` (a typecheck fails if the two drift), `exportSpaceGraph`, `spaceGraphFrom`. Bump `SPACE_GRAPH_FORMAT_VERSION` when the shape changes. It is generated to `schemas/generated/space-graph/` (`latest.json`, plus a frozen `<formatVersion>.json` per release); generation fails if a released version's schema no longer matches.
- `schemas/` — Bundled default schema files (JSON5) using the structured-context schema dialect and top-level `$metadata`. Files starting with `_` are "partials" (fragments for `$ref`).
- `src/schema/metadata-contract.ts` — Single source of truth for the `$metadata` contract
- `schemas/generated/latest/_structured_context_schema_meta.json` — Generated metaschema for the newest dialect (generated on build or with `bun run generate:schema-meta`). `schemas/generated/<version>/` folders are frozen copies, created by the `version` script (`generate:schema-meta --release`) only when a release changes the dialect; never edit them. `src/schema/meta-schemas.ts` loads them at runtime.
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Roger Barnes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ Keeps Obsidian template files in sync with schema examples:
## Programmatic API

The package exposes a library entry point at `structured-context/api` for embedding the tooling
in other applications. See
in other applications, and `structured-context/browser` for loading an exported space graph in a browser. See
[docs/api.md](docs/api.md) for the full reference and usage examples.

## Development
Expand Down
33 changes: 33 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ see [architecture.md](architecture.md#information-flow) for that flow.
| `loadSpaceGraph(spaceName, config, options?)` | Read, assemble, and optionally filter a space into a navigable `SpaceGraph`. `options.hierarchy` names the hierarchy that structures the graph (default: the main hierarchy). |
| `assembleSpaceGraph(context, options?)` | Assemble (and optionally filter) a graph from a context you already hold — reuses the context instead of rebuilding it. |
| `buildSpaceGraph(nodes, hierarchy?)` | Build a navigable `SpaceGraph` directly from an array of `SpaceNode`s and a `Hierarchy` definition. |
| `exportSpaceGraph(nodes, metadata)` | Turn nodes and the schema's hierarchies into plain JSON for another process. See [Space graph format](#space-graph-format). |
| `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. |
| `validateFile(filePath, config)` | Validate a single file within its space. |
| `listSchemas(options?)` | List the schemas available to a config: bundled, plugin-contributed and configured. |
Expand All @@ -28,6 +30,37 @@ see [architecture.md](architecture.md#information-flow) for that flow.

`ValidationResult.ruleViolations` carries each violation's effective `severity` (`error`, `warning` or `info`). Only `error` severity violations should be treated as failures; `validateFile` reports `warning` and `info` rule violations under `warnings` rather than `errors`.

A `SpaceGraph` classifies nodes against one hierarchy, and indexes child nodes and typed edges in both
directions.

## Space graph format

`exportSpaceGraph` returns the [space graph format](concepts.md#space-graph-format):

```jsonc
{ "formatVersion": 1, "hierarchies": [/* Hierarchy */], "mainHierarchy": "…", "nodes": [/* SpaceNode */] }
```

Edges are each node's `resolvedParents`. An exported subset keeps its edges to nodes outside the subset. The
receiver picks the hierarchy when it builds the graph.

`structured-context/browser` holds what a browser needs to load the data, and imports no Node built-ins.
Everything in it is also exported from `structured-context/api`. Derive other types from its exports, such as
`Parameters<typeof spaceGraphFrom>[0]` for the data.

```ts
// Server
const { nodes } = await readSpace(context);
const data = exportSpaceGraph(nodes, context.schema.metadata); // or graph.nodes.values() for a filtered graph

// Browser
import { spaceGraphFrom } from 'structured-context/browser';
const graph = spaceGraphFrom(data, { hierarchy: 'work' });
```

`sctx dump <space> --graph` prints the same data. The JSON Schema for each released
`formatVersion` ships in `schemas/generated/space-graph/`, named by version, and `latest.json` is the newest.

## Testing utilities

Test fixture builders are available via `structured-context/testing` for plugin and integration tests:
Expand Down
12 changes: 8 additions & 4 deletions docs/concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,11 +319,15 @@ Each entry is a `ResolvedParentRef` object:
|---|---|---|
| `id` | `NodeId` | The parent node's `id` |
| `field` | `string` | The frontmatter field that held the wikilink |
| `source` | `'hierarchy' \| 'relationship'` | Whether the edge came from a hierarchy level or a relationship |
| `hierarchy` | `string` | Name of the hierarchy the edge belongs to; present only when `source` is `'hierarchy'` |
| `kind` | `'hierarchy' \| 'relationship'` | Whether the edge came from a hierarchy level or a relationship |
| `hierarchy` | `string` | Name of the hierarchy the edge belongs to; present only when `kind` is `'hierarchy'` |
| `selfRef` | `boolean` | Whether the edge is a same-type (self-referential) parent link |

The `source` and `hierarchy` labels let downstream consumers distinguish edge types and hierarchies without re-inspecting the schema. Validation routes `hierarchy` edges to structural checks within their own hierarchy (parent-type rules, skip-level detection) and `relationship` edges to field reference checks (type-match, missing-target). Tree rendering and rule evaluation use the full set.
The `kind` and `hierarchy` labels let downstream consumers distinguish edge types and hierarchies without re-inspecting the schema. Validation routes `hierarchy` edges to structural checks within their own hierarchy (parent-type rules, skip-level detection) and `relationship` edges to field reference checks (type-match, missing-target). Tree rendering and rule evaluation use the full set.

### Space graph format

The **space graph format** is a space's nodes and hierarchies as plain JSON. A program exports it on one side of a process or network boundary and builds a `SpaceGraph` from it on the other. See [api.md](api.md#space-graph-format).

### Content links

Expand Down Expand Up @@ -386,7 +390,7 @@ Each entry in `ancestors[]` or `descendants[]` includes all schema fields of the
| Metadata field | Type | Description |
|----------------|------|-------------|
| `_field` | `string` | The edge field name that connects to this ancestor/descendant |
| `_source` | `'hierarchy' \| 'relationship'` | Whether the edge came from a hierarchy or a relationship |
| `_kind` | `'hierarchy' \| 'relationship'` | Whether the edge came from a hierarchy or a relationship |
| `_hierarchy` | `string` | Hierarchy name; present only for hierarchy edges |
| `_selfRef` | `boolean` | Whether the edge is a same-type (self-referential) link |

Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
"types": "./dist/api.d.ts",
"default": "./dist/api.js"
},
"./browser": {
"types": "./dist/browser.d.ts",
"default": "./dist/browser.js"
},
"./types": {
"types": "./dist/types.d.ts",
"default": "./dist/types.js"
Expand Down
2 changes: 1 addition & 1 deletion plugin/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "structured-context",
"version": "0.16.2",
"version": "0.16.5",
"description": "Structured content authoring for Obsidian — automatic validation hooks, slash commands, and agent skills to keep markdown files compliant with your schema.",
"homepage": "https://github.com/mindsocket/structured-context",
"repository": "https://github.com/mindsocket/structured-context",
Expand Down
9 changes: 6 additions & 3 deletions plugin/skills/structured-context/references/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ sctx show <space> --filter my-view-name
**Filter expression syntax:** `WHERE {jsonata}` | `SELECT {spec} WHERE {jsonata}` | `SELECT {spec}` | bare JSONata.
Within the WHERE predicate, node fields (e.g. `resolvedType`, `status`) are directly accessible. Two
traversal arrays are also available per node:
- `ancestors[]` — ancestor nodes nearest-first, each with `_field`, `_source`, `_hierarchy` (hierarchy edges only), `_selfRef` edge metadata
- `ancestors[]` — ancestor nodes nearest-first, each with `_field`, `_kind`, `_hierarchy` (hierarchy edges only), `_selfRef` edge metadata
- `descendants[]` — descendant nodes, same structure

The SELECT spec is a comma-separated list of directives that expand the result set:
Expand All @@ -111,17 +111,20 @@ The SELECT spec is a comma-separated list of directives that expand the result s
## dump

```bash
sctx dump <space> [--filter <view-or-expression>] [--hierarchy <name>]
sctx dump <space> [--filter <view-or-expression>] [--hierarchy <name>] [--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 `errors` map
- `title`, `resolvedType` — display title and type after alias resolution
- `resolvedParents` — parent refs after link resolution, with the edge field and source
- `resolvedParents` — parent refs after link resolution, with the edge field and kind

Unfiltered output includes schema-invalid nodes. `--filter` works the same as in `show`/`render`
(named view or inline expression, evaluated over the schema-valid graph).

`--graph` outputs the space graph format instead: the nodes plus every hierarchy, for a program to load
(see "Space graph format" in `sctx docs concepts`).

Use this to debug rule violations ("why is this rule firing?"), verify `fieldMap` remapping
is working, or inspect what JSONata expressions see at evaluation time.

Expand Down
Loading
Loading