@ggui-ai/negotiator 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +49 -0
  3. package/dist/contract-hash.d.ts +54 -0
  4. package/dist/contract-hash.d.ts.map +1 -0
  5. package/dist/contract-hash.js +96 -0
  6. package/dist/contract-validators.d.ts +171 -0
  7. package/dist/contract-validators.d.ts.map +1 -0
  8. package/dist/contract-validators.js +478 -0
  9. package/dist/decision-input.d.ts +48 -0
  10. package/dist/decision-input.d.ts.map +1 -0
  11. package/dist/decision-input.js +14 -0
  12. package/dist/decision.d.ts +54 -0
  13. package/dist/decision.d.ts.map +1 -0
  14. package/dist/decision.js +500 -0
  15. package/dist/index.d.ts +36 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +25 -0
  18. package/dist/intent.d.ts +22 -0
  19. package/dist/intent.d.ts.map +1 -0
  20. package/dist/intent.js +28 -0
  21. package/dist/llm-caller.d.ts +70 -0
  22. package/dist/llm-caller.d.ts.map +1 -0
  23. package/dist/llm-caller.js +38 -0
  24. package/dist/llm-rerank.d.ts +101 -0
  25. package/dist/llm-rerank.d.ts.map +1 -0
  26. package/dist/llm-rerank.js +178 -0
  27. package/dist/negotiate.d.ts +141 -0
  28. package/dist/negotiate.d.ts.map +1 -0
  29. package/dist/negotiate.js +161 -0
  30. package/dist/normalize-schema.d.ts +22 -0
  31. package/dist/normalize-schema.d.ts.map +1 -0
  32. package/dist/normalize-schema.js +191 -0
  33. package/dist/pure.d.ts +30 -0
  34. package/dist/pure.d.ts.map +1 -0
  35. package/dist/pure.js +43 -0
  36. package/dist/rag-search.d.ts +73 -0
  37. package/dist/rag-search.d.ts.map +1 -0
  38. package/dist/rag-search.js +192 -0
  39. package/dist/rerank-eval/pairs.d.ts +28 -0
  40. package/dist/rerank-eval/pairs.d.ts.map +1 -0
  41. package/dist/rerank-eval/pairs.js +531 -0
  42. package/dist/rerank-eval/run-probe-cli.d.ts +3 -0
  43. package/dist/rerank-eval/run-probe-cli.d.ts.map +1 -0
  44. package/dist/rerank-eval/run-probe-cli.js +146 -0
  45. package/dist/rerank-eval/run-probe.d.ts +68 -0
  46. package/dist/rerank-eval/run-probe.d.ts.map +1 -0
  47. package/dist/rerank-eval/run-probe.js +113 -0
  48. package/dist/session.d.ts +42 -0
  49. package/dist/session.d.ts.map +1 -0
  50. package/dist/session.js +21 -0
  51. package/dist/suggestion.d.ts +38 -0
  52. package/dist/suggestion.d.ts.map +1 -0
  53. package/dist/suggestion.js +47 -0
  54. package/dist/synth-bench/corpus.d.ts +106 -0
  55. package/dist/synth-bench/corpus.d.ts.map +1 -0
  56. package/dist/synth-bench/corpus.js +994 -0
  57. package/dist/synth-bench/run-bench-cli.d.ts +3 -0
  58. package/dist/synth-bench/run-bench-cli.d.ts.map +1 -0
  59. package/dist/synth-bench/run-bench-cli.js +181 -0
  60. package/dist/synth-bench/run-bench.d.ts +101 -0
  61. package/dist/synth-bench/run-bench.d.ts.map +1 -0
  62. package/dist/synth-bench/run-bench.js +374 -0
  63. package/dist/synthesize-contract.d.ts +131 -0
  64. package/dist/synthesize-contract.d.ts.map +1 -0
  65. package/dist/synthesize-contract.js +948 -0
  66. package/dist/types.d.ts +30 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +13 -0
  69. package/package.json +74 -0
  70. package/src/contract-hash.ts +102 -0
  71. package/src/contract-validators.ts +604 -0
  72. package/src/decision-input.ts +49 -0
  73. package/src/decision.ts +581 -0
  74. package/src/index.ts +63 -0
  75. package/src/intent.ts +37 -0
  76. package/src/llm-caller.ts +82 -0
  77. package/src/llm-rerank.ts +280 -0
  78. package/src/negotiate.ts +312 -0
  79. package/src/normalize-schema.ts +193 -0
  80. package/src/pure.ts +46 -0
  81. package/src/rag-search.ts +274 -0
  82. package/src/rerank-eval/pairs.ts +624 -0
  83. package/src/rerank-eval/run-probe-cli.ts +197 -0
  84. package/src/rerank-eval/run-probe.ts +198 -0
  85. package/src/session.ts +41 -0
  86. package/src/suggestion.ts +73 -0
  87. package/src/synth-bench/corpus.ts +1126 -0
  88. package/src/synth-bench/run-bench-cli.ts +237 -0
  89. package/src/synth-bench/run-bench.ts +525 -0
  90. package/src/synthesize-contract.ts +1161 -0
  91. package/src/types.ts +31 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Loqu, Inc. (Guuey)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @ggui-ai/negotiator
2
+
3
+ UI decision engine for [ggui](https://github.com/ggui-ai/ggui).
4
+
5
+ Given an agent's signal (data, prompt, context, agent tools) and the current
6
+ session state, the negotiator decides **which UI to render** — create a new
7
+ interface, update an existing one, compose with what's on screen, or replace
8
+ it — and, on the cold path, synthesizes the data contract that drives it.
9
+
10
+ The package is deployment-agnostic. It composes the storage interfaces
11
+ defined in `@ggui-ai/mcp-server-core` (`EmbeddingProvider`, `VectorStore`),
12
+ so concrete embedding and vector-store bindings plug in at the call site
13
+ without this package depending on any particular cloud vendor.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pnpm add @ggui-ai/negotiator
19
+ ```
20
+
21
+ ## What's in the box
22
+
23
+ - **`negotiate(deps, input)`** — top-level orchestrator. Runs RAG search over
24
+ registered blueprints, reads session state, fast-paths exact blueprint
25
+ hits, and otherwise calls the decision LLM.
26
+ - **`makeDecision(...)`** — the decision step in isolation: pick an action
27
+ (`create` / `update` / `compose` / `replace`) and a blueprint from the
28
+ candidate set.
29
+ - **`synthesizeContract(...)`** — cold-path contract synthesizer. Turns an
30
+ agent intent into a `DataContract` (props / context / action / stream
31
+ specs, plus gadget references), with a repair loop and a schema-validation
32
+ gate.
33
+ - **`ragSearch(...)`** — embedding + vector-store retrieval over the
34
+ blueprint corpus, composing the `@ggui-ai/mcp-server-core` interfaces.
35
+ - **`rerankCandidates(...)`** — LLM re-rank of retrieval candidates.
36
+ - **`validateContractStructure` / `validateContractNovelty`** — advisory
37
+ validators for the actions-vs-context placement rule.
38
+
39
+ ```ts
40
+ import { negotiate } from "@ggui-ai/negotiator";
41
+
42
+ const result = await negotiate(deps, input);
43
+ // result.action — "create" | "update" | "compose" | "replace"
44
+ // result.blueprint — the picked blueprint, if any
45
+ ```
46
+
47
+ ## License
48
+
49
+ Apache-2.0 — see [`../LICENSE`](../LICENSE).
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Contract Hashing — deterministic cache key from data contract.
3
+ *
4
+ * Uses RFC 8785 (JSON Canonicalization Scheme) for deterministic
5
+ * serialization, then SHA-256 for the hash.
6
+ *
7
+ * What's in the hash: intent only (the semantic identity).
8
+ * What's NOT in the hash: props, actions, stream (including per-channel source), adaptations.
9
+ *
10
+ * Why intent-only: The LLM generates slightly different prop descriptions
11
+ * each call, but the INTENT is deterministic (provided by the agent or
12
+ * generated once). Same intent = same component = same cached code.
13
+ * Props are passed at render time, not baked into the component.
14
+ *
15
+ * The `interaction` field was removed from `DataContract` in pre-launch
16
+ * cleanup (the four-spec surface — props/action/context/stream —
17
+ * describes the wire exhaustively); this function used to factor it in
18
+ * but no longer does. Old goldens were rotated when the field went away.
19
+ */
20
+ import type { DataContract } from '@ggui-ai/protocol';
21
+ /**
22
+ * Hash a data contract to a deterministic cache key.
23
+ *
24
+ * Hashes intent only — the semantic identity of the UI. Props,
25
+ * actions, stream specs are for code generation, not caching.
26
+ *
27
+ * `intent` is passed separately because `DataContract` itself does
28
+ * not carry an `intent` field — the outer pipeline owns intent
29
+ * (`story.intent` on `ggui_push`, the operator prompt for harness
30
+ * benchmarks). Threading intent into the hash keeps cache identity
31
+ * stable across negotiations: different intents produce different
32
+ * generated code (labels, copy, layout) even when the wire surface is
33
+ * identical.
34
+ *
35
+ * The `contract` argument is retained on the signature for forward
36
+ * compatibility — future cache-key fields (e.g., a structural
37
+ * fingerprint of the four specs) can be folded in without breaking
38
+ * call sites — but is not consulted by the current implementation.
39
+ *
40
+ * @param contract - The data contract from negotiation (unused today)
41
+ * @param intent - The outer pipeline's intent (story.intent on
42
+ * ggui_push). Empty/falsy values are dropped from the hash input.
43
+ * @returns Contract hash prefixed with `ch_` (e.g., `ch_a3f8b2c1e9d04567`)
44
+ */
45
+ export declare function hashContract(_contract: DataContract, intent: string): string;
46
+ /**
47
+ * Build a variant key from shell type and device category.
48
+ *
49
+ * @param shellType - Shell type (default: 'universal')
50
+ * @param deviceCategory - Device category (default: 'universal')
51
+ * @returns Variant string (e.g., 'fullscreen:mobile', 'universal:universal')
52
+ */
53
+ export declare function buildVariant(shellType?: string, deviceCategory?: string): string;
54
+ //# sourceMappingURL=contract-hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-hash.d.ts","sourceRoot":"","sources":["../src/contract-hash.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAiCtD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,YAAY,CAC1B,SAAS,EAAE,YAAY,EACvB,MAAM,EAAE,MAAM,GACb,MAAM,CAMR;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,SAAS,SAAc,EACvB,cAAc,SAAc,GAC3B,MAAM,CAER"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Contract Hashing — deterministic cache key from data contract.
3
+ *
4
+ * Uses RFC 8785 (JSON Canonicalization Scheme) for deterministic
5
+ * serialization, then SHA-256 for the hash.
6
+ *
7
+ * What's in the hash: intent only (the semantic identity).
8
+ * What's NOT in the hash: props, actions, stream (including per-channel source), adaptations.
9
+ *
10
+ * Why intent-only: The LLM generates slightly different prop descriptions
11
+ * each call, but the INTENT is deterministic (provided by the agent or
12
+ * generated once). Same intent = same component = same cached code.
13
+ * Props are passed at render time, not baked into the component.
14
+ *
15
+ * The `interaction` field was removed from `DataContract` in pre-launch
16
+ * cleanup (the four-spec surface — props/action/context/stream —
17
+ * describes the wire exhaustively); this function used to factor it in
18
+ * but no longer does. Old goldens were rotated when the field went away.
19
+ */
20
+ import { createHash } from 'node:crypto';
21
+ /**
22
+ * RFC 8785 JSON Canonicalization Scheme.
23
+ *
24
+ * Produces deterministic JSON by:
25
+ * - Sorting object keys lexicographically (recursive)
26
+ * - Normalizing numbers (no trailing zeros, no +0)
27
+ * - Removing undefined values
28
+ * - No whitespace
29
+ */
30
+ function canonicalize(value) {
31
+ if (value === null || value === undefined)
32
+ return 'null';
33
+ if (typeof value === 'boolean')
34
+ return value ? 'true' : 'false';
35
+ if (typeof value === 'number') {
36
+ if (!isFinite(value))
37
+ return 'null';
38
+ return Object.is(value, -0) ? '0' : String(value);
39
+ }
40
+ if (typeof value === 'string')
41
+ return JSON.stringify(value);
42
+ if (Array.isArray(value)) {
43
+ return '[' + value.map((v) => canonicalize(v)).join(',') + ']';
44
+ }
45
+ if (typeof value === 'object') {
46
+ const obj = value;
47
+ const keys = Object.keys(obj)
48
+ .filter((k) => obj[k] !== undefined)
49
+ .sort();
50
+ const entries = keys.map((k) => JSON.stringify(k) + ':' + canonicalize(obj[k]));
51
+ return '{' + entries.join(',') + '}';
52
+ }
53
+ return 'null';
54
+ }
55
+ /**
56
+ * Hash a data contract to a deterministic cache key.
57
+ *
58
+ * Hashes intent only — the semantic identity of the UI. Props,
59
+ * actions, stream specs are for code generation, not caching.
60
+ *
61
+ * `intent` is passed separately because `DataContract` itself does
62
+ * not carry an `intent` field — the outer pipeline owns intent
63
+ * (`story.intent` on `ggui_push`, the operator prompt for harness
64
+ * benchmarks). Threading intent into the hash keeps cache identity
65
+ * stable across negotiations: different intents produce different
66
+ * generated code (labels, copy, layout) even when the wire surface is
67
+ * identical.
68
+ *
69
+ * The `contract` argument is retained on the signature for forward
70
+ * compatibility — future cache-key fields (e.g., a structural
71
+ * fingerprint of the four specs) can be folded in without breaking
72
+ * call sites — but is not consulted by the current implementation.
73
+ *
74
+ * @param contract - The data contract from negotiation (unused today)
75
+ * @param intent - The outer pipeline's intent (story.intent on
76
+ * ggui_push). Empty/falsy values are dropped from the hash input.
77
+ * @returns Contract hash prefixed with `ch_` (e.g., `ch_a3f8b2c1e9d04567`)
78
+ */
79
+ export function hashContract(_contract, intent) {
80
+ const input = {};
81
+ if (intent)
82
+ input.intent = intent;
83
+ const canonical = canonicalize(input);
84
+ const hash = createHash('sha256').update(canonical).digest('hex');
85
+ return `ch_${hash.slice(0, 16)}`;
86
+ }
87
+ /**
88
+ * Build a variant key from shell type and device category.
89
+ *
90
+ * @param shellType - Shell type (default: 'universal')
91
+ * @param deviceCategory - Device category (default: 'universal')
92
+ * @returns Variant string (e.g., 'fullscreen:mobile', 'universal:universal')
93
+ */
94
+ export function buildVariant(shellType = 'universal', deviceCategory = 'universal') {
95
+ return `${shellType}:${deviceCategory}`;
96
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Programmatic safety validators for `DataContract` shapes.
3
+ *
4
+ * Two detectors live here:
5
+ *
6
+ * - {@link validateContractStructure} — pure structural heuristics that
7
+ * flag over-specified contracts without any runtime dependency. The
8
+ * load-bearing finding is `redundant-action`: an empty-payload
9
+ * `actionSpec` entry whose name parses as a mutator of an existing
10
+ * `contextSpec` slot. Real example that motivated this module: a
11
+ * synthesizer emitted both `actionSpec.increment` (empty payload)
12
+ * and `contextSpec.count` for a counter widget. The generator wired
13
+ * the increment button to `useAction("increment")`, dispatching to
14
+ * the agent instead of locally bumping the count slot — a button
15
+ * that looks right but does nothing. The structural fix is to
16
+ * declare `actionSpec[X]` IFF X is a discrete event the agent must
17
+ * witness; mutators of context slots use the slot setter.
18
+ *
19
+ * - {@link validateContractNovelty} — embeds the contract via the
20
+ * shared `summarizeContract` helper and computes cosine distance to
21
+ * the nearest registered blueprint. Distance above the threshold
22
+ * yields a `novel-shape` finding so operators can review before the
23
+ * contract pollutes the registry's neighborhood.
24
+ *
25
+ * Both validators return a `ContractValidationResult` carrying readonly
26
+ * findings — callers (synthesizer, registerBlueprint) decide how to act
27
+ * on warnings vs errors. Findings are deterministic; no LLM judgment.
28
+ */
29
+ import type { DataContract } from '@ggui-ai/protocol';
30
+ import type { EmbeddingProvider, VectorStore } from '@ggui-ai/mcp-server-core';
31
+ /**
32
+ * Discriminated finding kinds. Each kind documents a distinct
33
+ * structural signal — consumers MAY render them differently
34
+ * (`redundant-action` is a code smell on the synthesizer side;
35
+ * `novel-shape` is an operator-review prompt).
36
+ *
37
+ * Open-ended for forward compat: future detectors (e.g.,
38
+ * `unreachable-stream-channel`, `payload-collision`) add to the union
39
+ * without breaking consumers that switch with a default arm.
40
+ */
41
+ export type ContractValidationFindingKind = 'redundant-action' | 'novel-shape' | 'actions-vs-context-name-collision' | 'action-name-looks-state-y' | 'context-name-looks-action-y' | 'incoherent-no-data-surface' | 'context-props-name-collision' | (string & {});
42
+ /**
43
+ * One observation about a contract. `severity` is `'warn'` for
44
+ * heuristics that may produce false positives — current default for
45
+ * the structural detector. `'error'` is reserved for unambiguous
46
+ * contract bugs once we have evidence the heuristic doesn't false-
47
+ * positive at production volume.
48
+ */
49
+ export interface ContractValidationFinding {
50
+ readonly kind: ContractValidationFindingKind;
51
+ readonly severity: 'warn' | 'error';
52
+ readonly actionName?: string;
53
+ readonly slotName?: string;
54
+ readonly cosine?: number;
55
+ readonly hint: string;
56
+ }
57
+ export interface ContractValidationResult {
58
+ readonly findings: readonly ContractValidationFinding[];
59
+ }
60
+ /**
61
+ * Dependencies the novelty detector needs. Embedding provider + vector
62
+ * store are the same seams the negotiator's RAG path uses, so the
63
+ * novelty check operates over the production index without any extra
64
+ * infrastructure.
65
+ */
66
+ export interface ContractValidationNoveltyDeps {
67
+ readonly embedding: EmbeddingProvider;
68
+ readonly vectorStore: VectorStore;
69
+ /** Tenant / partition the nearest-neighbor query runs against. Same
70
+ * semantics as `RagSearchInput.scope`. */
71
+ readonly scope: string;
72
+ }
73
+ export interface ContractValidationNoveltyOptions {
74
+ /**
75
+ * Cosine distance threshold above which the contract is flagged as
76
+ * novel. Distance is `1 - cosine_similarity`. Default `0.8` —
77
+ * matches the negotiator's `RETRIEVAL_MIN_SCORE = 0.15` (=cosine
78
+ * similarity 0.15, distance 0.85) one-tail boundary, with a small
79
+ * buffer so contracts that hover near retrieval but slightly above
80
+ * still flag for review.
81
+ */
82
+ readonly thresholdCosine?: number;
83
+ }
84
+ /**
85
+ * Run the synchronous structural detectors against `contract`.
86
+ *
87
+ * Currently:
88
+ * - `redundant-action`: empty-payload action whose name parses as a
89
+ * mutator of an existing context slot.
90
+ *
91
+ * Returns an empty findings array for contracts that don't trip any
92
+ * heuristic.
93
+ */
94
+ export declare function validateContractStructure(contract: DataContract): ContractValidationResult;
95
+ /**
96
+ * Validate the actions-vs-context placement rule: actions drive agent
97
+ * turns, context observes state. Findings 1-3 are advisory `warn`;
98
+ * finding 4 (`context-props-name-collision`) is `error` — it is a
99
+ * SPEC §2.10 MUST. Synth pipelines use it as a self-check over their
100
+ * own output.
101
+ *
102
+ * Four findings:
103
+ *
104
+ * - `actions-vs-context-name-collision` — same key appears in both
105
+ * `actionSpec` AND `contextSpec`. Synth couldn't decide which
106
+ * bucket. Pick one.
107
+ *
108
+ * - `action-name-looks-state-y` — `actionSpec` entry name matches a
109
+ * state-mirror pattern (autosave, draft, typing, change, …). The
110
+ * thing might be observable state (continuous) rather than a
111
+ * turn-driving event. Consider `contextSpec`.
112
+ *
113
+ * - `context-name-looks-action-y` — `contextSpec` entry name matches
114
+ * a discrete-event pattern (submit, send, confirm, …). The thing
115
+ * might be a one-shot event the agent reacts to. Consider
116
+ * `actionSpec`.
117
+ *
118
+ * - `context-props-name-collision` (ERROR) — a `contextSpec` slot key
119
+ * equals a `propsSpec` property name. SPEC §2.10 MUST: the
120
+ * generated boilerplate would shadow the prop binding.
121
+ *
122
+ * Pure / synchronous / no dependencies. Safe to call on every synth
123
+ * output without measurable cost.
124
+ */
125
+ export declare function validateActionsVsContext(contract: DataContract): ContractValidationResult;
126
+ /**
127
+ * Validate that a contract is coherent with its intent. The only
128
+ * intent-aware validator: it reads the natural-language intent
129
+ * alongside the contract.
130
+ *
131
+ * One rule — `incoherent-no-data-surface`: the intent describes a
132
+ * data-bearing UI but the contract declares only EMPTY-payload
133
+ * actions, with no contextSpec / propsSpec / streamSpec /
134
+ * clientCapabilities. That contract is structurally degenerate — the
135
+ * agent gets a contentless event with nothing behind it. Emitted at
136
+ * `severity: 'error'` so the synth's repair loop retries (the
137
+ * contract is protocol-valid, so nothing else flags it).
138
+ *
139
+ * The empty-payload condition matters: an action that DOES carry a
140
+ * payload (e.g. an `autosave` action whose schema includes the draft
141
+ * text) gives the agent data through the payload — that is not
142
+ * degenerate and is NOT flagged.
143
+ *
144
+ * Pure / synchronous. The rule fires ONLY on the degenerate output —
145
+ * a correct contract for any data-bearing intent always has a
146
+ * surface, so it never false-positives on good output.
147
+ */
148
+ export declare function validateContractCoherence(contract: DataContract, intent: string): ContractValidationResult;
149
+ /**
150
+ * Run the cosine-distance novelty detector. Embeds the contract via
151
+ * `summarizeContract` and queries the vector store for the nearest
152
+ * neighbor in `scope`. Distance above `thresholdCosine` yields a
153
+ * `novel-shape` finding so operators see "this contract is far from
154
+ * anything we've registered — review encouraged" before it ships.
155
+ *
156
+ * Defaults to `severity: 'warn'`. Distance is computed as
157
+ * `1 - cosineSimilarity`; `VectorStore.query` returns
158
+ * cosine-similarity scores in `[0, 1]` per the seam contract.
159
+ *
160
+ * Empty index (no nearest neighbor in scope) ⇒ flag with
161
+ * `cosine: undefined` because a fresh registry will register
162
+ * everything as novel; operators learn that the registry is empty.
163
+ */
164
+ export declare function validateContractNovelty(contract: DataContract, deps: ContractValidationNoveltyDeps, options?: ContractValidationNoveltyOptions): Promise<ContractValidationResult>;
165
+ /**
166
+ * Render a findings array as a single human-readable line for use in
167
+ * synthesizer `reason` strings, cache trace events, and operator logs.
168
+ * Empty findings → empty string so callers can append unconditionally.
169
+ */
170
+ export declare function formatValidationFindings(result: ContractValidationResult): string;
171
+ //# sourceMappingURL=contract-validators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-validators.d.ts","sourceRoot":"","sources":["../src/contract-validators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,mBAAmB,CAAC;AAElE,OAAO,KAAK,EACV,iBAAiB,EACjB,WAAW,EACZ,MAAM,0BAA0B,CAAC;AAMlC;;;;;;;;;GASG;AACH,MAAM,MAAM,6BAA6B,GACrC,kBAAkB,GAClB,aAAa,GACb,mCAAmC,GACnC,2BAA2B,GAC3B,6BAA6B,GAC7B,4BAA4B,GAC5B,8BAA8B,GAC9B,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAElB;;;;;;GAMG;AACH,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,IAAI,EAAE,6BAA6B,CAAC;IAC7C,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;IACpC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAAQ,EAAE,SAAS,yBAAyB,EAAE,CAAC;CACzD;AAED;;;;;GAKG;AACH,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,CAAC,SAAS,EAAE,iBAAiB,CAAC;IACtC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC;8CAC0C;IAC1C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,gCAAgC;IAC/C;;;;;;;OAOG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CACnC;AAwJD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,YAAY,GACrB,wBAAwB,CAkC1B;AAsCD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,YAAY,GACrB,wBAAwB,CA8D1B;AAiCD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,YAAY,EACtB,MAAM,EAAE,MAAM,GACb,wBAAwB,CAoC1B;AAQD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,6BAA6B,EACnC,OAAO,GAAE,gCAAqC,GAC7C,OAAO,CAAC,wBAAwB,CAAC,CAkCnC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,wBAAwB,GAC/B,MAAM,CAKR"}