@contractspec/example.policy-safe-knowledge-assistant 1.46.0 → 1.47.0

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 (50) hide show
  1. package/.turbo/turbo-build$colon$bundle.log +50 -30
  2. package/.turbo/turbo-build.log +49 -29
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +7 -8
  5. package/dist/example.d.ts +2 -2
  6. package/dist/example.d.ts.map +1 -1
  7. package/dist/example.js +5 -3
  8. package/dist/example.js.map +1 -1
  9. package/dist/handlers/index.d.ts +2 -0
  10. package/dist/handlers/index.js +3 -0
  11. package/dist/handlers/policy-safe-knowledge-assistant.handlers.d.ts +127 -0
  12. package/dist/handlers/policy-safe-knowledge-assistant.handlers.d.ts.map +1 -0
  13. package/dist/handlers/policy-safe-knowledge-assistant.handlers.js +264 -0
  14. package/dist/handlers/policy-safe-knowledge-assistant.handlers.js.map +1 -0
  15. package/dist/index.d.ts +5 -2
  16. package/dist/index.js +5 -2
  17. package/dist/orchestrator/buildAnswer.js.map +1 -1
  18. package/dist/policy-safe-knowledge-assistant.feature.d.ts +7 -0
  19. package/dist/policy-safe-knowledge-assistant.feature.d.ts.map +1 -0
  20. package/dist/{feature.js → policy-safe-knowledge-assistant.feature.js} +6 -4
  21. package/dist/policy-safe-knowledge-assistant.feature.js.map +1 -0
  22. package/dist/seeders/index.d.ts +10 -0
  23. package/dist/seeders/index.d.ts.map +1 -0
  24. package/dist/seeders/index.js +16 -0
  25. package/dist/seeders/index.js.map +1 -0
  26. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.d.ts +7 -0
  27. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.d.ts.map +1 -0
  28. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js +231 -0
  29. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js.map +1 -0
  30. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.d.ts +55 -0
  31. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.d.ts.map +1 -0
  32. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js +193 -0
  33. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js.map +1 -0
  34. package/dist/ui/index.d.ts +2 -0
  35. package/dist/ui/index.js +3 -0
  36. package/package.json +27 -15
  37. package/src/example.ts +4 -4
  38. package/src/handlers/index.ts +1 -0
  39. package/src/handlers/policy-safe-knowledge-assistant.handlers.ts +476 -0
  40. package/src/index.ts +3 -1
  41. package/src/{feature.ts → policy-safe-knowledge-assistant.feature.ts} +3 -3
  42. package/src/seeders/index.ts +20 -0
  43. package/src/ui/PolicySafeKnowledgeAssistantDashboard.tsx +206 -0
  44. package/src/ui/hooks/usePolicySafeKnowledgeAssistant.ts +229 -0
  45. package/src/ui/index.ts +1 -0
  46. package/tsconfig.tsbuildinfo +1 -1
  47. package/IMPLEMENTATION_SKETCH.md +0 -40
  48. package/dist/feature.d.ts +0 -7
  49. package/dist/feature.d.ts.map +0 -1
  50. package/dist/feature.js.map +0 -1
@@ -0,0 +1,206 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useMemo, useState } from 'react';
4
+ import {
5
+ Button,
6
+ ErrorState,
7
+ LoaderBlock,
8
+ StatCard,
9
+ StatCardGroup,
10
+ } from '@contractspec/lib.design-system';
11
+ import { Card } from '@contractspec/lib.ui-kit-web/ui/card';
12
+ import { Input } from '@contractspec/lib.ui-kit-web/ui/input';
13
+ import { Textarea } from '@contractspec/lib.ui-kit-web/ui/textarea';
14
+ import {
15
+ Select,
16
+ SelectContent,
17
+ SelectItem,
18
+ SelectTrigger,
19
+ SelectValue,
20
+ } from '@contractspec/lib.ui-kit-web/ui/select';
21
+
22
+ import { usePolicySafeKnowledgeAssistant } from './hooks/usePolicySafeKnowledgeAssistant';
23
+
24
+ type AllowedScope = 'education_only' | 'generic_info' | 'escalation_required';
25
+
26
+ export function PolicySafeKnowledgeAssistantDashboard() {
27
+ const { state, actions } = usePolicySafeKnowledgeAssistant();
28
+ const [question, setQuestion] = useState('reporting obligations');
29
+ const [content, setContent] = useState(
30
+ 'EU: Reporting obligations v2 (updated)'
31
+ );
32
+ const [locale, setLocale] = useState('en-GB');
33
+ const [jurisdiction, setJurisdiction] = useState('EU');
34
+ const [allowedScope, setAllowedScope] =
35
+ useState<AllowedScope>('education_only');
36
+
37
+ const snapshotId =
38
+ state.context?.kbSnapshotId ?? state.lastSnapshotId ?? null;
39
+
40
+ const stats = useMemo(() => {
41
+ return [
42
+ { label: 'Locale', value: state.context?.locale ?? '—' },
43
+ { label: 'Jurisdiction', value: state.context?.jurisdiction ?? '—' },
44
+ { label: 'Scope', value: state.context?.allowedScope ?? '—' },
45
+ { label: 'KB Snapshot', value: snapshotId ?? '—' },
46
+ ];
47
+ }, [
48
+ snapshotId,
49
+ state.context?.allowedScope,
50
+ state.context?.jurisdiction,
51
+ state.context?.locale,
52
+ ]);
53
+
54
+ const handleSetContext = useCallback(async () => {
55
+ await actions.setContext({ locale, jurisdiction, allowedScope });
56
+ }, [actions, allowedScope, jurisdiction, locale]);
57
+
58
+ const handleAsk = useCallback(async () => {
59
+ await actions.askAssistant(question);
60
+ }, [actions, question]);
61
+
62
+ const handleAdminPublishFlow = useCallback(async () => {
63
+ const ruleId = state.lastRuleId ?? (await actions.createDemoRule());
64
+ const rvId = await actions.upsertRuleVersion({ ruleId, content });
65
+ await actions.approveRuleVersion(rvId);
66
+ await actions.simulateHighRiskChangeAndApprove(rvId);
67
+ await actions.publishSnapshot();
68
+ }, [actions, content, state.lastRuleId]);
69
+
70
+ if (state.loading && !state.context) {
71
+ return <LoaderBlock label="Loading demo..." />;
72
+ }
73
+
74
+ if (state.error) {
75
+ return (
76
+ <ErrorState
77
+ title="Failed to load demo"
78
+ description={state.error.message}
79
+ onRetry={actions.refreshContext}
80
+ retryLabel="Retry"
81
+ />
82
+ );
83
+ }
84
+
85
+ return (
86
+ <div className="space-y-6">
87
+ <StatCardGroup>
88
+ {stats.map((s) => (
89
+ <StatCard key={s.label} label={s.label} value={String(s.value)} />
90
+ ))}
91
+ </StatCardGroup>
92
+
93
+ <Card className="p-4">
94
+ <h3 className="text-lg font-semibold">
95
+ 1) Onboarding (explicit locale + jurisdiction)
96
+ </h3>
97
+ <div className="mt-3 grid gap-3 md:grid-cols-3">
98
+ <div>
99
+ <div className="text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase">
100
+ Locale
101
+ </div>
102
+ <Input value={locale} onChange={(e) => setLocale(e.target.value)} />
103
+ </div>
104
+ <div>
105
+ <div className="text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase">
106
+ Jurisdiction
107
+ </div>
108
+ <Input
109
+ value={jurisdiction}
110
+ onChange={(e) => setJurisdiction(e.target.value)}
111
+ />
112
+ </div>
113
+ <div>
114
+ <div className="text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase">
115
+ Allowed scope
116
+ </div>
117
+ <Select
118
+ value={allowedScope}
119
+ onValueChange={(v) => setAllowedScope(v as AllowedScope)}
120
+ >
121
+ <SelectTrigger>
122
+ <SelectValue placeholder="Select scope" />
123
+ </SelectTrigger>
124
+ <SelectContent>
125
+ <SelectItem value="education_only">education_only</SelectItem>
126
+ <SelectItem value="generic_info">generic_info</SelectItem>
127
+ <SelectItem value="escalation_required">
128
+ escalation_required
129
+ </SelectItem>
130
+ </SelectContent>
131
+ </Select>
132
+ </div>
133
+ </div>
134
+ <div className="mt-4 flex gap-2">
135
+ <Button onPress={handleSetContext}>Save context</Button>
136
+ <Button variant="outline" onPress={actions.refreshContext}>
137
+ Refresh
138
+ </Button>
139
+ </div>
140
+ </Card>
141
+
142
+ <Card className="p-4">
143
+ <h3 className="text-lg font-semibold">
144
+ 2) Ask the assistant (must cite KB snapshot)
145
+ </h3>
146
+ <div className="mt-3 flex flex-col gap-3">
147
+ <Input
148
+ value={question}
149
+ onChange={(e) => setQuestion(e.target.value)}
150
+ />
151
+ <div className="flex gap-2">
152
+ <Button onPress={handleAsk}>Ask</Button>
153
+ </div>
154
+ </div>
155
+
156
+ {state.lastAnswer ? (
157
+ <div className="mt-4 space-y-3">
158
+ {state.lastAnswer.refused ? (
159
+ <div className="text-sm text-red-600">
160
+ Refused: {state.lastAnswer.refusalReason ?? 'UNKNOWN'}
161
+ </div>
162
+ ) : null}
163
+ {state.lastAnswer.sections.map((s, idx) => (
164
+ <div key={`${s.heading}-${idx}`}>
165
+ <div className="text-sm font-semibold">{s.heading}</div>
166
+ <div className="text-muted-foreground text-sm">{s.body}</div>
167
+ </div>
168
+ ))}
169
+ <div className="text-sm font-semibold">Citations</div>
170
+ <ul className="text-muted-foreground list-disc pl-5 text-sm">
171
+ {state.lastAnswer.citations.map((c) => (
172
+ <li key={`${c.kbSnapshotId}-${c.sourceId}`}>
173
+ {c.kbSnapshotId} — {c.sourceId}
174
+ </li>
175
+ ))}
176
+ </ul>
177
+ </div>
178
+ ) : null}
179
+ </Card>
180
+
181
+ <Card className="p-4">
182
+ <h3 className="text-lg font-semibold">
183
+ 3) Admin: publish a new snapshot (HITL)
184
+ </h3>
185
+ <div className="mt-3 space-y-3">
186
+ <Textarea
187
+ value={content}
188
+ onChange={(e) => setContent(e.target.value)}
189
+ />
190
+ <Button onPress={handleAdminPublishFlow}>
191
+ Simulate change → review → approve → publish snapshot
192
+ </Button>
193
+ </div>
194
+ </Card>
195
+
196
+ <Card className="p-4">
197
+ <h3 className="text-lg font-semibold">4) Learning hub (patterns)</h3>
198
+ <p className="text-muted-foreground mt-2 text-sm">
199
+ This template includes drills, ambient coach, and quests as reusable
200
+ Learning Journey tracks. The interactive learning UI is demonstrated
201
+ in dedicated Learning Journey examples.
202
+ </p>
203
+ </Card>
204
+ </div>
205
+ );
206
+ }
@@ -0,0 +1,229 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect, useMemo, useState } from 'react';
4
+ import { useTemplateRuntime } from '@contractspec/lib.example-shared-ui';
5
+
6
+ type AllowedScope = 'education_only' | 'generic_info' | 'escalation_required';
7
+ type RiskLevel = 'low' | 'medium' | 'high';
8
+
9
+ export interface UsePolicySafeKnowledgeAssistantState {
10
+ context: {
11
+ locale: string;
12
+ jurisdiction: string;
13
+ allowedScope: AllowedScope;
14
+ kbSnapshotId: string | null;
15
+ } | null;
16
+ loading: boolean;
17
+ error: Error | null;
18
+ lastAnswer: {
19
+ refused?: boolean;
20
+ refusalReason?: string;
21
+ sections: { heading: string; body: string }[];
22
+ citations: {
23
+ kbSnapshotId: string;
24
+ sourceId: string;
25
+ excerpt?: string;
26
+ }[];
27
+ } | null;
28
+ lastRuleId: string | null;
29
+ lastRuleVersionId: string | null;
30
+ lastSnapshotId: string | null;
31
+ lastReviewTaskId: string | null;
32
+ }
33
+
34
+ interface CitationLike {
35
+ kbSnapshotId: string;
36
+ sourceId: string;
37
+ excerpt?: string;
38
+ }
39
+ interface AnswerLike {
40
+ refused?: boolean;
41
+ refusalReason?: string;
42
+ sections: { heading: string; body: string }[];
43
+ citations: CitationLike[];
44
+ }
45
+
46
+ function isCitationLike(value: unknown): value is CitationLike {
47
+ if (!value || typeof value !== 'object') return false;
48
+ const v = value as Record<string, unknown>;
49
+ return typeof v.kbSnapshotId === 'string' && typeof v.sourceId === 'string';
50
+ }
51
+
52
+ function toCitations(value: unknown): CitationLike[] {
53
+ if (!Array.isArray(value)) return [];
54
+ return value.filter(isCitationLike).map((c) => ({
55
+ kbSnapshotId: c.kbSnapshotId,
56
+ sourceId: c.sourceId,
57
+ excerpt: c.excerpt,
58
+ }));
59
+ }
60
+
61
+ import type { PolicySafeKnowledgeAssistantHandlers } from '../../handlers/policy-safe-knowledge-assistant.handlers';
62
+
63
+ export function usePolicySafeKnowledgeAssistant() {
64
+ const { handlers, projectId } = useTemplateRuntime<{
65
+ policySafeKnowledgeAssistant: PolicySafeKnowledgeAssistantHandlers;
66
+ }>();
67
+ const api = handlers.policySafeKnowledgeAssistant;
68
+
69
+ const [state, setState] = useState<UsePolicySafeKnowledgeAssistantState>({
70
+ context: null,
71
+ loading: true,
72
+ error: null,
73
+ lastAnswer: null,
74
+ lastRuleId: null,
75
+ lastRuleVersionId: null,
76
+ lastSnapshotId: null,
77
+ lastReviewTaskId: null,
78
+ });
79
+
80
+ const refreshContext = useCallback(async () => {
81
+ try {
82
+ setState((s) => ({ ...s, loading: true, error: null }));
83
+ const ctx = await api.getUserContext({ projectId });
84
+ setState((s) => ({
85
+ ...s,
86
+ context: {
87
+ locale: ctx.locale,
88
+ jurisdiction: ctx.jurisdiction,
89
+ allowedScope: ctx.allowedScope,
90
+ kbSnapshotId: ctx.kbSnapshotId,
91
+ },
92
+ loading: false,
93
+ }));
94
+ } catch (e) {
95
+ setState((s) => ({
96
+ ...s,
97
+ loading: false,
98
+ error: e instanceof Error ? e : new Error('Unknown error'),
99
+ }));
100
+ }
101
+ }, [api, projectId]);
102
+
103
+ useEffect(() => {
104
+ refreshContext();
105
+ }, [refreshContext]);
106
+
107
+ const setContext = useCallback(
108
+ async (input: {
109
+ locale: string;
110
+ jurisdiction: string;
111
+ allowedScope: AllowedScope;
112
+ }) => {
113
+ const ctx = await api.setUserContext({ projectId, ...input });
114
+ setState((s) => ({
115
+ ...s,
116
+ context: {
117
+ locale: ctx.locale,
118
+ jurisdiction: ctx.jurisdiction,
119
+ allowedScope: ctx.allowedScope,
120
+ kbSnapshotId: ctx.kbSnapshotId,
121
+ },
122
+ }));
123
+ },
124
+ [api, projectId]
125
+ );
126
+
127
+ const askAssistant = useCallback(
128
+ async (question: string) => {
129
+ const answerUnknown: unknown = await api.answer({ projectId, question });
130
+ const answer = answerUnknown as AnswerLike;
131
+ setState((s) => ({
132
+ ...s,
133
+ lastAnswer: {
134
+ refused: answer.refused,
135
+ refusalReason: answer.refusalReason,
136
+ sections: answer.sections,
137
+ citations: toCitations(
138
+ (answerUnknown as { citations?: unknown }).citations
139
+ ),
140
+ },
141
+ }));
142
+ },
143
+ [api, projectId]
144
+ );
145
+
146
+ const createDemoRule = useCallback(async () => {
147
+ const rule = await api.createRule({
148
+ projectId,
149
+ jurisdiction: state.context?.jurisdiction ?? 'EU',
150
+ topicKey: 'tax_reporting',
151
+ });
152
+ setState((s) => ({ ...s, lastRuleId: rule.id }));
153
+ return rule.id as string;
154
+ }, [api, projectId, state.context?.jurisdiction]);
155
+
156
+ const upsertRuleVersion = useCallback(
157
+ async (input: { ruleId: string; content: string }) => {
158
+ const rv = await api.upsertRuleVersion({
159
+ projectId,
160
+ ruleId: input.ruleId,
161
+ content: input.content,
162
+ sourceRefs: [{ sourceDocumentId: 'src_demo', excerpt: 'demo excerpt' }],
163
+ });
164
+ setState((s) => ({ ...s, lastRuleVersionId: rv.id }));
165
+ return rv.id as string;
166
+ },
167
+ [api, projectId]
168
+ );
169
+
170
+ const approveRuleVersion = useCallback(
171
+ async (ruleVersionId: string) => {
172
+ await api.approveRuleVersion({ ruleVersionId, approver: 'demo_expert' });
173
+ },
174
+ [api]
175
+ );
176
+
177
+ const publishSnapshot = useCallback(async () => {
178
+ const snap = await api.publishSnapshot({
179
+ projectId,
180
+ jurisdiction: state.context?.jurisdiction ?? 'EU',
181
+ asOfDate: new Date('2026-02-01T00:00:00.000Z'),
182
+ });
183
+ setState((s) => ({ ...s, lastSnapshotId: snap.id }));
184
+ await refreshContext();
185
+ return snap.id as string;
186
+ }, [api, projectId, refreshContext, state.context?.jurisdiction]);
187
+
188
+ const simulateHighRiskChangeAndApprove = useCallback(
189
+ async (ruleVersionId: string) => {
190
+ const cand = await api.createChangeCandidate({
191
+ projectId,
192
+ jurisdiction: state.context?.jurisdiction ?? 'EU',
193
+ diffSummary: 'Simulated change (demo)',
194
+ riskLevel: 'high' satisfies RiskLevel,
195
+ proposedRuleVersionIds: [ruleVersionId],
196
+ });
197
+ const review = await api.createReviewTask({ changeCandidateId: cand.id });
198
+ setState((s) => ({ ...s, lastReviewTaskId: review.id }));
199
+ await api.submitDecision({
200
+ reviewTaskId: review.id,
201
+ decision: 'approve',
202
+ decidedByRole: 'expert',
203
+ decidedBy: 'demo_expert',
204
+ });
205
+ await api.publishIfReady({
206
+ jurisdiction: state.context?.jurisdiction ?? 'EU',
207
+ });
208
+ return review.id as string;
209
+ },
210
+ [api, projectId, state.context?.jurisdiction]
211
+ );
212
+
213
+ const derived = useMemo(() => ({ projectId }), [projectId]);
214
+
215
+ return {
216
+ state,
217
+ derived,
218
+ actions: {
219
+ refreshContext,
220
+ setContext,
221
+ askAssistant,
222
+ createDemoRule,
223
+ upsertRuleVersion,
224
+ approveRuleVersion,
225
+ publishSnapshot,
226
+ simulateHighRiskChangeAndApprove,
227
+ },
228
+ };
229
+ }
@@ -0,0 +1 @@
1
+ export * from './PolicySafeKnowledgeAssistantDashboard';