@contractspec/example.policy-safe-knowledge-assistant 3.7.17 → 3.7.18

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 (45) hide show
  1. package/.turbo/turbo-build.log +45 -45
  2. package/CHANGELOG.md +20 -0
  3. package/dist/browser/docs/index.js +3 -27
  4. package/dist/browser/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
  5. package/dist/browser/example.js +1 -37
  6. package/dist/browser/handlers/index.js +5 -334
  7. package/dist/browser/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
  8. package/dist/browser/index.js +7 -913
  9. package/dist/browser/orchestrator/buildAnswer.js +1 -73
  10. package/dist/browser/policy-safe-knowledge-assistant.feature.js +1 -64
  11. package/dist/browser/seed/fixtures.js +1 -35
  12. package/dist/browser/seed/index.js +1 -35
  13. package/dist/browser/seeders/index.js +2 -12
  14. package/dist/browser/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
  15. package/dist/browser/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
  16. package/dist/browser/ui/index.js +1 -420
  17. package/dist/docs/index.js +3 -27
  18. package/dist/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
  19. package/dist/example.js +1 -37
  20. package/dist/handlers/index.js +5 -334
  21. package/dist/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
  22. package/dist/index.js +7 -913
  23. package/dist/node/docs/index.js +3 -27
  24. package/dist/node/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
  25. package/dist/node/example.js +1 -37
  26. package/dist/node/handlers/index.js +5 -334
  27. package/dist/node/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
  28. package/dist/node/index.js +7 -913
  29. package/dist/node/orchestrator/buildAnswer.js +1 -73
  30. package/dist/node/policy-safe-knowledge-assistant.feature.js +1 -64
  31. package/dist/node/seed/fixtures.js +1 -35
  32. package/dist/node/seed/index.js +1 -35
  33. package/dist/node/seeders/index.js +2 -12
  34. package/dist/node/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
  35. package/dist/node/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
  36. package/dist/node/ui/index.js +1 -420
  37. package/dist/orchestrator/buildAnswer.js +1 -73
  38. package/dist/policy-safe-knowledge-assistant.feature.js +1 -64
  39. package/dist/seed/fixtures.js +1 -35
  40. package/dist/seed/index.js +1 -35
  41. package/dist/seeders/index.js +2 -12
  42. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
  43. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
  44. package/dist/ui/index.js +1 -420
  45. package/package.json +13 -13
@@ -1,154 +1 @@
1
- // src/ui/hooks/usePolicySafeKnowledgeAssistant.ts
2
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
3
- import { useCallback, useEffect, useMemo, useState } from "react";
4
- "use client";
5
- function isCitationLike(value) {
6
- if (!value || typeof value !== "object")
7
- return false;
8
- const v = value;
9
- return typeof v.kbSnapshotId === "string" && typeof v.sourceId === "string";
10
- }
11
- function toCitations(value) {
12
- if (!Array.isArray(value))
13
- return [];
14
- return value.filter(isCitationLike).map((c) => ({
15
- kbSnapshotId: c.kbSnapshotId,
16
- sourceId: c.sourceId,
17
- excerpt: c.excerpt
18
- }));
19
- }
20
- function usePolicySafeKnowledgeAssistant() {
21
- const { handlers, projectId } = useTemplateRuntime();
22
- const api = handlers.policySafeKnowledgeAssistant;
23
- const [state, setState] = useState({
24
- context: null,
25
- loading: true,
26
- error: null,
27
- lastAnswer: null,
28
- lastRuleId: null,
29
- lastRuleVersionId: null,
30
- lastSnapshotId: null,
31
- lastReviewTaskId: null
32
- });
33
- const refreshContext = useCallback(async () => {
34
- try {
35
- setState((s) => ({ ...s, loading: true, error: null }));
36
- const ctx = await api.getUserContext({ projectId });
37
- setState((s) => ({
38
- ...s,
39
- context: {
40
- locale: ctx.locale,
41
- jurisdiction: ctx.jurisdiction,
42
- allowedScope: ctx.allowedScope,
43
- kbSnapshotId: ctx.kbSnapshotId
44
- },
45
- loading: false
46
- }));
47
- } catch (e) {
48
- setState((s) => ({
49
- ...s,
50
- loading: false,
51
- error: e instanceof Error ? e : new Error("Unknown error")
52
- }));
53
- }
54
- }, [api, projectId]);
55
- useEffect(() => {
56
- refreshContext();
57
- }, [refreshContext]);
58
- const setContext = useCallback(async (input) => {
59
- const ctx = await api.setUserContext({ projectId, ...input });
60
- setState((s) => ({
61
- ...s,
62
- context: {
63
- locale: ctx.locale,
64
- jurisdiction: ctx.jurisdiction,
65
- allowedScope: ctx.allowedScope,
66
- kbSnapshotId: ctx.kbSnapshotId
67
- }
68
- }));
69
- }, [api, projectId]);
70
- const askAssistant = useCallback(async (question) => {
71
- const answerUnknown = await api.answer({ projectId, question });
72
- const answer = answerUnknown;
73
- setState((s) => ({
74
- ...s,
75
- lastAnswer: {
76
- refused: answer.refused,
77
- refusalReason: answer.refusalReason,
78
- sections: answer.sections,
79
- citations: toCitations(answerUnknown.citations)
80
- }
81
- }));
82
- }, [api, projectId]);
83
- const createDemoRule = useCallback(async () => {
84
- const rule = await api.createRule({
85
- projectId,
86
- jurisdiction: state.context?.jurisdiction ?? "EU",
87
- topicKey: "tax_reporting"
88
- });
89
- setState((s) => ({ ...s, lastRuleId: rule.id }));
90
- return rule.id;
91
- }, [api, projectId, state.context?.jurisdiction]);
92
- const upsertRuleVersion = useCallback(async (input) => {
93
- const rv = await api.upsertRuleVersion({
94
- projectId,
95
- ruleId: input.ruleId,
96
- content: input.content,
97
- sourceRefs: [{ sourceDocumentId: "src_demo", excerpt: "demo excerpt" }]
98
- });
99
- setState((s) => ({ ...s, lastRuleVersionId: rv.id }));
100
- return rv.id;
101
- }, [api, projectId]);
102
- const approveRuleVersion = useCallback(async (ruleVersionId) => {
103
- await api.approveRuleVersion({ ruleVersionId, approver: "demo_expert" });
104
- }, [api]);
105
- const publishSnapshot = useCallback(async () => {
106
- const snap = await api.publishSnapshot({
107
- projectId,
108
- jurisdiction: state.context?.jurisdiction ?? "EU",
109
- asOfDate: new Date("2026-02-01T00:00:00.000Z")
110
- });
111
- setState((s) => ({ ...s, lastSnapshotId: snap.id }));
112
- await refreshContext();
113
- return snap.id;
114
- }, [api, projectId, refreshContext, state.context?.jurisdiction]);
115
- const simulateHighRiskChangeAndApprove = useCallback(async (ruleVersionId) => {
116
- const cand = await api.createChangeCandidate({
117
- projectId,
118
- jurisdiction: state.context?.jurisdiction ?? "EU",
119
- diffSummary: "Simulated change (demo)",
120
- riskLevel: "high",
121
- proposedRuleVersionIds: [ruleVersionId]
122
- });
123
- const review = await api.createReviewTask({ changeCandidateId: cand.id });
124
- setState((s) => ({ ...s, lastReviewTaskId: review.id }));
125
- await api.submitDecision({
126
- reviewTaskId: review.id,
127
- decision: "approve",
128
- decidedByRole: "expert",
129
- decidedBy: "demo_expert"
130
- });
131
- await api.publishIfReady({
132
- jurisdiction: state.context?.jurisdiction ?? "EU"
133
- });
134
- return review.id;
135
- }, [api, projectId, state.context?.jurisdiction]);
136
- const derived = useMemo(() => ({ projectId }), [projectId]);
137
- return {
138
- state,
139
- derived,
140
- actions: {
141
- refreshContext,
142
- setContext,
143
- askAssistant,
144
- createDemoRule,
145
- upsertRuleVersion,
146
- approveRuleVersion,
147
- publishSnapshot,
148
- simulateHighRiskChangeAndApprove
149
- }
150
- };
151
- }
152
- export {
153
- usePolicySafeKnowledgeAssistant
154
- };
1
+ import{useTemplateRuntime as X}from"@contractspec/lib.example-shared-ui";import{useCallback as J,useEffect as Y,useMemo as Z,useState as _}from"react";function $(F){if(!F||typeof F!=="object")return!1;let j=F;return typeof j.kbSnapshotId==="string"&&typeof j.sourceId==="string"}function D(F){if(!Array.isArray(F))return[];return F.filter($).map((j)=>({kbSnapshotId:j.kbSnapshotId,sourceId:j.sourceId,excerpt:j.excerpt}))}function m(){let{handlers:F,projectId:j}=X(),z=F.policySafeKnowledgeAssistant,[G,E]=_({context:null,loading:!0,error:null,lastAnswer:null,lastRuleId:null,lastRuleVersionId:null,lastSnapshotId:null,lastReviewTaskId:null}),K=J(async()=>{try{E((y)=>({...y,loading:!0,error:null}));let b=await z.getUserContext({projectId:j});E((y)=>({...y,context:{locale:b.locale,jurisdiction:b.jurisdiction,allowedScope:b.allowedScope,kbSnapshotId:b.kbSnapshotId},loading:!1}))}catch(b){E((y)=>({...y,loading:!1,error:b instanceof Error?b:Error("Unknown error")}))}},[z,j]);Y(()=>{K()},[K]);let M=J(async(b)=>{let y=await z.setUserContext({projectId:j,...b});E((B)=>({...B,context:{locale:y.locale,jurisdiction:y.jurisdiction,allowedScope:y.allowedScope,kbSnapshotId:y.kbSnapshotId}}))},[z,j]),N=J(async(b)=>{let y=await z.answer({projectId:j,question:b}),B=y;E((L)=>({...L,lastAnswer:{refused:B.refused,refusalReason:B.refusalReason,sections:B.sections,citations:D(y.citations)}}))},[z,j]),O=J(async()=>{let b=await z.createRule({projectId:j,jurisdiction:G.context?.jurisdiction??"EU",topicKey:"tax_reporting"});return E((y)=>({...y,lastRuleId:b.id})),b.id},[z,j,G.context?.jurisdiction]),P=J(async(b)=>{let y=await z.upsertRuleVersion({projectId:j,ruleId:b.ruleId,content:b.content,sourceRefs:[{sourceDocumentId:"src_demo",excerpt:"demo excerpt"}]});return E((B)=>({...B,lastRuleVersionId:y.id})),y.id},[z,j]),Q=J(async(b)=>{await z.approveRuleVersion({ruleVersionId:b,approver:"demo_expert"})},[z]),S=J(async()=>{let b=await z.publishSnapshot({projectId:j,jurisdiction:G.context?.jurisdiction??"EU",asOfDate:new Date("2026-02-01T00:00:00.000Z")});return E((y)=>({...y,lastSnapshotId:b.id})),await K(),b.id},[z,j,K,G.context?.jurisdiction]),T=J(async(b)=>{let y=await z.createChangeCandidate({projectId:j,jurisdiction:G.context?.jurisdiction??"EU",diffSummary:"Simulated change (demo)",riskLevel:"high",proposedRuleVersionIds:[b]}),B=await z.createReviewTask({changeCandidateId:y.id});return E((L)=>({...L,lastReviewTaskId:B.id})),await z.submitDecision({reviewTaskId:B.id,decision:"approve",decidedByRole:"expert",decidedBy:"demo_expert"}),await z.publishIfReady({jurisdiction:G.context?.jurisdiction??"EU"}),B.id},[z,j,G.context?.jurisdiction]),W=Z(()=>({projectId:j}),[j]);return{state:G,derived:W,actions:{refreshContext:K,setContext:M,askAssistant:N,createDemoRule:O,upsertRuleVersion:P,approveRuleVersion:Q,publishSnapshot:S,simulateHighRiskChangeAndApprove:T}}}export{m as usePolicySafeKnowledgeAssistant};
@@ -1,420 +1 @@
1
- // src/ui/hooks/usePolicySafeKnowledgeAssistant.ts
2
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
3
- import { useCallback, useEffect, useMemo, useState } from "react";
4
- "use client";
5
- function isCitationLike(value) {
6
- if (!value || typeof value !== "object")
7
- return false;
8
- const v = value;
9
- return typeof v.kbSnapshotId === "string" && typeof v.sourceId === "string";
10
- }
11
- function toCitations(value) {
12
- if (!Array.isArray(value))
13
- return [];
14
- return value.filter(isCitationLike).map((c) => ({
15
- kbSnapshotId: c.kbSnapshotId,
16
- sourceId: c.sourceId,
17
- excerpt: c.excerpt
18
- }));
19
- }
20
- function usePolicySafeKnowledgeAssistant() {
21
- const { handlers, projectId } = useTemplateRuntime();
22
- const api = handlers.policySafeKnowledgeAssistant;
23
- const [state, setState] = useState({
24
- context: null,
25
- loading: true,
26
- error: null,
27
- lastAnswer: null,
28
- lastRuleId: null,
29
- lastRuleVersionId: null,
30
- lastSnapshotId: null,
31
- lastReviewTaskId: null
32
- });
33
- const refreshContext = useCallback(async () => {
34
- try {
35
- setState((s) => ({ ...s, loading: true, error: null }));
36
- const ctx = await api.getUserContext({ projectId });
37
- setState((s) => ({
38
- ...s,
39
- context: {
40
- locale: ctx.locale,
41
- jurisdiction: ctx.jurisdiction,
42
- allowedScope: ctx.allowedScope,
43
- kbSnapshotId: ctx.kbSnapshotId
44
- },
45
- loading: false
46
- }));
47
- } catch (e) {
48
- setState((s) => ({
49
- ...s,
50
- loading: false,
51
- error: e instanceof Error ? e : new Error("Unknown error")
52
- }));
53
- }
54
- }, [api, projectId]);
55
- useEffect(() => {
56
- refreshContext();
57
- }, [refreshContext]);
58
- const setContext = useCallback(async (input) => {
59
- const ctx = await api.setUserContext({ projectId, ...input });
60
- setState((s) => ({
61
- ...s,
62
- context: {
63
- locale: ctx.locale,
64
- jurisdiction: ctx.jurisdiction,
65
- allowedScope: ctx.allowedScope,
66
- kbSnapshotId: ctx.kbSnapshotId
67
- }
68
- }));
69
- }, [api, projectId]);
70
- const askAssistant = useCallback(async (question) => {
71
- const answerUnknown = await api.answer({ projectId, question });
72
- const answer = answerUnknown;
73
- setState((s) => ({
74
- ...s,
75
- lastAnswer: {
76
- refused: answer.refused,
77
- refusalReason: answer.refusalReason,
78
- sections: answer.sections,
79
- citations: toCitations(answerUnknown.citations)
80
- }
81
- }));
82
- }, [api, projectId]);
83
- const createDemoRule = useCallback(async () => {
84
- const rule = await api.createRule({
85
- projectId,
86
- jurisdiction: state.context?.jurisdiction ?? "EU",
87
- topicKey: "tax_reporting"
88
- });
89
- setState((s) => ({ ...s, lastRuleId: rule.id }));
90
- return rule.id;
91
- }, [api, projectId, state.context?.jurisdiction]);
92
- const upsertRuleVersion = useCallback(async (input) => {
93
- const rv = await api.upsertRuleVersion({
94
- projectId,
95
- ruleId: input.ruleId,
96
- content: input.content,
97
- sourceRefs: [{ sourceDocumentId: "src_demo", excerpt: "demo excerpt" }]
98
- });
99
- setState((s) => ({ ...s, lastRuleVersionId: rv.id }));
100
- return rv.id;
101
- }, [api, projectId]);
102
- const approveRuleVersion = useCallback(async (ruleVersionId) => {
103
- await api.approveRuleVersion({ ruleVersionId, approver: "demo_expert" });
104
- }, [api]);
105
- const publishSnapshot = useCallback(async () => {
106
- const snap = await api.publishSnapshot({
107
- projectId,
108
- jurisdiction: state.context?.jurisdiction ?? "EU",
109
- asOfDate: new Date("2026-02-01T00:00:00.000Z")
110
- });
111
- setState((s) => ({ ...s, lastSnapshotId: snap.id }));
112
- await refreshContext();
113
- return snap.id;
114
- }, [api, projectId, refreshContext, state.context?.jurisdiction]);
115
- const simulateHighRiskChangeAndApprove = useCallback(async (ruleVersionId) => {
116
- const cand = await api.createChangeCandidate({
117
- projectId,
118
- jurisdiction: state.context?.jurisdiction ?? "EU",
119
- diffSummary: "Simulated change (demo)",
120
- riskLevel: "high",
121
- proposedRuleVersionIds: [ruleVersionId]
122
- });
123
- const review = await api.createReviewTask({ changeCandidateId: cand.id });
124
- setState((s) => ({ ...s, lastReviewTaskId: review.id }));
125
- await api.submitDecision({
126
- reviewTaskId: review.id,
127
- decision: "approve",
128
- decidedByRole: "expert",
129
- decidedBy: "demo_expert"
130
- });
131
- await api.publishIfReady({
132
- jurisdiction: state.context?.jurisdiction ?? "EU"
133
- });
134
- return review.id;
135
- }, [api, projectId, state.context?.jurisdiction]);
136
- const derived = useMemo(() => ({ projectId }), [projectId]);
137
- return {
138
- state,
139
- derived,
140
- actions: {
141
- refreshContext,
142
- setContext,
143
- askAssistant,
144
- createDemoRule,
145
- upsertRuleVersion,
146
- approveRuleVersion,
147
- publishSnapshot,
148
- simulateHighRiskChangeAndApprove
149
- }
150
- };
151
- }
152
-
153
- // src/ui/PolicySafeKnowledgeAssistantDashboard.tsx
154
- import {
155
- Button,
156
- ErrorState,
157
- LoaderBlock,
158
- StatCard,
159
- StatCardGroup
160
- } from "@contractspec/lib.design-system";
161
- import { Card } from "@contractspec/lib.ui-kit-web/ui/card";
162
- import { Input } from "@contractspec/lib.ui-kit-web/ui/input";
163
- import {
164
- Select,
165
- SelectContent,
166
- SelectItem,
167
- SelectTrigger,
168
- SelectValue
169
- } from "@contractspec/lib.ui-kit-web/ui/select";
170
- import { Textarea } from "@contractspec/lib.ui-kit-web/ui/textarea";
171
- import { useCallback as useCallback2, useMemo as useMemo2, useState as useState2 } from "react";
172
- import { jsxDEV } from "react/jsx-dev-runtime";
173
- "use client";
174
- function PolicySafeKnowledgeAssistantDashboard() {
175
- const { state, actions } = usePolicySafeKnowledgeAssistant();
176
- const [question, setQuestion] = useState2("reporting obligations");
177
- const [content, setContent] = useState2("EU: Reporting obligations v2 (updated)");
178
- const [locale, setLocale] = useState2("en-GB");
179
- const [jurisdiction, setJurisdiction] = useState2("EU");
180
- const [allowedScope, setAllowedScope] = useState2("education_only");
181
- const snapshotId = state.context?.kbSnapshotId ?? state.lastSnapshotId ?? null;
182
- const stats = useMemo2(() => {
183
- return [
184
- { label: "Locale", value: state.context?.locale ?? "—" },
185
- { label: "Jurisdiction", value: state.context?.jurisdiction ?? "—" },
186
- { label: "Scope", value: state.context?.allowedScope ?? "—" },
187
- { label: "KB Snapshot", value: snapshotId ?? "—" }
188
- ];
189
- }, [
190
- snapshotId,
191
- state.context?.allowedScope,
192
- state.context?.jurisdiction,
193
- state.context?.locale
194
- ]);
195
- const handleSetContext = useCallback2(async () => {
196
- await actions.setContext({ locale, jurisdiction, allowedScope });
197
- }, [actions, allowedScope, jurisdiction, locale]);
198
- const handleAsk = useCallback2(async () => {
199
- await actions.askAssistant(question);
200
- }, [actions, question]);
201
- const handleAdminPublishFlow = useCallback2(async () => {
202
- const ruleId = state.lastRuleId ?? await actions.createDemoRule();
203
- const rvId = await actions.upsertRuleVersion({ ruleId, content });
204
- await actions.approveRuleVersion(rvId);
205
- await actions.simulateHighRiskChangeAndApprove(rvId);
206
- await actions.publishSnapshot();
207
- }, [actions, content, state.lastRuleId]);
208
- if (state.loading && !state.context) {
209
- return /* @__PURE__ */ jsxDEV(LoaderBlock, {
210
- label: "Loading demo..."
211
- }, undefined, false, undefined, this);
212
- }
213
- if (state.error) {
214
- return /* @__PURE__ */ jsxDEV(ErrorState, {
215
- title: "Failed to load demo",
216
- description: state.error.message,
217
- onRetry: actions.refreshContext,
218
- retryLabel: "Retry"
219
- }, undefined, false, undefined, this);
220
- }
221
- return /* @__PURE__ */ jsxDEV("div", {
222
- className: "space-y-6",
223
- children: [
224
- /* @__PURE__ */ jsxDEV(StatCardGroup, {
225
- children: stats.map((s) => /* @__PURE__ */ jsxDEV(StatCard, {
226
- label: s.label,
227
- value: String(s.value)
228
- }, s.label, false, undefined, this))
229
- }, undefined, false, undefined, this),
230
- /* @__PURE__ */ jsxDEV(Card, {
231
- className: "p-4",
232
- children: [
233
- /* @__PURE__ */ jsxDEV("h3", {
234
- className: "font-semibold text-lg",
235
- children: "1) Onboarding (explicit locale + jurisdiction)"
236
- }, undefined, false, undefined, this),
237
- /* @__PURE__ */ jsxDEV("div", {
238
- className: "mt-3 grid gap-3 md:grid-cols-3",
239
- children: [
240
- /* @__PURE__ */ jsxDEV("div", {
241
- children: [
242
- /* @__PURE__ */ jsxDEV("div", {
243
- className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
244
- children: "Locale"
245
- }, undefined, false, undefined, this),
246
- /* @__PURE__ */ jsxDEV(Input, {
247
- value: locale,
248
- onChange: (e) => setLocale(e.target.value)
249
- }, undefined, false, undefined, this)
250
- ]
251
- }, undefined, true, undefined, this),
252
- /* @__PURE__ */ jsxDEV("div", {
253
- children: [
254
- /* @__PURE__ */ jsxDEV("div", {
255
- className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
256
- children: "Jurisdiction"
257
- }, undefined, false, undefined, this),
258
- /* @__PURE__ */ jsxDEV(Input, {
259
- value: jurisdiction,
260
- onChange: (e) => setJurisdiction(e.target.value)
261
- }, undefined, false, undefined, this)
262
- ]
263
- }, undefined, true, undefined, this),
264
- /* @__PURE__ */ jsxDEV("div", {
265
- children: [
266
- /* @__PURE__ */ jsxDEV("div", {
267
- className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
268
- children: "Allowed scope"
269
- }, undefined, false, undefined, this),
270
- /* @__PURE__ */ jsxDEV(Select, {
271
- value: allowedScope,
272
- onValueChange: (v) => setAllowedScope(v),
273
- children: [
274
- /* @__PURE__ */ jsxDEV(SelectTrigger, {
275
- children: /* @__PURE__ */ jsxDEV(SelectValue, {
276
- placeholder: "Select scope"
277
- }, undefined, false, undefined, this)
278
- }, undefined, false, undefined, this),
279
- /* @__PURE__ */ jsxDEV(SelectContent, {
280
- children: [
281
- /* @__PURE__ */ jsxDEV(SelectItem, {
282
- value: "education_only",
283
- children: "education_only"
284
- }, undefined, false, undefined, this),
285
- /* @__PURE__ */ jsxDEV(SelectItem, {
286
- value: "generic_info",
287
- children: "generic_info"
288
- }, undefined, false, undefined, this),
289
- /* @__PURE__ */ jsxDEV(SelectItem, {
290
- value: "escalation_required",
291
- children: "escalation_required"
292
- }, undefined, false, undefined, this)
293
- ]
294
- }, undefined, true, undefined, this)
295
- ]
296
- }, undefined, true, undefined, this)
297
- ]
298
- }, undefined, true, undefined, this)
299
- ]
300
- }, undefined, true, undefined, this),
301
- /* @__PURE__ */ jsxDEV("div", {
302
- className: "mt-4 flex gap-2",
303
- children: [
304
- /* @__PURE__ */ jsxDEV(Button, {
305
- onPress: handleSetContext,
306
- children: "Save context"
307
- }, undefined, false, undefined, this),
308
- /* @__PURE__ */ jsxDEV(Button, {
309
- variant: "outline",
310
- onPress: actions.refreshContext,
311
- children: "Refresh"
312
- }, undefined, false, undefined, this)
313
- ]
314
- }, undefined, true, undefined, this)
315
- ]
316
- }, undefined, true, undefined, this),
317
- /* @__PURE__ */ jsxDEV(Card, {
318
- className: "p-4",
319
- children: [
320
- /* @__PURE__ */ jsxDEV("h3", {
321
- className: "font-semibold text-lg",
322
- children: "2) Ask the assistant (must cite KB snapshot)"
323
- }, undefined, false, undefined, this),
324
- /* @__PURE__ */ jsxDEV("div", {
325
- className: "mt-3 flex flex-col gap-3",
326
- children: [
327
- /* @__PURE__ */ jsxDEV(Input, {
328
- value: question,
329
- onChange: (e) => setQuestion(e.target.value)
330
- }, undefined, false, undefined, this),
331
- /* @__PURE__ */ jsxDEV("div", {
332
- className: "flex gap-2",
333
- children: /* @__PURE__ */ jsxDEV(Button, {
334
- onPress: handleAsk,
335
- children: "Ask"
336
- }, undefined, false, undefined, this)
337
- }, undefined, false, undefined, this)
338
- ]
339
- }, undefined, true, undefined, this),
340
- state.lastAnswer ? /* @__PURE__ */ jsxDEV("div", {
341
- className: "mt-4 space-y-3",
342
- children: [
343
- state.lastAnswer.refused ? /* @__PURE__ */ jsxDEV("div", {
344
- className: "text-red-600 text-sm",
345
- children: [
346
- "Refused: ",
347
- state.lastAnswer.refusalReason ?? "UNKNOWN"
348
- ]
349
- }, undefined, true, undefined, this) : null,
350
- state.lastAnswer.sections.map((s, idx) => /* @__PURE__ */ jsxDEV("div", {
351
- children: [
352
- /* @__PURE__ */ jsxDEV("div", {
353
- className: "font-semibold text-sm",
354
- children: s.heading
355
- }, undefined, false, undefined, this),
356
- /* @__PURE__ */ jsxDEV("div", {
357
- className: "text-muted-foreground text-sm",
358
- children: s.body
359
- }, undefined, false, undefined, this)
360
- ]
361
- }, `${s.heading}-${idx}`, true, undefined, this)),
362
- /* @__PURE__ */ jsxDEV("div", {
363
- className: "font-semibold text-sm",
364
- children: "Citations"
365
- }, undefined, false, undefined, this),
366
- /* @__PURE__ */ jsxDEV("ul", {
367
- className: "list-disc pl-5 text-muted-foreground text-sm",
368
- children: state.lastAnswer.citations.map((c) => /* @__PURE__ */ jsxDEV("li", {
369
- children: [
370
- c.kbSnapshotId,
371
- " — ",
372
- c.sourceId
373
- ]
374
- }, `${c.kbSnapshotId}-${c.sourceId}`, true, undefined, this))
375
- }, undefined, false, undefined, this)
376
- ]
377
- }, undefined, true, undefined, this) : null
378
- ]
379
- }, undefined, true, undefined, this),
380
- /* @__PURE__ */ jsxDEV(Card, {
381
- className: "p-4",
382
- children: [
383
- /* @__PURE__ */ jsxDEV("h3", {
384
- className: "font-semibold text-lg",
385
- children: "3) Admin: publish a new snapshot (HITL)"
386
- }, undefined, false, undefined, this),
387
- /* @__PURE__ */ jsxDEV("div", {
388
- className: "mt-3 space-y-3",
389
- children: [
390
- /* @__PURE__ */ jsxDEV(Textarea, {
391
- value: content,
392
- onChange: (e) => setContent(e.target.value)
393
- }, undefined, false, undefined, this),
394
- /* @__PURE__ */ jsxDEV(Button, {
395
- onPress: handleAdminPublishFlow,
396
- children: "Simulate change → review → approve → publish snapshot"
397
- }, undefined, false, undefined, this)
398
- ]
399
- }, undefined, true, undefined, this)
400
- ]
401
- }, undefined, true, undefined, this),
402
- /* @__PURE__ */ jsxDEV(Card, {
403
- className: "p-4",
404
- children: [
405
- /* @__PURE__ */ jsxDEV("h3", {
406
- className: "font-semibold text-lg",
407
- children: "4) Learning hub (patterns)"
408
- }, undefined, false, undefined, this),
409
- /* @__PURE__ */ jsxDEV("p", {
410
- className: "mt-2 text-muted-foreground text-sm",
411
- children: "This template includes drills, ambient coach, and quests as reusable Learning Journey tracks. The interactive learning UI is demonstrated in dedicated Learning Journey examples."
412
- }, undefined, false, undefined, this)
413
- ]
414
- }, undefined, true, undefined, this)
415
- ]
416
- }, undefined, true, undefined, this);
417
- }
418
- export {
419
- PolicySafeKnowledgeAssistantDashboard
420
- };
1
+ import{useTemplateRuntime as f}from"@contractspec/lib.example-shared-ui";import{useCallback as G,useEffect as m,useMemo as A,useState as k}from"react";function v(O){if(!O||typeof O!=="object")return!1;let z=O;return typeof z.kbSnapshotId==="string"&&typeof z.sourceId==="string"}function I(O){if(!Array.isArray(O))return[];return O.filter(v).map((z)=>({kbSnapshotId:z.kbSnapshotId,sourceId:z.sourceId,excerpt:z.excerpt}))}function g(){let{handlers:O,projectId:z}=f(),Z=O.policySafeKnowledgeAssistant,[F,$]=k({context:null,loading:!0,error:null,lastAnswer:null,lastRuleId:null,lastRuleVersionId:null,lastSnapshotId:null,lastReviewTaskId:null}),H=G(async()=>{try{$((Y)=>({...Y,loading:!0,error:null}));let X=await Z.getUserContext({projectId:z});$((Y)=>({...Y,context:{locale:X.locale,jurisdiction:X.jurisdiction,allowedScope:X.allowedScope,kbSnapshotId:X.kbSnapshotId},loading:!1}))}catch(X){$((Y)=>({...Y,loading:!1,error:X instanceof Error?X:Error("Unknown error")}))}},[Z,z]);m(()=>{H()},[H]);let J=G(async(X)=>{let Y=await Z.setUserContext({projectId:z,...X});$((E)=>({...E,context:{locale:Y.locale,jurisdiction:Y.jurisdiction,allowedScope:Y.allowedScope,kbSnapshotId:Y.kbSnapshotId}}))},[Z,z]),K=G(async(X)=>{let Y=await Z.answer({projectId:z,question:X}),E=Y;$((W)=>({...W,lastAnswer:{refused:E.refused,refusalReason:E.refusalReason,sections:E.sections,citations:I(Y.citations)}}))},[Z,z]),M=G(async()=>{let X=await Z.createRule({projectId:z,jurisdiction:F.context?.jurisdiction??"EU",topicKey:"tax_reporting"});return $((Y)=>({...Y,lastRuleId:X.id})),X.id},[Z,z,F.context?.jurisdiction]),R=G(async(X)=>{let Y=await Z.upsertRuleVersion({projectId:z,ruleId:X.ruleId,content:X.content,sourceRefs:[{sourceDocumentId:"src_demo",excerpt:"demo excerpt"}]});return $((E)=>({...E,lastRuleVersionId:Y.id})),Y.id},[Z,z]),Q=G(async(X)=>{await Z.approveRuleVersion({ruleVersionId:X,approver:"demo_expert"})},[Z]),P=G(async()=>{let X=await Z.publishSnapshot({projectId:z,jurisdiction:F.context?.jurisdiction??"EU",asOfDate:new Date("2026-02-01T00:00:00.000Z")});return $((Y)=>({...Y,lastSnapshotId:X.id})),await H(),X.id},[Z,z,H,F.context?.jurisdiction]),L=G(async(X)=>{let Y=await Z.createChangeCandidate({projectId:z,jurisdiction:F.context?.jurisdiction??"EU",diffSummary:"Simulated change (demo)",riskLevel:"high",proposedRuleVersionIds:[X]}),E=await Z.createReviewTask({changeCandidateId:Y.id});return $((W)=>({...W,lastReviewTaskId:E.id})),await Z.submitDecision({reviewTaskId:E.id,decision:"approve",decidedByRole:"expert",decidedBy:"demo_expert"}),await Z.publishIfReady({jurisdiction:F.context?.jurisdiction??"EU"}),E.id},[Z,z,F.context?.jurisdiction]),b=A(()=>({projectId:z}),[z]);return{state:F,derived:b,actions:{refreshContext:H,setContext:J,askAssistant:K,createDemoRule:M,upsertRuleVersion:R,approveRuleVersion:Q,publishSnapshot:P,simulateHighRiskChangeAndApprove:L}}}import{Button as U,ErrorState as h,LoaderBlock as w,StatCard as C,StatCardGroup as S}from"@contractspec/lib.design-system";import{Card as y}from"@contractspec/lib.ui-kit-web/ui/card";import{Input as q}from"@contractspec/lib.ui-kit-web/ui/input";import{Select as d,SelectContent as p,SelectItem as B,SelectTrigger as u,SelectValue as j}from"@contractspec/lib.ui-kit-web/ui/select";import{Textarea as l}from"@contractspec/lib.ui-kit-web/ui/textarea";import{useCallback as V,useMemo as c,useState as D}from"react";import{jsx as N,jsxs as _}from"react/jsx-runtime";function Nz(){let{state:O,actions:z}=g(),[Z,F]=D("reporting obligations"),[$,H]=D("EU: Reporting obligations v2 (updated)"),[J,K]=D("en-GB"),[M,R]=D("EU"),[Q,P]=D("education_only"),L=O.context?.kbSnapshotId??O.lastSnapshotId??null,b=c(()=>{return[{label:"Locale",value:O.context?.locale??"—"},{label:"Jurisdiction",value:O.context?.jurisdiction??"—"},{label:"Scope",value:O.context?.allowedScope??"—"},{label:"KB Snapshot",value:L??"—"}]},[L,O.context?.allowedScope,O.context?.jurisdiction,O.context?.locale]),X=V(async()=>{await z.setContext({locale:J,jurisdiction:M,allowedScope:Q})},[z,Q,M,J]),Y=V(async()=>{await z.askAssistant(Z)},[z,Z]),E=V(async()=>{let W=O.lastRuleId??await z.createDemoRule(),T=await z.upsertRuleVersion({ruleId:W,content:$});await z.approveRuleVersion(T),await z.simulateHighRiskChangeAndApprove(T),await z.publishSnapshot()},[z,$,O.lastRuleId]);if(O.loading&&!O.context)return N(w,{label:"Loading demo..."});if(O.error)return N(h,{title:"Failed to load demo",description:O.error.message,onRetry:z.refreshContext,retryLabel:"Retry"});return _("div",{className:"space-y-6",children:[N(S,{children:b.map((W)=>N(C,{label:W.label,value:String(W.value)},W.label))}),_(y,{className:"p-4",children:[N("h3",{className:"font-semibold text-lg",children:"1) Onboarding (explicit locale + jurisdiction)"}),_("div",{className:"mt-3 grid gap-3 md:grid-cols-3",children:[_("div",{children:[N("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Locale"}),N(q,{value:J,onChange:(W)=>K(W.target.value)})]}),_("div",{children:[N("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Jurisdiction"}),N(q,{value:M,onChange:(W)=>R(W.target.value)})]}),_("div",{children:[N("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Allowed scope"}),_(d,{value:Q,onValueChange:(W)=>P(W),children:[N(u,{children:N(j,{placeholder:"Select scope"})}),_(p,{children:[N(B,{value:"education_only",children:"education_only"}),N(B,{value:"generic_info",children:"generic_info"}),N(B,{value:"escalation_required",children:"escalation_required"})]})]})]})]}),_("div",{className:"mt-4 flex gap-2",children:[N(U,{onPress:X,children:"Save context"}),N(U,{variant:"outline",onPress:z.refreshContext,children:"Refresh"})]})]}),_(y,{className:"p-4",children:[N("h3",{className:"font-semibold text-lg",children:"2) Ask the assistant (must cite KB snapshot)"}),_("div",{className:"mt-3 flex flex-col gap-3",children:[N(q,{value:Z,onChange:(W)=>F(W.target.value)}),N("div",{className:"flex gap-2",children:N(U,{onPress:Y,children:"Ask"})})]}),O.lastAnswer?_("div",{className:"mt-4 space-y-3",children:[O.lastAnswer.refused?_("div",{className:"text-red-600 text-sm",children:["Refused: ",O.lastAnswer.refusalReason??"UNKNOWN"]}):null,O.lastAnswer.sections.map((W,T)=>_("div",{children:[N("div",{className:"font-semibold text-sm",children:W.heading}),N("div",{className:"text-muted-foreground text-sm",children:W.body})]},`${W.heading}-${T}`)),N("div",{className:"font-semibold text-sm",children:"Citations"}),N("ul",{className:"list-disc pl-5 text-muted-foreground text-sm",children:O.lastAnswer.citations.map((W)=>_("li",{children:[W.kbSnapshotId," — ",W.sourceId]},`${W.kbSnapshotId}-${W.sourceId}`))})]}):null]}),_(y,{className:"p-4",children:[N("h3",{className:"font-semibold text-lg",children:"3) Admin: publish a new snapshot (HITL)"}),_("div",{className:"mt-3 space-y-3",children:[N(l,{value:$,onChange:(W)=>H(W.target.value)}),N(U,{onPress:E,children:"Simulate change → review → approve → publish snapshot"})]})]}),_(y,{className:"p-4",children:[N("h3",{className:"font-semibold text-lg",children:"4) Learning hub (patterns)"}),N("p",{className:"mt-2 text-muted-foreground text-sm",children:"This template includes drills, ambient coach, and quests as reusable Learning Journey tracks. The interactive learning UI is demonstrated in dedicated Learning Journey examples."})]})]})}export{Nz as PolicySafeKnowledgeAssistantDashboard};
@@ -1,74 +1,2 @@
1
1
  // @bun
2
- // src/orchestrator/buildAnswer.ts
3
- import {
4
- enforceAllowedScope,
5
- enforceCitations,
6
- validateEnvelope
7
- } from "@contractspec/example.locale-jurisdiction-gate/policy/guard";
8
- async function buildPolicySafeAnswer(input) {
9
- const env = validateEnvelope(input.envelope);
10
- if (!env.ok) {
11
- return {
12
- locale: input.envelope.locale ?? "en-GB",
13
- jurisdiction: input.envelope.regulatoryContext?.jurisdiction ?? "UNKNOWN",
14
- allowedScope: input.envelope.allowedScope ?? "education_only",
15
- sections: [{ heading: "Request blocked", body: env.error.message }],
16
- citations: [],
17
- disclaimers: ["This system refuses to answer without a valid envelope."],
18
- riskFlags: [env.error.code],
19
- refused: true,
20
- refusalReason: env.error.code
21
- };
22
- }
23
- const results = await input.kbSearch({
24
- snapshotId: env.value.kbSnapshotId,
25
- jurisdiction: env.value.regulatoryContext?.jurisdiction ?? "UNKNOWN",
26
- query: input.question
27
- });
28
- const citations = results.items.map((item) => ({
29
- kbSnapshotId: env.value.kbSnapshotId,
30
- sourceType: "ruleVersion",
31
- sourceId: item.ruleVersionId,
32
- title: "Curated rule version",
33
- excerpt: item.excerpt
34
- }));
35
- const draft = {
36
- locale: env.value.locale,
37
- jurisdiction: env.value.regulatoryContext?.jurisdiction ?? "UNKNOWN",
38
- allowedScope: env.value.allowedScope,
39
- sections: [
40
- {
41
- heading: "Answer (KB-derived)",
42
- body: results.items.length > 0 ? `This answer is derived from ${results.items.length} curated rule version(s) in the referenced snapshot.` : "No curated knowledge found in the referenced snapshot."
43
- }
44
- ],
45
- citations,
46
- disclaimers: ["Educational demo only."],
47
- riskFlags: []
48
- };
49
- const scope = enforceAllowedScope(env.value.allowedScope, draft);
50
- if (!scope.ok) {
51
- return {
52
- ...draft,
53
- sections: [{ heading: "Escalation required", body: scope.error.message }],
54
- refused: true,
55
- refusalReason: scope.error.code,
56
- riskFlags: [...draft.riskFlags ?? [], scope.error.code]
57
- };
58
- }
59
- const cited = enforceCitations(draft);
60
- if (!cited.ok) {
61
- return {
62
- ...draft,
63
- sections: [{ heading: "Request blocked", body: cited.error.message }],
64
- citations: [],
65
- refused: true,
66
- refusalReason: cited.error.code,
67
- riskFlags: [...draft.riskFlags ?? [], cited.error.code]
68
- };
69
- }
70
- return draft;
71
- }
72
- export {
73
- buildPolicySafeAnswer
74
- };
2
+ import{enforceAllowedScope as G,enforceCitations as H,validateEnvelope as I}from"@contractspec/example.locale-jurisdiction-gate/policy/guard";async function K(k){let b=I(k.envelope);if(!b.ok)return{locale:k.envelope.locale??"en-GB",jurisdiction:k.envelope.regulatoryContext?.jurisdiction??"UNKNOWN",allowedScope:k.envelope.allowedScope??"education_only",sections:[{heading:"Request blocked",body:b.error.message}],citations:[],disclaimers:["This system refuses to answer without a valid envelope."],riskFlags:[b.error.code],refused:!0,refusalReason:b.error.code};let B=await k.kbSearch({snapshotId:b.value.kbSnapshotId,jurisdiction:b.value.regulatoryContext?.jurisdiction??"UNKNOWN",query:k.question}),F=B.items.map((D)=>({kbSnapshotId:b.value.kbSnapshotId,sourceType:"ruleVersion",sourceId:D.ruleVersionId,title:"Curated rule version",excerpt:D.excerpt})),h={locale:b.value.locale,jurisdiction:b.value.regulatoryContext?.jurisdiction??"UNKNOWN",allowedScope:b.value.allowedScope,sections:[{heading:"Answer (KB-derived)",body:B.items.length>0?`This answer is derived from ${B.items.length} curated rule version(s) in the referenced snapshot.`:"No curated knowledge found in the referenced snapshot."}],citations:F,disclaimers:["Educational demo only."],riskFlags:[]},q=G(b.value.allowedScope,h);if(!q.ok)return{...h,sections:[{heading:"Escalation required",body:q.error.message}],refused:!0,refusalReason:q.error.code,riskFlags:[...h.riskFlags??[],q.error.code]};let z=H(h);if(!z.ok)return{...h,sections:[{heading:"Request blocked",body:z.error.message}],citations:[],refused:!0,refusalReason:z.error.code,riskFlags:[...h.riskFlags??[],z.error.code]};return h}export{K as buildPolicySafeAnswer};