diff --git a/docs/oss/attribution.md b/docs/oss/attribution.md index 0b7a9ac..9e54814 100644 --- a/docs/oss/attribution.md +++ b/docs/oss/attribution.md @@ -289,3 +289,39 @@ License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) | [LICENSE](https://github.com/aws/smithy-go/blob/e094f45e716e33a1b950cf8bbe804790bf87f965/internal/sync/singleflight/LICENSE). [Source](https://github.com/aws/smithy-go/commit/e094f45e716e33a1b950cf8bbe804790bf87f965). + +## JSON Schema + +Selected module: `github.com/santhosh-tekuri/jsonschema/v6` at `v6.0.3`. + +SPDX-License-Identifier: Apache-2.0 + +License and notices: [Apache 2.0](licenses/Apache-2.0.txt) | +[LICENSE](https://github.com/santhosh-tekuri/jsonschema/blob/b0fc661f4939578bc429f408c18202573dbafcc4/LICENSE). + +[Source](https://github.com/santhosh-tekuri/jsonschema/commit/b0fc661f4939578bc429f408c18202573dbafcc4). + +## Go text extension + +Selected module: `golang.org/x/text` at `v0.14.0`. + +Copyright 2009 The Go Authors. + +SPDX-License-Identifier: BSD-3-Clause + +License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) | +[LICENSE](https://github.com/golang/text/blob/6c97a165dd661335ff7bce6104a008558123c353/LICENSE) | +[PATENTS](https://github.com/golang/text/blob/6c97a165dd661335ff7bce6104a008558123c353/PATENTS). + +[Source](https://github.com/golang/text/commit/6c97a165dd661335ff7bce6104a008558123c353). + +## Narratio reference catalog + +Material: `internal/glossary/glossary-v1.schema.json`. + +SPDX-License-Identifier: CC0-1.0 + +License and notices: [CC0 1.0](licenses/CC0-1.0.txt) | +[LICENSE](https://forge.maximumdirect.net/eric/narratio-reference-catalog/src/commit/ecad94a5a53f87847b1fd81fd042eee9c8d3ea08/LICENSE). + +[Source](https://forge.maximumdirect.net/eric/narratio-reference-catalog/src/commit/ecad94a5a53f87847b1fd81fd042eee9c8d3ea08). diff --git a/docs/oss/licenses/CC0-1.0.txt b/docs/oss/licenses/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/docs/oss/licenses/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 5695659..ccd2b18 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -114,7 +114,14 @@ compatibility checking is completed in Stage 17. ## Stage 2. Add the shared glossary model and pinned schema validation -Status: Pending +Status: Complete + +Embedded the verbatim schema from catalog revision +`ecad94a5a53f87847b1fd81fd042eee9c8d3ea08`, added offline JSON Schema +validation and collection-scoped ID checks, and recorded dependency notices. +Verified with `go test ./internal/glossary ./internal/doccheck` and a bytewise +schema comparison. Integration with acquisition and preparation follows in +later stages. Read roadmap “Canonical glossary format” and Audita's native input contract. Create `internal/glossary` with native collection/entry representations retaining diff --git a/go.mod b/go.mod index 7baed94..2eb073a 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 github.com/aws/smithy-go v1.25.1 github.com/google/go-cmp v0.7.0 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 go.maximumdirect.net/ckconfig v0.11.0 go.maximumdirect.net/commandkit v0.8.0 go.maximumdirect.net/configkit v1.4.0 @@ -38,6 +39,7 @@ require ( github.com/yuin/goldmark/v2 v2.1.16 // indirect go.yaml.in/yaml/v4 v4.0.0 // indirect golang.org/x/mod v0.43.0 // indirect + golang.org/x/text v0.14.0 // indirect ) tool go.maximumdirect.net/releasekit/cmd/releasekit diff --git a/go.sum b/go.sum index df62348..32c57a7 100644 --- a/go.sum +++ b/go.sum @@ -35,11 +35,15 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7 github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI= github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -64,6 +68,8 @@ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/glossary/glossary-v1.schema.json b/internal/glossary/glossary-v1.schema.json new file mode 100644 index 0000000..f2af736 --- /dev/null +++ b/internal/glossary/glossary-v1.schema.json @@ -0,0 +1,85 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json", + "title": "Glossary named collections v1", + "$ref": "#/$defs/document", + "$defs": { + "entry": { + "type": "object", + "required": [ + "id", + "name", + "category" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + }, + "category": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "plural": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": true + }, + "partialCollection": { + "type": "object", + "properties": { + "instruction": { + "type": "string" + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/$defs/entry" + } + } + }, + "additionalProperties": false + }, + "collection": { + "allOf": [ + { + "$ref": "#/$defs/partialCollection" + }, + { + "required": [ + "entries" + ] + } + ] + }, + "document": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/collection" + } + } + } +} diff --git a/internal/glossary/glossary.go b/internal/glossary/glossary.go new file mode 100644 index 0000000..b25bd2b --- /dev/null +++ b/internal/glossary/glossary.go @@ -0,0 +1,159 @@ +// Package glossary owns the shared native glossary representation and validation. +package glossary + +import ( + "bytes" + _ "embed" + "encoding/json" + "fmt" + "sort" + "sync" + + "github.com/santhosh-tekuri/jsonschema/v6" +) + +// Collection preserves an explicitly supplied empty instruction. +type Collection struct { + Instruction *string `yaml:"instruction,omitempty" json:"instruction,omitempty"` + Entries []Entry `yaml:"entries" json:"entries"` +} + +// Entry retains native fields and any additional vocabulary metadata. +type Entry struct { + ID string `yaml:"id" json:"id"` + Name string `yaml:"name" json:"name"` + Category string `yaml:"category" json:"category"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"` + Plural *string `yaml:"plural,omitempty" json:"plural,omitempty"` + Extra map[string]any `yaml:",inline" json:"-"` +} + +// MarshalJSON retains extension fields when validating or serializing typed entries. +func (entry Entry) MarshalJSON() ([]byte, error) { + type fields Entry + b, err := json.Marshal(fields(entry)) + if err != nil { + return nil, err + } + var result map[string]any + if err := json.Unmarshal(b, &result); err != nil { + return nil, err + } + for key, value := range entry.Extra { + if _, known := result[key]; !known { + result[key] = value + } + } + return json.Marshal(result) +} + +// CatalogRevision identifies the upstream source of the embedded schema. +const CatalogRevision = "ecad94a5a53f87847b1fd81fd042eee9c8d3ea08" + +//go:embed glossary-v1.schema.json +var schemaData []byte + +const schemaURL = "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json" + +var compiled struct { + sync.Once + document, partial *jsonschema.Schema + err error +} + +type offlineLoader struct{} + +func (offlineLoader) Load(url string) (any, error) { + return nil, fmt.Errorf("schema resource unavailable: %s", url) +} + +func schemas() (*jsonschema.Schema, *jsonschema.Schema, error) { + compiled.Do(func() { + var doc any + if compiled.err = json.Unmarshal(schemaData, &doc); compiled.err != nil { + return + } + c := jsonschema.NewCompiler() + c.UseLoader(offlineLoader{}) + if compiled.err = c.AddResource(schemaURL, doc); compiled.err != nil { + return + } + if compiled.document, compiled.err = c.Compile(schemaURL); compiled.err != nil { + return + } + compiled.partial, compiled.err = c.Compile(schemaURL + "#/$defs/partialCollection") + }) + return compiled.document, compiled.partial, compiled.err +} + +// ValidatePartial validates a decoded collection contribution without requiring entries. +func ValidatePartial(value any) error { + _, schema, err := schemas() + if err != nil { + return fmt.Errorf("compile glossary schema: %w", err) + } + v, err := jsonValue(value) + if err != nil { + return err + } + if err := schema.Validate(v); err != nil { + return fmt.Errorf("glossary contribution: %w", err) + } + return nil +} + +// ValidateDocument validates decoded complete named collections and their IDs. +func ValidateDocument(value any) error { + schema, _, err := schemas() + if err != nil { + return fmt.Errorf("compile glossary schema: %w", err) + } + v, err := jsonValue(value) + if err != nil { + return err + } + if err := schema.Validate(v); err != nil { + return fmt.Errorf("glossary document: %w", err) + } + doc := v.(map[string]any) + names := make([]string, 0, len(doc)) + for name := range doc { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + if err := uniqueIDs("collection "+name, doc[name]); err != nil { + return err + } + } + return nil +} + +func jsonValue(value any) (any, error) { + data, err := json.Marshal(value) + if err != nil { + return nil, fmt.Errorf("encode glossary data: %w", err) + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var result any + if err := decoder.Decode(&result); err != nil { + return nil, fmt.Errorf("decode glossary data: %w", err) + } + return result, nil +} + +func uniqueIDs(context string, value any) error { + collection := value.(map[string]any) + entries, _ := collection["entries"].([]any) + seen := make(map[string]bool, len(entries)) + for _, raw := range entries { + id := raw.(map[string]any)["id"].(string) + if seen[id] { + return fmt.Errorf("%s: duplicate entry id %q", context, id) + } + seen[id] = true + } + return nil +} diff --git a/internal/glossary/glossary_test.go b/internal/glossary/glossary_test.go new file mode 100644 index 0000000..c050795 --- /dev/null +++ b/internal/glossary/glossary_test.go @@ -0,0 +1,63 @@ +package glossary + +import ( + "encoding/json" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestValidation(t *testing.T) { + for _, tc := range []struct { + name, input string + partial, valid bool + }{ + {"empty", "party: {entries: []}", false, true}, + {"missing entries", "party: {instruction: hi}", false, false}, + {"instruction only", "instruction: hi", true, true}, + {"optional and extensions", "party: {entries: [{id: a, name: A, category: person, aliases: [Alias], plural: People, description: text, extra: {rank: 2}}]}", false, true}, + {"missing category", "party: {entries: [{id: a, name: A}]}", false, false}, + {"duplicate within collection", "party: {entries: [{id: a, name: A, category: person}, {id: a, name: B, category: person}]}", false, false}, + {"same id across collections", "party: {entries: [{id: a, name: A, category: person}]}\nother: {entries: [{id: a, name: B, category: person}]}", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var value any + if err := yaml.Unmarshal([]byte(tc.input), &value); err != nil { + t.Fatal(err) + } + var err error + if tc.partial { + err = ValidatePartial(value) + } else { + err = ValidateDocument(value) + } + if (err == nil) != tc.valid { + t.Fatalf("valid=%v: %v", tc.valid, err) + } + if tc.name == "duplicate within collection" && !strings.Contains(err.Error(), "party") { + t.Fatal(err) + } + }) + } +} + +func TestTypedCollectionRetainsExtensionsAndEmptyInstruction(t *testing.T) { + var collection Collection + if err := yaml.Unmarshal([]byte("instruction: ''\nentries: [{id: a, name: A, category: person, source_note: test}]\n"), &collection); err != nil { + t.Fatal(err) + } + if collection.Instruction == nil || *collection.Instruction != "" || collection.Entries[0].Extra["source_note"] != "test" { + t.Fatalf("lost data: %+v", collection) + } + b, err := json.Marshal(map[string]Collection{"party": collection}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), `"source_note":"test"`) || !strings.Contains(string(b), `"instruction":""`) { + t.Fatalf("lost data: %s", b) + } + if err := ValidateDocument(map[string]Collection{"party": collection}); err != nil { + t.Fatal(err) + } +}