diff --git a/AGENTS.md b/AGENTS.md index 28181e4..0e6108b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,10 @@ Space names (e.g. `personal`, `politics`) are resolved via a config file - `$SCT A Claude Code plugin lives at `plugin/`. It includes skills, commands and hooks used when working with collections of Obsidian markdown content (aka a space) in a vault. +The plugin version in `plugin/.claude-plugin/plugin.json` is managed by git hooks (`lefthook.yml`, `scripts/sync-plugin-version.ts`); never edit it by hand: +- **pre-commit:** bumps the patch version for any commit touching `plugin/`, so the plugin version runs ahead of `package.json` between releases by design. It also syncs major.minor up when `package.json` moves ahead (i.e. a release). +- **pre-push:** fails if a commit since the last tag changed `plugin/` without bumping the version. + ## Definition of done There are several places that need reviewing and updating with any new feature or change added: diff --git a/README.md b/README.md index 4f20538..a0e215f 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ See `config.example.json` for the full structure. The config maps space names to Schemas define the structure and rules for the entities in a space, allowing customisation and extension to different models. -Several schemas (`strict_ost`, `knowledge_wiki` and `general`) are included. The general (strategy) schema combines a basic vision/mission/goals hierarchy with a hierarchy loosely based on Opportunity Solution Trees. It is intentionally flexible to support rapid initial adoption. The strict OST schema has a narrower scope, and reflects Teresa Torres' specific recommendations for Opportunity Solution Trees more closely. The knowledge wiki schema defines a flatter set of types used for knowledge bases. +Several schemas (`strict_ost`, `knowledge_wiki`, `general` and `okf`) are included. The general (strategy) schema combines a basic vision/mission/goals hierarchy with a hierarchy loosely based on Opportunity Solution Trees. It is intentionally flexible to support rapid initial adoption. The strict OST schema has a narrower scope, and reflects Teresa Torres' specific recommendations for Opportunity Solution Trees more closely. The knowledge wiki schema defines a flatter set of types used for knowledge bases. The `okf` schema validates [Open Knowledge Format](https://github.com/GoogleCloudPlatform/open-knowledge-format) bundles: any concept `type`, with provenance, trust, lifecycle and Attested Computation fields checked when present. structured-context schemas use a metaschema based on JSON Schema 2020-12 that adds a top-level `$metadata` block: @@ -217,7 +217,7 @@ A space can have several hierarchies by importing schemas that each declare one. - The main hierarchy drives `space_on_a_page` parsing, hierarchy embedding, `template-sync`, and the default `show`/`diagram`/`render` output. Use `--hierarchy ` to render another one. **Customizing Schemas:** -- **Partial schemas**: Files starting with an underscore (like `_sctx_base.json`, `_strategy_general.json`, `_knowledge_wiki.json`) are loaded and used to resolve references (using `$ref`). +- **Partial schemas**: Files starting with an underscore (like `_sctx_base.json`, `_strategy_general.json`, `_knowledge_wiki.json`, `_okf.json`) are loaded and used to resolve references (using `$ref`). - **Partials as entity libraries**: Partials can define reusable entity types in `$defs` that composing schemas reference via `$ref`. Bundled partials like `_strategy_general` and `_knowledge_wiki` provide common entity sets for strategy and wiki content. - **Partials can carry metadata**: Unlike plain JSON Schema, partials may include `$metadata` (hierarchy, aliases, relationships, rules). A schema gets that metadata only by listing the partial in `$metadata.imports`. - **No-metadata partials**: If a partial has no `$metadata`, prefer `$schema: "https://json-schema.org/draft/2020-12/schema"` so it validates standalone as plain JSON Schema. @@ -298,6 +298,8 @@ The WHERE predicate is a [JSONata](https://docs.jsonata.org/overview) expression - `_selfRef` — whether the edge is a same-type (self-referential) link - **`descendants[]`** — same structure, for descendant nodes +Dates and datetimes are the strings written in frontmatter, so compare them with `$toMillis()` rather than as strings (offsets and precision vary), e.g. `WHERE $toMillis(updated) > $toMillis('2026-03-31T00:00:00Z')`. See [Rules: dates and times](docs/rules.md#dates-and-times). + **SELECT spec** expands the result set by walking the graph from matched nodes. The spec is a comma-separated list of directives: | Directive | Meaning | diff --git a/docs/rules.md b/docs/rules.md index 303b37d..1e746f9 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -145,3 +145,16 @@ $count(current.sources) >= 1 $count(nodes[resolvedType='outcome' and status='active']) <= 1 current.status != 'active' or $exists(parent) = false or parent.status = 'active' ``` + +### Dates and times + +Dates and datetimes reach rules as ISO 8601 strings. Convert with `$toMillis()` to compare them, including date against datetime, and use `$millis()` for the current time: + +```jsonata +$not($exists(current.due)) or $toMillis(current.due) > $millis() +$toMillis(current.stale_after) > $toMillis(current.generated.at) +``` + +A datetime without an offset (`2026-07-01T00:00:00`) is read in the machine's local time zone, so require an offset with `format: "date-time"` when results must not depend on where validation runs. `$toMillis()` also needs seconds: it cannot parse a minute-precision datetime such as `2026-07-01T09:15`, which `format: "date-or-date-time"` accepts. A value `$toMillis()` cannot parse makes the rule fail. + +The same applies to [filter expressions](../README.md#filter-expressions): compare dates with `$toMillis()`, not as strings. diff --git a/docs/schemas.md b/docs/schemas.md index 136a55f..df8827e 100644 --- a/docs/schemas.md +++ b/docs/schemas.md @@ -59,7 +59,9 @@ This schema reuses shared structural defs from partials via `$ref` and imports i | Format | Validates | Example | |--------|-----------|---------| -| `date` | ISO 8601 date (`YYYY-MM-DD`) | `"2026-03-31"` | +| `date` | ISO 8601 calendar date (`YYYY-MM-DD`) | `"2026-03-31"` | +| `date-time` | ISO 8601 datetime with seconds and a UTC offset (`Z` or `±HH:MM`) | `"2026-03-31T09:15:00+10:00"` | +| `date-or-date-time` | A date, or a datetime where seconds and offset are optional (as Obsidian's datetime property writes) | `"2026-03-31"`, `"2026-03-31T09:15"`, `"2026-03-31T09:15:00Z"` | | `path` | Non-empty filesystem path — absolute, relative, or a plain name | `"notes"`, `"./subdir/file.md"`, `"/abs/path"` | | `wikilink` | Obsidian wikilink syntax (`[[...]]`) | `"[[Parent Node]]"` | @@ -75,15 +77,16 @@ Using `format` directly is more concise when the full definition isn't needed: { "type": "string", "format": "wikilink" } ``` -### Date coercion +### Dates and datetimes -YAML parsers (gray-matter, js-yaml) coerce unquoted ISO dates to JavaScript `Date` objects: +The markdown plugin reads frontmatter and embedded YAML blocks without YAML's timestamp type, so unquoted dates and datetimes stay as the strings written, at any depth (including inside lists): ```yaml -published_date: 2026-03-31 # parsed as a Date object by gray-matter +published_date: 2026-03-31 # "2026-03-31" +updated: 2026-06-20T22:53:05+10:00 # "2026-06-20T22:53:05+10:00", offset kept ``` -The markdown plugin automatically coerces `Date` objects to `YYYY-MM-DD` strings before validation, so unquoted dates in frontmatter and embedded YAML blocks work correctly with `format: "date"` fields. +Validate them with `format: "date"` or `format: "date-time"` when a field needs one precision, or `format: "date-or-date-time"` to accept either, and compare them in rules with JSONata's `$toMillis()` (see [Rules](rules.md#dates-and-times)). ## Metadata dialect @@ -373,7 +376,7 @@ Every schema `$id` uses the `sctx://` scheme. The shape of the `$id` says where - `$id` values follow the [namespace rules](#schema-id-namespaces) and must not collide across bundled, plugin and local schemas. - `$ref` resolution is transitive across files. - Partials with no `$metadata` should prefer `$schema: "https://json-schema.org/draft/2020-12/schema"` so they validate standalone as plain JSON Schema fragments. -- **Bundled partials as entity libraries**: `_sctx_base.json`, `_strategy_general.json`, `_knowledge_wiki.json`, and `_ost_strict.json` provide reusable entity definitions and metadata. Composing schemas can reference their entity types via `$ref` rather than redefining them. +- **Bundled partials as entity libraries**: `_sctx_base.json`, `_strategy_general.json`, `_knowledge_wiki.json`, `_okf.json`, and `_ost_strict.json` provide reusable entity definitions and metadata. Composing schemas can reference their entity types via `$ref` rather than redefining them. - **Partials can carry metadata**: Partials may include `$metadata` (hierarchy, aliases, relationships, rules). A schema gets it only by listing the partial in `$metadata.imports`; `$ref` alone brings none. ## Plugin-contributed schemas diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 224badd..c937904 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.12.0", + "version": "0.12.4", "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/schema-authoring.md b/plugin/skills/structured-context/references/schema-authoring.md index 3db88eb..2909ea7 100644 --- a/plugin/skills/structured-context/references/schema-authoring.md +++ b/plugin/skills/structured-context/references/schema-authoring.md @@ -126,10 +126,12 @@ Use `sctx schemas show _sctx_base.json` to inspect built-in defs. | `summary` | Short summary string | Any schema that needs a summary property | | `status` | OST lifecycle status enum | OST-domain schemas only | +Custom string formats: `date` (`YYYY-MM-DD`), `date-time` (ISO 8601 with seconds and offset), `date-or-date-time` (date, or datetime with optional seconds/offset; prefer it unless one precision is required), `path`, `wikilink`. Frontmatter dates and datetimes arrive as the strings written. + Convention: - define reusable concepts in `$defs` - reference via `$ref` from `oneOf` entries -- **always check existing schemas** (`strategy_general.json`, `strict_ost.json`, `knowledge_wiki.json`) before authoring — use them as consistency references for property names, patterns, and structure +- **always check existing schemas** (`strategy_general.json`, `strict_ost.json`, `knowledge_wiki.json`, `okf.json`) before authoring — use them as consistency references for property names, patterns, and structure ## `oneOf` authoring pattern diff --git a/schemas/_knowledge_wiki.json b/schemas/_knowledge_wiki.json index da7490b..c15424b 100644 --- a/schemas/_knowledge_wiki.json +++ b/schemas/_knowledge_wiki.json @@ -89,7 +89,7 @@ }, "published_date": { "type": "string", - "format": "date", + "format": "date-or-date-time", "description": "Original publication date" }, "source_type": { @@ -213,7 +213,7 @@ "type": { "const": "note" }, "date": { "type": "string", - "format": "date", + "format": "date-or-date-time", "description": "Date this entry was created or relates to" } }, diff --git a/schemas/_okf.json b/schemas/_okf.json new file mode 100644 index 0000000..ea2049f --- /dev/null +++ b/schemas/_okf.json @@ -0,0 +1,176 @@ +{ + "$schema": "https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json", + "$id": "sctx://core/_okf", + // Open Knowledge Format v0.2 frontmatter families: core, provenance, trust, lifecycle, attested computation. + // OKF §4.1: consumers MUST NOT reject unknown fields, so every object here allows additional properties. + // Concept types are not registered centrally (§4.1), so there is deliberately no oneOf over `type` consts: + // type checking would reject every type not listed. `Attested Computation` is handled with if/then instead. + // index.md and log.md are reserved bundle files without a `type`; they are reported as excluded during parsing. + "$metadata": { + "rules": [ + { + "id": "okf-description", + "category": "best-practice", + "severity": "warning", + "description": "Concepts should have a one-line description (used by index generators and search snippets)", + "check": "$exists(current.description) and $length(current.description) > 0" + }, + { + "id": "okf-stale-after-generated", + "category": "coherence", + "severity": "error", + "description": "stale_after must be later than generated.at", + "check": "$not($exists(current.stale_after)) or $not($exists(current.generated.at)) or $toMillis(current.stale_after) > $toMillis(current.generated.at)" + }, + { + "id": "okf-usage-count-window", + "category": "coherence", + "severity": "warning", + "description": "A source's usage_count is only meaningful within a usage_window (on the source or shared at the top level)", + "check": "$not($exists(current.sources)) or $count(current.sources[$exists(usage_count) and $not($exists(usage_window)) and $not($exists($$.current.usage_window))]) = 0" + }, + { + // Body content is plain text (headings are not kept), so a `# Computation` section can't be told apart + // from other body text: any body counts. + "id": "okf-computation-present", + "category": "validation", + "severity": "error", + "type": "Attested Computation", + "description": "An Attested Computation needs its computation: a `computation` path or a body `# Computation` section", + "check": "$exists(current.computation) or $exists(current.content)" + } + ] + }, + "$defs": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 datetime with an explicit UTC offset, e.g. 2026-06-30T14:00:00Z (§5)" + }, + "actor": { + "type": "string", + "minLength": 1, + "description": "/ for agents, human: for people, process: for automated processes (§7)" + }, + "usageWindow": { + "type": "object", + "properties": { + "from": { "$ref": "#/$defs/timestamp" }, + "to": { "$ref": "#/$defs/timestamp" } + }, + "required": ["from", "to"] + }, + "source": { + "type": "object", + "properties": { + "resource": { + "type": "string", + "minLength": 1, + "description": "Followable artifact (URL or path) or a scope descriptor" + }, + "id": { "type": "string", "description": "Stable key for footnote attribution" }, + "title": { "type": "string" }, + "author": { "$ref": "#/$defs/actor" }, + "usage_count": { "type": "integer", "minimum": 0 }, + "last_modified": { "$ref": "#/$defs/timestamp" }, + "usage_window": { "$ref": "#/$defs/usageWindow" } + }, + "required": ["resource"] + }, + "generated": { + "type": "object", + "properties": { + "by": { "$ref": "#/$defs/actor" }, + "at": { "$ref": "#/$defs/timestamp" } + }, + "required": ["by"] + }, + "verification": { + "type": "object", + "properties": { + "by": { "$ref": "#/$defs/actor" }, + "at": { "$ref": "#/$defs/timestamp" } + }, + "required": ["by", "at"] + }, + "okfProps": { + "type": "object", + "properties": { + "type": { + "type": "string", + "minLength": 1, + "description": "Kind of concept; unregistered and open-ended (§4.1)" + }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "resource": { "type": "string", "minLength": 1, "description": "URI or path of the underlying asset" }, + "tags": { "type": "array", "items": { "type": "string" } }, + "sources": { "type": "array", "items": { "$ref": "#/$defs/source" } }, + "usage_window": { "$ref": "#/$defs/usageWindow" }, + "generated": { "$ref": "#/$defs/generated" }, + "verified": { + "description": "One verification event, or a list of them (§5.2: a bare mapping is a one-element list)", + "anyOf": [ + { "$ref": "#/$defs/verification" }, + { "type": "array", "items": { "$ref": "#/$defs/verification" } } + ] + }, + "status": { "type": "string", "enum": ["draft", "stable", "deprecated"], "default": "stable" }, + "stale_after": { "$ref": "#/$defs/timestamp" } + }, + "required": ["type"] + }, + "concept": { + "type": "object", + "allOf": [ + { "$ref": "#/$defs/okfProps" }, + { + "if": { "properties": { "type": { "const": "Attested Computation" } }, "required": ["type"] }, + "then": { "$ref": "#/$defs/attestedComputation" } + } + ], + "additionalProperties": true + }, + "attestedComputation": { + "type": "object", + "properties": { + "runtime": { + "type": "string", + "minLength": 1, + "description": "How to run the computation; defines what `parameters` mean (§10.2)" + }, + "parameters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "minLength": 1 }, + "required": { "type": "boolean" } + }, + "required": ["name", "type"] + } + }, + "computation": { + "type": "string", + "minLength": 1, + "description": "Path to a file holding the computation, instead of the body fence" + }, + "executor": { + "type": "object", + "properties": { + "resource": { "type": "string", "minLength": 1 }, + "receipt": { "type": "array", "items": { "type": "string" }, "description": "Fields a run must return" } + }, + "required": ["resource"] + }, + "attester": { + "type": "object", + "properties": { "resource": { "type": "string", "minLength": 1 } }, + "required": ["resource"] + } + }, + "required": ["runtime"] + } + } +} diff --git a/schemas/okf.json b/schemas/okf.json new file mode 100644 index 0000000..90e9d06 --- /dev/null +++ b/schemas/okf.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json", + "$id": "sctx://core/okf", + "title": "Open Knowledge Format", + "description": "Validates the frontmatter of Open Knowledge Format (OKF v0.2) concept documents in a bundle. Any `type` is accepted and unknown fields are tolerated; `Attested Computation` concepts additionally carry the computation contract.\n\nSpecification: https://github.com/GoogleCloudPlatform/open-knowledge-format", + "$metadata": { "imports": ["sctx://core/_okf"] }, + "allOf": [{ "$ref": "sctx://core/_okf" }, { "$ref": "sctx://core/_okf#/$defs/concept" }] +} diff --git a/src/plugins/markdown/parse-embedded.ts b/src/plugins/markdown/parse-embedded.ts index 7a8cae2..6a91bd9 100644 --- a/src/plugins/markdown/parse-embedded.ts +++ b/src/plugins/markdown/parse-embedded.ts @@ -1,4 +1,3 @@ -import { load as yamlLoad } from 'js-yaml'; import type { Code, Heading, List, ListItem, Paragraph, Root, Table, TableRow } from 'mdast'; import { toString as mdastToString } from 'mdast-util-to-string'; import remarkGfm from 'remark-gfm'; @@ -13,7 +12,7 @@ import type { SharedEmbeddingFields, } from '../../api'; import { extractLinksFromAstNode } from './extract-content-links'; -import { applyFieldMap, coerceDates } from './util'; +import { applyFieldMap, parseYaml } from './util'; /** Type values that identify a space_on_a_page container (not themselves space nodes). */ export const ON_A_PAGE_TYPES = ['ost_on_a_page', 'space_on_a_page']; @@ -884,9 +883,9 @@ export function extractEmbeddedNodes(body: string, options: ExtractEmbeddedOptio activeNode.contentLinks.push(...extractLinksFromAstNode(child)); } else if (child.type === 'code' && (child as Code).lang?.trim() === 'yaml') { const code = child as Code; - const parsed = yamlLoad(code.value); + const parsed = parseYaml(code.value); if (parsed && !Array.isArray(parsed) && typeof parsed === 'object') { - Object.assign(activeNode.schemaData, coerceDates(applyFieldMap(parsed as Record, fieldMap))); + Object.assign(activeNode.schemaData, applyFieldMap(parsed as Record, fieldMap)); } else if (Array.isArray(parsed)) { throw new Error(`YAML block must be an object at "${activeNode.label}".`); } else { diff --git a/src/plugins/markdown/read-space.ts b/src/plugins/markdown/read-space.ts index 02a40c4..7f1a5aa 100644 --- a/src/plugins/markdown/read-space.ts +++ b/src/plugins/markdown/read-space.ts @@ -9,7 +9,7 @@ import type { ParseResult, PluginContext } from '../util'; import type { MarkdownPluginConfig } from '.'; import { extractLinksFromBody, extractLinksFromFrontmatter, getEdgeFieldNames } from './extract-content-links'; import { extractEmbeddedNodes, ON_A_PAGE_TYPES } from './parse-embedded'; -import { applyFieldMap, coerceDates, inferTypeFromPath } from './util'; +import { applyFieldMap, inferTypeFromPath, MATTER_OPTIONS } from './util'; type ReadSpaceDirectoryOptions = { includeOnAPageFiles?: boolean; @@ -23,7 +23,7 @@ export function readSpaceOnAPage(context: PluginContext): ParseResult { } = context; const filePath = resolve(space.path); const raw = readFileSync(filePath, 'utf-8'); - const { data: frontmatter, content: body } = matter(raw); + const { data: frontmatter, content: body } = matter(raw, MATTER_OPTIONS); const pageType = frontmatter.type as string | undefined; if (pageType !== undefined && !ON_A_PAGE_TYPES.includes(pageType)) { @@ -99,13 +99,8 @@ export async function readSpaceDirectory( let parsed: ReturnType; try { - parsed = matter(content); + parsed = matter(content, MATTER_OPTIONS); } catch (err) { - // gray-matter caches parsed YAML and has a known bug where a caught exception - // corrupts its internal cache, causing subsequent parses to silently return {}. - // Clear the cache after any parse error to avoid stale state. - // See: https://github.com/jonschlinkert/gray-matter/issues/166 - (matter as unknown as { clearCache: () => void }).clearCache(); const yamlErr = err as { mark?: { line: number; column: number } }; const line = yamlErr.mark ? yamlErr.mark.line + 1 : undefined; const column = yamlErr.mark ? yamlErr.mark.column + 1 : undefined; @@ -131,7 +126,7 @@ export async function readSpaceDirectory( continue; } - const data = coerceDates(applyFieldMap(parsed.data, fieldMap)); + const data = applyFieldMap(parsed.data, fieldMap); if (!data.type && typeInferenceCfg && knownTypes) { data.type = inferTypeFromPath(file, typeInferenceCfg, knownTypes, context.schema.metadata.typeAliases); diff --git a/src/plugins/markdown/render-directory.ts b/src/plugins/markdown/render-directory.ts index 5999131..8e41c7f 100644 --- a/src/plugins/markdown/render-directory.ts +++ b/src/plugins/markdown/render-directory.ts @@ -3,7 +3,7 @@ import matter from 'gray-matter'; import type { SpaceGraph } from '../../space-graph'; import type { PluginContext, RenderMultiFileOutput, RenderOptions } from '../util'; import { getMarkdownConfig } from './index'; -import { coerceDates, invertFieldMap } from './util'; +import { invertFieldMap, MATTER_OPTIONS } from './util'; /** * Sanitize a node title into a valid filesystem filename. @@ -131,12 +131,12 @@ export function renderMarkdownDirectory( frontmatterData[typeKey] = nodeType; } - const coercedData = coerceDates(sortFrontmatterKeys(frontmatterData)); + const sortedData = sortFrontmatterKeys(frontmatterData); const body = (node.content ?? '').trim(); let fileContent: string; - if (Object.keys(coercedData).length > 0) { - fileContent = matter.stringify(body ? `\n${body}\n` : '', coercedData); + if (Object.keys(sortedData).length > 0) { + fileContent = matter.stringify(body ? `\n${body}\n` : '', sortedData, MATTER_OPTIONS); } else { fileContent = body ? `${body}\n` : ''; } diff --git a/src/plugins/markdown/template-sync.ts b/src/plugins/markdown/template-sync.ts index 6a1e225..bb3843f 100644 --- a/src/plugins/markdown/template-sync.ts +++ b/src/plugins/markdown/template-sync.ts @@ -3,12 +3,11 @@ import { join } from 'node:path'; import type { AnySchemaObject } from 'ajv'; import fg from 'fast-glob'; import matter from 'gray-matter'; -import yaml from 'js-yaml'; import type { HierarchyLevel, Relationship, SchemaWithMetadata } from '../../api'; import { mergeVariantProperties, resolveRef } from '../../schema/schema-refs'; import type { PluginContext, TemplateSyncOptions } from '../util'; import type { MarkdownPluginConfig } from './index'; -import { invertFieldMap } from './util'; +import { dumpYaml, invertFieldMap, MATTER_OPTIONS } from './util'; export interface TypeVariant { required: string[]; @@ -135,7 +134,7 @@ export function generateNewContent( const remappedExample = Object.fromEntries( Object.entries(exampleWithPlaceholders).map(([k, v]) => [toFileKey(k), v]), ); - let frontmatterYaml = (yaml.dump(remappedExample, { lineWidth: -1 }) as string).trim(); + let frontmatterYaml = dumpYaml(remappedExample, { lineWidth: -1 }).trim(); // Append property descriptions as comments // YAML lines use file field names; look up properties using canonical key. @@ -279,7 +278,7 @@ export async function templateSync(context: PluginContext, options: TemplateSync } const body = content.slice(fmMatch[0].length); - const parsed = matter(content); + const parsed = matter(content, MATTER_OPTIONS); const nodeType = parsed.data.type as string | undefined; if (!nodeType) { continue; diff --git a/src/plugins/markdown/util.ts b/src/plugins/markdown/util.ts index d31dc7d..cd97846 100644 --- a/src/plugins/markdown/util.ts +++ b/src/plugins/markdown/util.ts @@ -1,4 +1,5 @@ import { posix } from 'node:path'; +import { DEFAULT_SCHEMA, type DumpOptions, dump, load, Schema, type Type } from 'js-yaml'; import type { TypeInferenceConfig } from '.'; export function inferTypeFromPath( @@ -51,25 +52,46 @@ export function inferTypeFromPath( return undefined; } +// js-yaml schemas expose their type lists (and types their tag) at runtime, but @types/js-yaml does not declare them. +const defaultTypes = DEFAULT_SCHEMA as unknown as { implicit: (Type & { tag: string })[]; explicit: Type[] }; + /** - * Coerce Date objects in frontmatter/YAML data to ISO date strings (YYYY-MM-DD). - * gray-matter and js-yaml parse unquoted ISO dates (e.g. `date: 2026-03-31`) as - * JavaScript Date objects, which are not valid JSON and fail string type validation. + * YAML schema for frontmatter and embedded YAML blocks: js-yaml's default schema without the + * `timestamp` type. Dates and datetimes stay as the strings written (e.g. `2026-03-31`, + * `2026-06-20T22:53:05+10:00`) rather than becoming Date objects, which lose precision and offset + * and are not valid JSON. */ -export function coerceDates(data: Record): Record { - const result: Record = {}; - for (const [key, value] of Object.entries(data)) { - if (value instanceof Date) { - result[key] = value.toISOString().slice(0, 10); - } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) { - result[key] = coerceDates(value as Record); - } else { - result[key] = value; - } - } - return result; +export const YAML_SCHEMA = new Schema({ + implicit: defaultTypes.implicit.filter((type) => type.tag !== 'tag:yaml.org,2002:timestamp'), + explicit: defaultTypes.explicit, +}); + +export function parseYaml(text: string): unknown { + return load(text, { schema: YAML_SCHEMA }); +} + +/** Dumps with YAML_SCHEMA. Date values (e.g. from non-markdown plugins) are written as ISO 8601 strings. */ +export function dumpYaml(data: unknown, options?: DumpOptions): string { + return dump(data, { + ...options, + schema: YAML_SCHEMA, + replacer: (key, value) => { + const replaced = options?.replacer ? options.replacer(key, value) : value; + return replaced instanceof Date ? replaced.toISOString() : replaced; + }, + }); } +/** + * gray-matter options using YAML_SCHEMA. Passing options also bypasses gray-matter's parse cache, + * which is corrupted by a caught parse error (https://github.com/jonschlinkert/gray-matter/issues/166). + */ +export const MATTER_OPTIONS = { + engines: { + yaml: { parse: (text: string) => parseYaml(text) as object, stringify: (data: object) => dumpYaml(data) }, + }, +}; + /** * Apply field remapping to a data object. * Renames keys according to fieldMap (file field name → canonical field name). diff --git a/src/schema/schema.ts b/src/schema/schema.ts index b2c629c..4b3d094 100644 --- a/src/schema/schema.ts +++ b/src/schema/schema.ts @@ -233,13 +233,47 @@ export function buildFullRegistry( return schemaRefRegistry; } +const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; +const DATE_TIME_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|[+-](\d{2}):(\d{2}))?$/; + +function isCalendarDate(year: string, month: string, day: string): boolean { + const d = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day))); + return d.getUTCMonth() === Number(month) - 1 && d.getUTCDate() === Number(day); +} + +/** ISO 8601 date, e.g. 2026-03-31. */ +function isDate(value: string): boolean { + const m = DATE_PATTERN.exec(value); + return m !== null && isCalendarDate(m[1]!, m[2]!, m[3]!); +} + +/** + * ISO 8601 datetime. `strict` requires seconds and a UTC offset (e.g. 2026-03-31T09:15:00+10:00); + * otherwise both are optional, as in the local datetimes Obsidian writes (e.g. 2026-03-31T09:15). + */ +function isDateTime(value: string, strict: boolean): boolean { + const m = DATE_TIME_PATTERN.exec(value); + if (!m || !isCalendarDate(m[1]!, m[2]!, m[3]!)) return false; + const [, , , , hour, minute, second, , offset, offsetHour, offsetMinute] = m; + if (strict && (second === undefined || offset === undefined)) return false; + return ( + Number(hour) < 24 && + Number(minute) < 60 && + Number(second ?? 0) < 60 && + Number(offsetHour ?? 0) < 24 && + Number(offsetMinute ?? 0) < 60 + ); +} + function compileValidator( targetSchema: AnySchemaObject, schemaRefRegistry: Map, ): ValidateFunction { const ajv = new Ajv2020(); ajv.addFormat('path', (value: string) => value.length > 0 && !value.includes('\0')); - ajv.addFormat('date', (value: string) => /^\d{4}-\d{2}-\d{2}$/.test(value)); + ajv.addFormat('date', isDate); + ajv.addFormat('date-time', (value: string) => isDateTime(value, true)); + ajv.addFormat('date-or-date-time', (value: string) => isDate(value) || isDateTime(value, false)); ajv.addFormat('wikilink', (value: string) => /^\[\[.+\]\]$/.test(value)); ajv.addKeyword({ keyword: '$metadata', diff --git a/tests/fixtures/date-coercion/valid/article.md b/tests/fixtures/date-coercion/valid/article.md deleted file mode 100644 index 1c3e82e..0000000 --- a/tests/fixtures/date-coercion/valid/article.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -type: note -title: Article Note -date: 2026-03-31 ---- - -A note with an unquoted YAML date in frontmatter. diff --git a/tests/fixtures/dates/valid/article.md b/tests/fixtures/dates/valid/article.md new file mode 100644 index 0000000..456397a --- /dev/null +++ b/tests/fixtures/dates/valid/article.md @@ -0,0 +1,8 @@ +--- +type: note +title: Article Note +date: 2026-03-31 +updated: 2026-03-31T09:15:00+10:00 +--- + +A note with an unquoted YAML date and datetime in frontmatter. diff --git a/tests/fixtures/okf/bundle/computations/revenue.md b/tests/fixtures/okf/bundle/computations/revenue.md new file mode 100644 index 0000000..c1f0959 --- /dev/null +++ b/tests/fixtures/okf/bundle/computations/revenue.md @@ -0,0 +1,34 @@ +--- +type: Attested Computation +title: Revenue for fiscal year +description: Recognized revenue for a fiscal year, per Finance's definition. +status: stable +runtime: bigquery +parameters: + - { name: year, type: integer, required: true } +executor: + resource: references/skills/run-on-bq.md + receipt: [job_id, executed_sql, result] +attester: + resource: references/attesters/revenue.py +generated: { by: reference_agent/gemini-2.5-pro, at: 2026-06-20T22:53:05Z } +verified: { by: human:analyst, at: 2026-06-25T09:00:00Z } +stale_after: 2026-09-23T00:00:00Z +sources: + - id: rev-policy + resource: https://wiki.acme/finance/revenue-recognition + title: Revenue recognition policy + usage_count: 5000 + last_modified: 2026-05-30T00:00:00Z +usage_window: { from: 2026-06-01T00:00:00Z, to: 2026-06-30T00:00:00Z } +--- + +# Computation + + SELECT SUM(amount) AS revenue + FROM finance.recognized_revenue + WHERE fiscal_year = @year + +The computation binds only the declared `parameters`.[^rev-policy] + +[^rev-policy]: Revenue recognition policy diff --git a/tests/fixtures/okf/bundle/index.md b/tests/fixtures/okf/bundle/index.md new file mode 100644 index 0000000..14c3a58 --- /dev/null +++ b/tests/fixtures/okf/bundle/index.md @@ -0,0 +1,7 @@ +--- +okf_version: "0.2" +--- + +# Tables + +* [Customer Orders](tables/orders.md) - One row per completed customer order across all channels. diff --git a/tests/fixtures/okf/bundle/log.md b/tests/fixtures/okf/bundle/log.md new file mode 100644 index 0000000..7ec9cae --- /dev/null +++ b/tests/fixtures/okf/bundle/log.md @@ -0,0 +1,4 @@ +# Directory Update Log + +## 2026-05-22 +* **Creation**: Established the bundle. diff --git a/tests/fixtures/okf/bundle/playbooks/bare.md b/tests/fixtures/okf/bundle/playbooks/bare.md new file mode 100644 index 0000000..b1827dd --- /dev/null +++ b/tests/fixtures/okf/bundle/playbooks/bare.md @@ -0,0 +1,3 @@ +--- +type: Reference +--- diff --git a/tests/fixtures/okf/bundle/playbooks/freshness.md b/tests/fixtures/okf/bundle/playbooks/freshness.md new file mode 100644 index 0000000..3577293 --- /dev/null +++ b/tests/fixtures/okf/bundle/playbooks/freshness.md @@ -0,0 +1,12 @@ +--- +type: Playbook +title: "Incident response: data freshness alert" +description: Steps to triage a freshness alert on the orders pipeline. +tags: [oncall, incident] +generated: { by: human:analyst, at: 2026-04-12T09:00:00Z } +vendor_extension: { anything: goes } +--- + +# Trigger + +A freshness alert fires when `orders` lags more than 30 minutes behind its SLA. diff --git a/tests/fixtures/okf/bundle/tables/orders.md b/tests/fixtures/okf/bundle/tables/orders.md new file mode 100644 index 0000000..75a1e16 --- /dev/null +++ b/tests/fixtures/okf/bundle/tables/orders.md @@ -0,0 +1,16 @@ +--- +type: BigQuery Table +title: Customer Orders +description: One row per completed customer order across all channels. +resource: https://console.cloud.google.com/bigquery?p=acme&d=sales&t=orders +tags: [sales, orders, revenue] +generated: { by: reference_agent/gemini-2.5-pro, at: 2026-05-28T14:30:00Z } +--- + +# Schema + +| Column | Type | Description | +|------------|--------|------------------------------| +| `order_id` | STRING | Globally unique order identifier. | + +Joined with [customers](/tables/customers.md) on `customer_id`. diff --git a/tests/fixtures/okf/rule-violations/no-computation.md b/tests/fixtures/okf/rule-violations/no-computation.md new file mode 100644 index 0000000..1120c2a --- /dev/null +++ b/tests/fixtures/okf/rule-violations/no-computation.md @@ -0,0 +1,5 @@ +--- +type: Attested Computation +description: d +runtime: python +--- diff --git a/tests/fixtures/okf/rule-violations/stale-before-generated.md b/tests/fixtures/okf/rule-violations/stale-before-generated.md new file mode 100644 index 0000000..aea76da --- /dev/null +++ b/tests/fixtures/okf/rule-violations/stale-before-generated.md @@ -0,0 +1,6 @@ +--- +type: Metric +description: d +generated: { by: agent/1, at: 2026-06-20T00:00:00Z } +stale_after: 2026-06-19T00:00:00Z +--- diff --git a/tests/fixtures/okf/rule-violations/usage-without-window.md b/tests/fixtures/okf/rule-violations/usage-without-window.md new file mode 100644 index 0000000..7cc3d1a --- /dev/null +++ b/tests/fixtures/okf/rule-violations/usage-without-window.md @@ -0,0 +1,6 @@ +--- +type: Metric +description: d +sources: + - { resource: all dashboards, usage_count: 10 } +--- diff --git a/tests/fixtures/test-schema.json b/tests/fixtures/test-schema.json index 888affb..49a36c4 100644 --- a/tests/fixtures/test-schema.json +++ b/tests/fixtures/test-schema.json @@ -4,7 +4,7 @@ "oneOf": [ { "type": "object", - "description": "A simple note type with an optional date field for testing date coercion and format validation.", + "description": "A simple note type with an optional date and datetime fields for testing date handling and format validation.", "properties": { "type": { "const": "note" }, "title": { "type": "string" }, @@ -13,6 +13,16 @@ "format": "date", "description": "ISO 8601 date (YYYY-MM-DD)" }, + "updated": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 datetime with a UTC offset" + }, + "when": { + "type": "string", + "format": "date-or-date-time", + "description": "ISO 8601 date or datetime" + }, "path": { "type": "string", "format": "path", diff --git a/tests/plugins/markdown/util.test.ts b/tests/plugins/markdown/util.test.ts index 70108a4..48f3947 100644 --- a/tests/plugins/markdown/util.test.ts +++ b/tests/plugins/markdown/util.test.ts @@ -1,32 +1,49 @@ import { describe, expect, it } from 'bun:test'; -import { coerceDates } from '../../../src/plugins/markdown/util'; +import matter from 'gray-matter'; +import { dumpYaml, MATTER_OPTIONS, parseYaml } from '../../../src/plugins/markdown/util'; -describe('coerceDates', () => { - it('converts a Date object to YYYY-MM-DD string', () => { - const result = coerceDates({ date: new Date('2026-03-31') }); - expect(result.date).toBe('2026-03-31'); +describe('parseYaml', () => { + it('keeps dates and datetimes as the strings written, at any depth', () => { + const result = parseYaml( + [ + 'date: 2026-03-31', + 'at: 2026-06-20T22:53:05Z', + 'local: 2026-07-01T00:00:00+10:00', + 'meta: { created: 2025-01-01 }', + 'items: [2025-01-01, { at: 2025-02-01T09:00:00Z }]', + ].join('\n'), + ); + expect(result).toEqual({ + date: '2026-03-31', + at: '2026-06-20T22:53:05Z', + local: '2026-07-01T00:00:00+10:00', + meta: { created: '2025-01-01' }, + items: ['2025-01-01', { at: '2025-02-01T09:00:00Z' }], + }); }); - it('leaves string values unchanged', () => { - const result = coerceDates({ date: '2026-03-31', title: 'hello' }); - expect(result.date).toBe('2026-03-31'); - expect(result.title).toBe('hello'); + it('still resolves numbers, booleans, nulls and merge keys', () => { + const result = parseYaml('base: &b { x: 1 }\nm: { <<: *b, y: true }\nn: ~\nf: 1.5'); + expect(result).toEqual({ base: { x: 1 }, m: { x: 1, y: true }, n: null, f: 1.5 }); }); +}); - it('leaves numbers and booleans unchanged', () => { - const result = coerceDates({ count: 3, active: true }); - expect(result.count).toBe(3); - expect(result.active).toBe(true); +describe('dumpYaml', () => { + it('round-trips date strings unquoted', () => { + const yaml = dumpYaml({ date: '2026-03-31', at: '2026-06-20T22:53:05Z' }); + expect(yaml).toBe('date: 2026-03-31\nat: 2026-06-20T22:53:05Z\n'); + expect(parseYaml(yaml)).toEqual({ date: '2026-03-31', at: '2026-06-20T22:53:05Z' }); }); - it('recurses into nested objects', () => { - const result = coerceDates({ meta: { created: new Date('2025-01-01') } }); - expect((result.meta as Record).created).toBe('2025-01-01'); + it('writes Date values as ISO 8601 strings, including inside lists', () => { + const yaml = dumpYaml({ at: new Date('2026-06-20T22:53:05Z'), list: [new Date('2026-03-31T00:00:00Z')] }); + expect(parseYaml(yaml)).toEqual({ at: '2026-06-20T22:53:05.000Z', list: ['2026-03-31T00:00:00.000Z'] }); }); +}); - it('does not recurse into arrays', () => { - const dates = [new Date('2025-01-01')]; - const result = coerceDates({ items: dates }); - expect(result.items).toBe(dates); +describe('MATTER_OPTIONS', () => { + it('parses frontmatter timestamps as strings', () => { + const { data } = matter('---\ngenerated: { at: 2026-06-20T22:53:05Z }\n---\nbody', MATTER_OPTIONS); + expect(data).toEqual({ generated: { at: '2026-06-20T22:53:05Z' } }); }); }); diff --git a/tests/validate/date-coercion.test.ts b/tests/validate/date-coercion.test.ts deleted file mode 100644 index 461ce19..0000000 --- a/tests/validate/date-coercion.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { beforeAll, describe, expect, it } from 'bun:test'; -import { join } from 'node:path'; -import { readSpaceDirectory } from '../../src/plugins/markdown/read-space'; -import { createValidator } from '../../src/schema/schema'; -import { makePluginContext } from '../helpers/context'; - -const TEST_SCHEMA_PATH = join(import.meta.dir, '../fixtures/test-schema.json'); -const VALID_DIR = join(import.meta.dir, '../fixtures/date-coercion/valid'); - -const validateNode = createValidator(TEST_SCHEMA_PATH); - -describe('date coercion and format validation', () => { - describe('readSpaceDirectory with unquoted YAML date', () => { - let nodes: Awaited>['nodes']; - - beforeAll(async () => { - ({ nodes } = await readSpaceDirectory(makePluginContext(VALID_DIR, TEST_SCHEMA_PATH))); - }); - - it('produces one node', () => { - expect(nodes).toHaveLength(1); - }); - - it('coerces Date object to ISO date string', () => { - expect(nodes[0]?.schemaData.date).toBe('2026-03-31'); - expect(nodes[0]?.schemaData.date).toBeTypeOf('string'); - }); - - it('coerced date passes schema validation', () => { - expect(validateNode(nodes[0]?.schemaData)).toBe(true); - }); - }); - - describe('format: "date" schema validation', () => { - it('accepts a valid ISO date string', () => { - expect(validateNode({ type: 'note', title: 'Test', date: '2026-03-31' })).toBe(true); - }); - - it('rejects a non-date string', () => { - expect(validateNode({ type: 'note', title: 'Test', date: 'not-a-date' })).toBe(false); - }); - - it('rejects a datetime string for a date field', () => { - expect(validateNode({ type: 'note', title: 'Test', date: '2026-03-31T00:00:00Z' })).toBe(false); - }); - - it('rejects a Date object (unconverted)', () => { - expect(validateNode({ type: 'note', title: 'Test', date: new Date('2026-03-31') })).toBe(false); - }); - }); -}); diff --git a/tests/validate/dates.test.ts b/tests/validate/dates.test.ts new file mode 100644 index 0000000..2e1d5f2 --- /dev/null +++ b/tests/validate/dates.test.ts @@ -0,0 +1,94 @@ +import { beforeAll, describe, expect, it } from 'bun:test'; +import { join } from 'node:path'; +import { readSpaceDirectory } from '../../src/plugins/markdown/read-space'; +import { createValidator } from '../../src/schema/schema'; +import { makePluginContext } from '../helpers/context'; + +const TEST_SCHEMA_PATH = join(import.meta.dir, '../fixtures/test-schema.json'); +const VALID_DIR = join(import.meta.dir, '../fixtures/dates/valid'); + +const validateNode = createValidator(TEST_SCHEMA_PATH); + +describe('dates and format validation', () => { + describe('readSpaceDirectory with unquoted YAML date and datetime', () => { + let nodes: Awaited>['nodes']; + + beforeAll(async () => { + ({ nodes } = await readSpaceDirectory(makePluginContext(VALID_DIR, TEST_SCHEMA_PATH))); + }); + + it('produces one node', () => { + expect(nodes).toHaveLength(1); + }); + + it('keeps the date and datetime as written', () => { + expect(nodes[0]?.schemaData.date).toBe('2026-03-31'); + expect(nodes[0]?.schemaData.updated).toBe('2026-03-31T09:15:00+10:00'); + }); + + it('passes schema validation', () => { + expect(validateNode(nodes[0]?.schemaData)).toBe(true); + }); + }); + + describe('format: "date" schema validation', () => { + it('accepts a valid ISO date string', () => { + expect(validateNode({ type: 'note', title: 'Test', date: '2026-03-31' })).toBe(true); + }); + + it('rejects a non-date string', () => { + expect(validateNode({ type: 'note', title: 'Test', date: 'not-a-date' })).toBe(false); + }); + + it('rejects a datetime string for a date field', () => { + expect(validateNode({ type: 'note', title: 'Test', date: '2026-03-31T00:00:00Z' })).toBe(false); + }); + + it.each(['2026-13-01', '2026-02-30', '2026-04-31'])('rejects impossible date %s', (value) => { + expect(validateNode({ type: 'note', title: 'Test', date: value })).toBe(false); + }); + + it('rejects a Date object', () => { + expect(validateNode({ type: 'note', title: 'Test', date: new Date('2026-03-31') })).toBe(false); + }); + }); + + describe('format: "date-time" schema validation', () => { + it.each([ + '2026-03-31T09:15:00Z', + '2026-03-31T09:15:00.250Z', + '2026-03-31T09:15:00+10:00', + ])('accepts %s', (value) => { + expect(validateNode({ type: 'note', title: 'Test', updated: value })).toBe(true); + }); + + it.each([ + '2026-03-31', + '2026-03-31T09:15:00', + '2026-03-31T09:15Z', + '2026-03-31 09:15:00Z', + '2026-02-31T09:15:00Z', + '2026-03-31T24:00:00Z', + '2026-03-31T09:60:00Z', + '2026-03-31T09:15:00+25:00', + ])('rejects %s', (value) => { + expect(validateNode({ type: 'note', title: 'Test', updated: value })).toBe(false); + }); + }); + + describe('format: "date-or-date-time" schema validation', () => { + it.each([ + '2026-03-31', + '2026-03-31T09:15:00Z', + '2026-03-31T09:15:00+10:00', + '2026-03-31T09:15:00', + '2026-03-31T09:15', + ])('accepts %s', (value) => { + expect(validateNode({ type: 'note', title: 'Test', when: value })).toBe(true); + }); + + it.each(['2026-02-29', '2026-03-31T25:00', '2026-03-31 09:15', '31/03/2026', 'today'])('rejects %s', (value) => { + expect(validateNode({ type: 'note', title: 'Test', when: value })).toBe(false); + }); + }); +}); diff --git a/tests/validate/okf.test.ts b/tests/validate/okf.test.ts new file mode 100644 index 0000000..301ecc4 --- /dev/null +++ b/tests/validate/okf.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'bun:test'; +import { join } from 'node:path'; +import { bundledSchemasDir, createValidator } from '../../src/schema/schema'; +import { validateSpace } from '../../src/validate'; +import { makeSpaceContext } from '../helpers/context'; + +const OKF_SCHEMA_PATH = join(bundledSchemasDir, 'okf.json'); +const BUNDLE_DIR = join(import.meta.dir, '../fixtures/okf/bundle'); +const RULE_VIOLATIONS_DIR = join(import.meta.dir, '../fixtures/okf/rule-violations'); + +const validateNode = createValidator(OKF_SCHEMA_PATH); +const ts = '2026-06-20T22:53:05Z'; +const valid = (data: Record) => validateNode({ title: 't', ...data }); + +describe('OKF schema', () => { + it('accepts a concept carrying only `type`, with any type value', () => { + expect(valid({ type: 'Reference' })).toBe(true); + expect(valid({ type: 'Something Nobody Registered' })).toBe(true); + }); + + it('requires `type`', () => { + expect(valid({})).toBe(false); + }); + + it('tolerates unknown extension keys', () => { + expect(valid({ type: 'Metric', vendor: { nested: [1, 2] } })).toBe(true); + }); + + it('accepts provenance, trust and lifecycle families', () => { + expect( + valid({ + type: 'Metric', + description: 'd', + resource: 'https://example.com/x', + tags: ['a'], + sources: [ + { resource: 'all queries in project X', usage_count: 3, last_modified: ts, author: 'team:docs' }, + { id: 'a', resource: '/references/a.md' }, + ], + usage_window: { from: ts, to: '2026-07-01T00:00:00+10:00' }, + generated: { by: 'agent/1', at: ts }, + verified: [{ by: 'human:a', at: ts }], + status: 'draft', + stale_after: '2026-09-23T00:00:00Z', + }), + ).toBe(true); + }); + + it('accepts `verified` as a bare mapping', () => { + expect(valid({ type: 'Metric', verified: { by: 'human:a', at: ts } })).toBe(true); + }); + + it.each([ + ['date-only timestamp', { generated: { by: 'a/1', at: '2026-06-20' } }], + ['timestamp without offset', { stale_after: '2026-09-23T00:00:00' }], + ['unknown status', { status: 'archived' }], + ['source without resource', { sources: [{ id: 'a' }] }], + ['generated without by', { generated: { at: ts } }], + ['verified without at', { verified: { by: 'human:a' } }], + ['non-list tags', { tags: 'a' }], + ])('rejects %s', (_name, extra) => { + expect(valid({ type: 'Metric', ...extra })).toBe(false); + }); + + it('requires runtime on Attested Computation and validates its contract fields', () => { + const ac = { type: 'Attested Computation', runtime: 'bigquery' }; + expect(valid(ac)).toBe(true); + expect(valid({ type: 'Attested Computation' })).toBe(false); + expect(valid({ ...ac, parameters: [{ name: 'year', type: 'integer', required: true }] })).toBe(true); + expect(valid({ ...ac, parameters: [{ type: 'integer' }] })).toBe(false); + expect(valid({ ...ac, executor: { resource: 'r.md', receipt: ['job_id'] }, attester: { resource: 'a.py' } })).toBe( + true, + ); + expect(valid({ ...ac, executor: { receipt: ['job_id'] } })).toBe(false); + expect(valid({ ...ac, attester: {} })).toBe(false); + }); +}); + +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(result.validCount).toBe(4); + expect(result.parseIssues.map((i) => i.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.file, 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.file}:${v.ruleId}`).sort()).toEqual([ + 'no-computation.md:okf-computation-present', + 'stale-before-generated.md:okf-stale-after-generated', + 'usage-without-window.md:okf-usage-count-window', + ]); + }); +});