@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.
- package/.turbo/turbo-build.log +45 -45
- package/CHANGELOG.md +20 -0
- package/dist/browser/docs/index.js +3 -27
- package/dist/browser/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
- package/dist/browser/example.js +1 -37
- package/dist/browser/handlers/index.js +5 -334
- package/dist/browser/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
- package/dist/browser/index.js +7 -913
- package/dist/browser/orchestrator/buildAnswer.js +1 -73
- package/dist/browser/policy-safe-knowledge-assistant.feature.js +1 -64
- package/dist/browser/seed/fixtures.js +1 -35
- package/dist/browser/seed/index.js +1 -35
- package/dist/browser/seeders/index.js +2 -12
- package/dist/browser/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
- package/dist/browser/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
- package/dist/browser/ui/index.js +1 -420
- package/dist/docs/index.js +3 -27
- package/dist/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
- package/dist/example.js +1 -37
- package/dist/handlers/index.js +5 -334
- package/dist/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
- package/dist/index.js +7 -913
- package/dist/node/docs/index.js +3 -27
- package/dist/node/docs/policy-safe-knowledge-assistant.docblock.js +3 -27
- package/dist/node/example.js +1 -37
- package/dist/node/handlers/index.js +5 -334
- package/dist/node/handlers/policy-safe-knowledge-assistant.handlers.js +5 -334
- package/dist/node/index.js +7 -913
- package/dist/node/orchestrator/buildAnswer.js +1 -73
- package/dist/node/policy-safe-knowledge-assistant.feature.js +1 -64
- package/dist/node/seed/fixtures.js +1 -35
- package/dist/node/seed/index.js +1 -35
- package/dist/node/seeders/index.js +2 -12
- package/dist/node/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
- package/dist/node/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
- package/dist/node/ui/index.js +1 -420
- package/dist/orchestrator/buildAnswer.js +1 -73
- package/dist/policy-safe-knowledge-assistant.feature.js +1 -64
- package/dist/seed/fixtures.js +1 -35
- package/dist/seed/index.js +1 -35
- package/dist/seeders/index.js +2 -12
- package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js +1 -420
- package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js +1 -154
- package/dist/ui/index.js +1 -420
- package/package.json +13 -13
package/dist/node/index.js
CHANGED
|
@@ -1,15 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { registerDocBlocks } from "@contractspec/lib.contracts-spec/docs";
|
|
3
|
-
var docBlocks = [
|
|
4
|
-
{
|
|
5
|
-
id: "docs.examples.policy-safe-knowledge-assistant.goal",
|
|
6
|
-
title: "Policy-safe Knowledge Assistant — Goal",
|
|
7
|
-
summary: "End-to-end example: versioned KB snapshots + locale/jurisdiction gating + HITL pipeline + learning hub.",
|
|
8
|
-
kind: "goal",
|
|
9
|
-
visibility: "public",
|
|
10
|
-
route: "/docs/examples/policy-safe-knowledge-assistant/goal",
|
|
11
|
-
tags: ["assistant", "knowledge", "policy", "hitl", "learning"],
|
|
12
|
-
body: `## What this template proves
|
|
1
|
+
import{registerDocBlocks as b}from"@contractspec/lib.contracts-spec/docs";var x=[{id:"docs.examples.policy-safe-knowledge-assistant.goal",title:"Policy-safe Knowledge Assistant — Goal",summary:"End-to-end example: versioned KB snapshots + locale/jurisdiction gating + HITL pipeline + learning hub.",kind:"goal",visibility:"public",route:"/docs/examples/policy-safe-knowledge-assistant/goal",tags:["assistant","knowledge","policy","hitl","learning"],body:`## What this template proves
|
|
13
2
|
- Assistant answers are structured and must cite a KB snapshot (or refuse).
|
|
14
3
|
- Locale + jurisdiction are mandatory inputs for every assistant call.
|
|
15
4
|
- Automation proposes KB patches; humans verify; publishing stays blocked until approvals.
|
|
@@ -17,908 +6,13 @@ var docBlocks = [
|
|
|
17
6
|
|
|
18
7
|
## Offline-first
|
|
19
8
|
- Seeded fixtures are deterministic and require no external services.
|
|
20
|
-
- Optional non-authoritative fallback can be added behind a single feature flag (disabled by default).`
|
|
21
|
-
},
|
|
22
|
-
{
|
|
23
|
-
id: "docs.examples.policy-safe-knowledge-assistant.usage",
|
|
24
|
-
title: "Policy-safe Knowledge Assistant — Usage",
|
|
25
|
-
summary: "5–10 minute sandbox walkthrough for developers.",
|
|
26
|
-
kind: "usage",
|
|
27
|
-
visibility: "public",
|
|
28
|
-
route: "/docs/examples/policy-safe-knowledge-assistant/usage",
|
|
29
|
-
tags: ["assistant", "knowledge", "usage"],
|
|
30
|
-
body: `## Demo walkthrough (high level)
|
|
9
|
+
- Optional non-authoritative fallback can be added behind a single feature flag (disabled by default).`},{id:"docs.examples.policy-safe-knowledge-assistant.usage",title:"Policy-safe Knowledge Assistant — Usage",summary:"5–10 minute sandbox walkthrough for developers.",kind:"usage",visibility:"public",route:"/docs/examples/policy-safe-knowledge-assistant/usage",tags:["assistant","knowledge","usage"],body:`## Demo walkthrough (high level)
|
|
31
10
|
1) Onboard: set locale + jurisdiction.
|
|
32
11
|
2) Publish snapshot: ingest source -> propose rule -> approve -> publish.
|
|
33
12
|
3) Ask assistant: must pass gate and cite snapshot.
|
|
34
13
|
4) Simulate change: watcher -> review -> publish new snapshot.
|
|
35
|
-
5) Learning hub: drills session, ambient tip, quest start + step completion.`
|
|
36
|
-
|
|
37
|
-
];
|
|
38
|
-
|
|
39
|
-
// src/example.ts
|
|
40
|
-
import { defineExample } from "@contractspec/lib.contracts-spec";
|
|
41
|
-
var example = defineExample({
|
|
42
|
-
meta: {
|
|
43
|
-
key: "policy-safe-knowledge-assistant",
|
|
44
|
-
version: "1.0.0",
|
|
45
|
-
title: "Policy-safe Knowledge Assistant",
|
|
46
|
-
description: "All-in-one template: locale/jurisdiction gating + versioned KB snapshots + HITL update pipeline + learning hub.",
|
|
47
|
-
kind: "template",
|
|
48
|
-
visibility: "public",
|
|
49
|
-
stability: "experimental",
|
|
50
|
-
owners: ["@platform.core"],
|
|
51
|
-
tags: ["assistant", "knowledge", "policy", "hitl", "learning"]
|
|
52
|
-
},
|
|
53
|
-
docs: {
|
|
54
|
-
goalDocId: "docs.examples.policy-safe-knowledge-assistant.goal",
|
|
55
|
-
usageDocId: "docs.examples.policy-safe-knowledge-assistant.usage"
|
|
56
|
-
},
|
|
57
|
-
entrypoints: {
|
|
58
|
-
packageName: "@contractspec/example.policy-safe-knowledge-assistant",
|
|
59
|
-
feature: "./policy-safe-knowledge-assistant.feature",
|
|
60
|
-
docs: "./docs"
|
|
61
|
-
},
|
|
62
|
-
surfaces: {
|
|
63
|
-
templates: true,
|
|
64
|
-
sandbox: {
|
|
65
|
-
enabled: true,
|
|
66
|
-
modes: ["playground", "specs", "builder", "markdown", "evolution"]
|
|
67
|
-
},
|
|
68
|
-
studio: { enabled: true, installable: true },
|
|
69
|
-
mcp: { enabled: true }
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
var example_default = example;
|
|
73
|
-
|
|
74
|
-
// src/orchestrator/buildAnswer.ts
|
|
75
|
-
import {
|
|
76
|
-
enforceAllowedScope,
|
|
77
|
-
enforceCitations,
|
|
78
|
-
validateEnvelope
|
|
79
|
-
} from "@contractspec/example.locale-jurisdiction-gate/policy/guard";
|
|
80
|
-
async function buildPolicySafeAnswer(input) {
|
|
81
|
-
const env = validateEnvelope(input.envelope);
|
|
82
|
-
if (!env.ok) {
|
|
83
|
-
return {
|
|
84
|
-
locale: input.envelope.locale ?? "en-GB",
|
|
85
|
-
jurisdiction: input.envelope.regulatoryContext?.jurisdiction ?? "UNKNOWN",
|
|
86
|
-
allowedScope: input.envelope.allowedScope ?? "education_only",
|
|
87
|
-
sections: [{ heading: "Request blocked", body: env.error.message }],
|
|
88
|
-
citations: [],
|
|
89
|
-
disclaimers: ["This system refuses to answer without a valid envelope."],
|
|
90
|
-
riskFlags: [env.error.code],
|
|
91
|
-
refused: true,
|
|
92
|
-
refusalReason: env.error.code
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
const results = await input.kbSearch({
|
|
96
|
-
snapshotId: env.value.kbSnapshotId,
|
|
97
|
-
jurisdiction: env.value.regulatoryContext?.jurisdiction ?? "UNKNOWN",
|
|
98
|
-
query: input.question
|
|
99
|
-
});
|
|
100
|
-
const citations = results.items.map((item) => ({
|
|
101
|
-
kbSnapshotId: env.value.kbSnapshotId,
|
|
102
|
-
sourceType: "ruleVersion",
|
|
103
|
-
sourceId: item.ruleVersionId,
|
|
104
|
-
title: "Curated rule version",
|
|
105
|
-
excerpt: item.excerpt
|
|
106
|
-
}));
|
|
107
|
-
const draft = {
|
|
108
|
-
locale: env.value.locale,
|
|
109
|
-
jurisdiction: env.value.regulatoryContext?.jurisdiction ?? "UNKNOWN",
|
|
110
|
-
allowedScope: env.value.allowedScope,
|
|
111
|
-
sections: [
|
|
112
|
-
{
|
|
113
|
-
heading: "Answer (KB-derived)",
|
|
114
|
-
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."
|
|
115
|
-
}
|
|
116
|
-
],
|
|
117
|
-
citations,
|
|
118
|
-
disclaimers: ["Educational demo only."],
|
|
119
|
-
riskFlags: []
|
|
120
|
-
};
|
|
121
|
-
const scope = enforceAllowedScope(env.value.allowedScope, draft);
|
|
122
|
-
if (!scope.ok) {
|
|
123
|
-
return {
|
|
124
|
-
...draft,
|
|
125
|
-
sections: [{ heading: "Escalation required", body: scope.error.message }],
|
|
126
|
-
refused: true,
|
|
127
|
-
refusalReason: scope.error.code,
|
|
128
|
-
riskFlags: [...draft.riskFlags ?? [], scope.error.code]
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
const cited = enforceCitations(draft);
|
|
132
|
-
if (!cited.ok) {
|
|
133
|
-
return {
|
|
134
|
-
...draft,
|
|
135
|
-
sections: [{ heading: "Request blocked", body: cited.error.message }],
|
|
136
|
-
citations: [],
|
|
137
|
-
refused: true,
|
|
138
|
-
refusalReason: cited.error.code,
|
|
139
|
-
riskFlags: [...draft.riskFlags ?? [], cited.error.code]
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
return draft;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// src/handlers/policy-safe-knowledge-assistant.handlers.ts
|
|
146
|
-
import { web } from "@contractspec/lib.runtime-sandbox";
|
|
147
|
-
var { generateId } = web;
|
|
148
|
-
function parseJsonArray(value) {
|
|
149
|
-
if (!value)
|
|
150
|
-
return [];
|
|
151
|
-
try {
|
|
152
|
-
const parsed = JSON.parse(value);
|
|
153
|
-
return Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string") : [];
|
|
154
|
-
} catch {
|
|
155
|
-
return [];
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
function nowIso() {
|
|
159
|
-
return new Date().toISOString();
|
|
160
|
-
}
|
|
161
|
-
function createPolicySafeKnowledgeAssistantHandlers(db) {
|
|
162
|
-
async function getUserContext(input) {
|
|
163
|
-
const result = await db.query(`SELECT * FROM psa_user_context WHERE "projectId" = $1 LIMIT 1`, [input.projectId]);
|
|
164
|
-
const row = result.rows[0];
|
|
165
|
-
if (!row) {
|
|
166
|
-
return {
|
|
167
|
-
projectId: input.projectId,
|
|
168
|
-
locale: "en-GB",
|
|
169
|
-
jurisdiction: "EU",
|
|
170
|
-
allowedScope: "education_only",
|
|
171
|
-
kbSnapshotId: null
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
return {
|
|
175
|
-
projectId: row.projectId,
|
|
176
|
-
locale: row.locale,
|
|
177
|
-
jurisdiction: row.jurisdiction,
|
|
178
|
-
allowedScope: row.allowedScope,
|
|
179
|
-
kbSnapshotId: row.kbSnapshotId
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
async function setUserContext(input) {
|
|
183
|
-
const existing = await db.query(`SELECT "projectId" FROM psa_user_context WHERE "projectId" = $1 LIMIT 1`, [input.projectId]);
|
|
184
|
-
if (existing.rows.length) {
|
|
185
|
-
await db.execute(`UPDATE psa_user_context SET locale = $1, jurisdiction = $2, "allowedScope" = $3 WHERE "projectId" = $4`, [input.locale, input.jurisdiction, input.allowedScope, input.projectId]);
|
|
186
|
-
} else {
|
|
187
|
-
await db.execute(`INSERT INTO psa_user_context ("projectId", locale, jurisdiction, "allowedScope", "kbSnapshotId") VALUES ($1, $2, $3, $4, $5)`, [
|
|
188
|
-
input.projectId,
|
|
189
|
-
input.locale,
|
|
190
|
-
input.jurisdiction,
|
|
191
|
-
input.allowedScope,
|
|
192
|
-
null
|
|
193
|
-
]);
|
|
194
|
-
}
|
|
195
|
-
return await getUserContext({ projectId: input.projectId });
|
|
196
|
-
}
|
|
197
|
-
async function createRule(input) {
|
|
198
|
-
const id = generateId("psa_rule");
|
|
199
|
-
await db.execute(`INSERT INTO psa_rule (id, "projectId", jurisdiction, "topicKey") VALUES ($1, $2, $3, $4)`, [id, input.projectId, input.jurisdiction, input.topicKey]);
|
|
200
|
-
return { id, ...input };
|
|
201
|
-
}
|
|
202
|
-
async function upsertRuleVersion(input) {
|
|
203
|
-
if (!input.sourceRefs.length)
|
|
204
|
-
throw new Error("SOURCE_REFS_REQUIRED");
|
|
205
|
-
const rulesResult = await db.query(`SELECT * FROM psa_rule WHERE id = $1 LIMIT 1`, [input.ruleId]);
|
|
206
|
-
const rule = rulesResult.rows[0];
|
|
207
|
-
if (!rule)
|
|
208
|
-
throw new Error("RULE_NOT_FOUND");
|
|
209
|
-
const maxResult = await db.query(`SELECT MAX(version) as maxVersion FROM psa_rule_version WHERE "ruleId" = $1`, [input.ruleId]);
|
|
210
|
-
const maxVersion = Number(maxResult.rows[0]?.maxVersion ?? 0);
|
|
211
|
-
const version = maxVersion + 1;
|
|
212
|
-
const id = generateId("psa_rv");
|
|
213
|
-
const createdAt = nowIso();
|
|
214
|
-
await db.execute(`INSERT INTO psa_rule_version (id, "ruleId", jurisdiction, "topicKey", version, content, status, "sourceRefsJson", "approvedBy", "approvedAt", "createdAt")
|
|
215
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
|
|
216
|
-
id,
|
|
217
|
-
input.ruleId,
|
|
218
|
-
rule.jurisdiction,
|
|
219
|
-
rule.topicKey,
|
|
220
|
-
version,
|
|
221
|
-
input.content,
|
|
222
|
-
"draft",
|
|
223
|
-
JSON.stringify(input.sourceRefs),
|
|
224
|
-
null,
|
|
225
|
-
null,
|
|
226
|
-
createdAt
|
|
227
|
-
]);
|
|
228
|
-
return {
|
|
229
|
-
id,
|
|
230
|
-
ruleId: input.ruleId,
|
|
231
|
-
jurisdiction: rule.jurisdiction,
|
|
232
|
-
topicKey: rule.topicKey,
|
|
233
|
-
version,
|
|
234
|
-
content: input.content,
|
|
235
|
-
status: "draft",
|
|
236
|
-
sourceRefs: input.sourceRefs,
|
|
237
|
-
createdAt: new Date(createdAt)
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
async function approveRuleVersion(input) {
|
|
241
|
-
const approvedAt = nowIso();
|
|
242
|
-
await db.execute(`UPDATE psa_rule_version SET status = $1, "approvedBy" = $2, "approvedAt" = $3 WHERE id = $4`, ["approved", input.approver, approvedAt, input.ruleVersionId]);
|
|
243
|
-
return { ruleVersionId: input.ruleVersionId, status: "approved" };
|
|
244
|
-
}
|
|
245
|
-
async function publishSnapshot(input) {
|
|
246
|
-
const approvedResult = await db.query(`SELECT id FROM psa_rule_version WHERE jurisdiction = $1 AND status = 'approved' ORDER BY id ASC`, [input.jurisdiction]);
|
|
247
|
-
const includedIds = approvedResult.rows.map((r) => r.id).filter(Boolean);
|
|
248
|
-
if (!includedIds.length)
|
|
249
|
-
throw new Error("NO_APPROVED_RULES");
|
|
250
|
-
const id = generateId("psa_snap");
|
|
251
|
-
const publishedAt = nowIso();
|
|
252
|
-
await db.execute(`INSERT INTO psa_snapshot (id, jurisdiction, "asOfDate", "includedRuleVersionIdsJson", "publishedAt")
|
|
253
|
-
VALUES ($1, $2, $3, $4, $5)`, [
|
|
254
|
-
id,
|
|
255
|
-
input.jurisdiction,
|
|
256
|
-
input.asOfDate.toISOString(),
|
|
257
|
-
JSON.stringify(includedIds),
|
|
258
|
-
publishedAt
|
|
259
|
-
]);
|
|
260
|
-
await db.execute(`UPDATE psa_user_context SET "kbSnapshotId" = $1 WHERE "projectId" = $2`, [id, input.projectId]);
|
|
261
|
-
return {
|
|
262
|
-
id,
|
|
263
|
-
jurisdiction: input.jurisdiction,
|
|
264
|
-
includedRuleVersionIds: includedIds
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
async function searchKb(input) {
|
|
268
|
-
const snapResult = await db.query(`SELECT * FROM psa_snapshot WHERE id = $1 LIMIT 1`, [input.snapshotId]);
|
|
269
|
-
const snap = snapResult.rows[0];
|
|
270
|
-
if (!snap)
|
|
271
|
-
throw new Error("SNAPSHOT_NOT_FOUND");
|
|
272
|
-
if (snap.jurisdiction !== input.jurisdiction)
|
|
273
|
-
throw new Error("JURISDICTION_MISMATCH");
|
|
274
|
-
const includedIds = parseJsonArray(snap.includedRuleVersionIdsJson);
|
|
275
|
-
const tokens = input.query.toLowerCase().split(/\s+/).map((t) => t.trim()).filter(Boolean);
|
|
276
|
-
const items = [];
|
|
277
|
-
for (const id of includedIds) {
|
|
278
|
-
const rvResult = await db.query(`SELECT * FROM psa_rule_version WHERE id = $1 LIMIT 1`, [id]);
|
|
279
|
-
const rv = rvResult.rows[0];
|
|
280
|
-
if (!rv)
|
|
281
|
-
continue;
|
|
282
|
-
const hay = rv.content.toLowerCase();
|
|
283
|
-
const match = tokens.length ? tokens.every((t) => hay.includes(t)) : true;
|
|
284
|
-
if (!match)
|
|
285
|
-
continue;
|
|
286
|
-
items.push({ ruleVersionId: rv.id, excerpt: rv.content.slice(0, 140) });
|
|
287
|
-
}
|
|
288
|
-
return { items };
|
|
289
|
-
}
|
|
290
|
-
async function answer(input) {
|
|
291
|
-
const ctx = await getUserContext({ projectId: input.projectId });
|
|
292
|
-
if (!ctx.kbSnapshotId) {
|
|
293
|
-
const refused = await buildPolicySafeAnswer({
|
|
294
|
-
envelope: {
|
|
295
|
-
traceId: generateId("trace"),
|
|
296
|
-
locale: ctx.locale,
|
|
297
|
-
kbSnapshotId: "",
|
|
298
|
-
allowedScope: ctx.allowedScope,
|
|
299
|
-
regulatoryContext: { jurisdiction: ctx.jurisdiction }
|
|
300
|
-
},
|
|
301
|
-
question: input.question,
|
|
302
|
-
kbSearch: async () => ({ items: [] })
|
|
303
|
-
});
|
|
304
|
-
return refused;
|
|
305
|
-
}
|
|
306
|
-
return await buildPolicySafeAnswer({
|
|
307
|
-
envelope: {
|
|
308
|
-
traceId: generateId("trace"),
|
|
309
|
-
locale: ctx.locale,
|
|
310
|
-
kbSnapshotId: ctx.kbSnapshotId,
|
|
311
|
-
allowedScope: ctx.allowedScope,
|
|
312
|
-
regulatoryContext: { jurisdiction: ctx.jurisdiction }
|
|
313
|
-
},
|
|
314
|
-
question: input.question,
|
|
315
|
-
kbSearch: async (q) => await searchKb(q)
|
|
316
|
-
});
|
|
317
|
-
}
|
|
318
|
-
async function createChangeCandidate(input) {
|
|
319
|
-
const id = generateId("psa_change");
|
|
320
|
-
await db.execute(`INSERT INTO psa_change_candidate (id, "projectId", jurisdiction, "detectedAt", "diffSummary", "riskLevel", "proposedRuleVersionIdsJson")
|
|
321
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7)`, [
|
|
322
|
-
id,
|
|
323
|
-
input.projectId,
|
|
324
|
-
input.jurisdiction,
|
|
325
|
-
nowIso(),
|
|
326
|
-
input.diffSummary,
|
|
327
|
-
input.riskLevel,
|
|
328
|
-
JSON.stringify(input.proposedRuleVersionIds)
|
|
329
|
-
]);
|
|
330
|
-
return { id };
|
|
331
|
-
}
|
|
332
|
-
async function createReviewTask(input) {
|
|
333
|
-
const candResult = await db.query(`SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1`, [input.changeCandidateId]);
|
|
334
|
-
const candidate = candResult.rows[0];
|
|
335
|
-
if (!candidate)
|
|
336
|
-
throw new Error("CHANGE_CANDIDATE_NOT_FOUND");
|
|
337
|
-
const assignedRole = candidate.riskLevel === "high" ? "expert" : "curator";
|
|
338
|
-
const id = generateId("psa_review");
|
|
339
|
-
await db.execute(`INSERT INTO psa_review_task (id, "changeCandidateId", status, "assignedRole", decision, "decidedAt", "decidedBy")
|
|
340
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7)`, [id, input.changeCandidateId, "open", assignedRole, null, null, null]);
|
|
341
|
-
return { id, assignedRole };
|
|
342
|
-
}
|
|
343
|
-
async function submitDecision(input) {
|
|
344
|
-
const reviewResult = await db.query(`SELECT * FROM psa_review_task WHERE id = $1 LIMIT 1`, [input.reviewTaskId]);
|
|
345
|
-
const task = reviewResult.rows[0];
|
|
346
|
-
if (!task)
|
|
347
|
-
throw new Error("REVIEW_TASK_NOT_FOUND");
|
|
348
|
-
const candidateResult = await db.query(`SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1`, [task.changeCandidateId]);
|
|
349
|
-
const candidate = candidateResult.rows[0];
|
|
350
|
-
if (!candidate)
|
|
351
|
-
throw new Error("CHANGE_CANDIDATE_NOT_FOUND");
|
|
352
|
-
if (candidate.riskLevel === "high" && input.decision === "approve" && input.decidedByRole !== "expert") {
|
|
353
|
-
throw new Error("FORBIDDEN_ROLE");
|
|
354
|
-
}
|
|
355
|
-
const decidedAt = nowIso();
|
|
356
|
-
await db.execute(`UPDATE psa_review_task SET status = $1, decision = $2, "decidedAt" = $3, "decidedBy" = $4 WHERE id = $5`, [
|
|
357
|
-
"decided",
|
|
358
|
-
input.decision,
|
|
359
|
-
decidedAt,
|
|
360
|
-
input.decidedBy,
|
|
361
|
-
input.reviewTaskId
|
|
362
|
-
]);
|
|
363
|
-
return { id: input.reviewTaskId, status: "decided" };
|
|
364
|
-
}
|
|
365
|
-
async function publishIfReady(input) {
|
|
366
|
-
const openResult = await db.query(`SELECT COUNT(*) as count FROM psa_review_task WHERE status != 'decided'`, []);
|
|
367
|
-
const openCount = Number(openResult.rows[0]?.count ?? 0);
|
|
368
|
-
if (openCount > 0)
|
|
369
|
-
throw new Error("NOT_READY");
|
|
370
|
-
const decidedResult = await db.query(`SELECT * FROM psa_review_task`, []);
|
|
371
|
-
for (const row of decidedResult.rows) {
|
|
372
|
-
if (row.decision !== "approve")
|
|
373
|
-
continue;
|
|
374
|
-
const candQueryResult = await db.query(`SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1`, [row.changeCandidateId]);
|
|
375
|
-
const cand = candQueryResult.rows[0];
|
|
376
|
-
if (!cand)
|
|
377
|
-
continue;
|
|
378
|
-
if (cand.jurisdiction !== input.jurisdiction)
|
|
379
|
-
continue;
|
|
380
|
-
const proposedIds = parseJsonArray(cand.proposedRuleVersionIdsJson);
|
|
381
|
-
for (const rvId of proposedIds) {
|
|
382
|
-
const rvQueryResult = await db.query(`SELECT status FROM psa_rule_version WHERE id = $1 LIMIT 1`, [rvId]);
|
|
383
|
-
const status = String(rvQueryResult.rows[0]?.status ?? "");
|
|
384
|
-
if (status !== "approved")
|
|
385
|
-
throw new Error("NOT_READY");
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
return { published: true };
|
|
389
|
-
}
|
|
390
|
-
return {
|
|
391
|
-
getUserContext,
|
|
392
|
-
setUserContext,
|
|
393
|
-
createRule,
|
|
394
|
-
upsertRuleVersion,
|
|
395
|
-
approveRuleVersion,
|
|
396
|
-
publishSnapshot,
|
|
397
|
-
searchKb,
|
|
398
|
-
answer,
|
|
399
|
-
createChangeCandidate,
|
|
400
|
-
createReviewTask,
|
|
401
|
-
submitDecision,
|
|
402
|
-
publishIfReady
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// src/policy-safe-knowledge-assistant.feature.ts
|
|
407
|
-
import { defineFeature } from "@contractspec/lib.contracts-spec";
|
|
408
|
-
var PolicySafeKnowledgeAssistantFeature = defineFeature({
|
|
409
|
-
meta: {
|
|
410
|
-
key: "policy-safe-knowledge-assistant",
|
|
411
|
-
version: "1.0.0",
|
|
412
|
-
title: "Policy-safe Knowledge Assistant",
|
|
413
|
-
description: "All-in-one example composing locale/jurisdiction gate + versioned KB + HITL pipeline + learning hub.",
|
|
414
|
-
domain: "knowledge",
|
|
415
|
-
owners: ["@examples"],
|
|
416
|
-
tags: ["assistant", "knowledge", "policy", "hitl", "learning"],
|
|
417
|
-
stability: "experimental"
|
|
418
|
-
},
|
|
419
|
-
operations: [
|
|
420
|
-
{ key: "assistant.answer", version: "1.0.0" },
|
|
421
|
-
{ key: "assistant.explainConcept", version: "1.0.0" },
|
|
422
|
-
{ key: "kb.ingestSource", version: "1.0.0" },
|
|
423
|
-
{ key: "kb.upsertRuleVersion", version: "1.0.0" },
|
|
424
|
-
{ key: "kb.approveRuleVersion", version: "1.0.0" },
|
|
425
|
-
{ key: "kb.publishSnapshot", version: "1.0.0" },
|
|
426
|
-
{ key: "kb.search", version: "1.0.0" },
|
|
427
|
-
{ key: "kbPipeline.runWatch", version: "1.0.0" },
|
|
428
|
-
{ key: "kbPipeline.createReviewTask", version: "1.0.0" },
|
|
429
|
-
{ key: "kbPipeline.submitDecision", version: "1.0.0" },
|
|
430
|
-
{ key: "kbPipeline.publishIfReady", version: "1.0.0" }
|
|
431
|
-
],
|
|
432
|
-
events: [
|
|
433
|
-
{ key: "assistant.answer.requested", version: "1.0.0" },
|
|
434
|
-
{ key: "assistant.answer.blocked", version: "1.0.0" },
|
|
435
|
-
{ key: "assistant.answer.delivered", version: "1.0.0" },
|
|
436
|
-
{ key: "kb.source.ingested", version: "1.0.0" },
|
|
437
|
-
{ key: "kb.ruleVersion.created", version: "1.0.0" },
|
|
438
|
-
{ key: "kb.ruleVersion.approved", version: "1.0.0" },
|
|
439
|
-
{ key: "kb.snapshot.published", version: "1.0.0" },
|
|
440
|
-
{ key: "kb.change.detected", version: "1.0.0" },
|
|
441
|
-
{ key: "kb.review.requested", version: "1.0.0" },
|
|
442
|
-
{ key: "kb.review.decided", version: "1.0.0" }
|
|
443
|
-
],
|
|
444
|
-
presentations: [],
|
|
445
|
-
opToPresentation: [],
|
|
446
|
-
presentationsTargets: [],
|
|
447
|
-
capabilities: {
|
|
448
|
-
requires: [
|
|
449
|
-
{ key: "identity", version: "1.0.0" },
|
|
450
|
-
{ key: "audit-trail", version: "1.0.0" },
|
|
451
|
-
{ key: "notifications", version: "1.0.0" },
|
|
452
|
-
{ key: "jobs", version: "1.0.0" },
|
|
453
|
-
{ key: "feature-flags", version: "1.0.0" },
|
|
454
|
-
{ key: "files", version: "1.0.0" },
|
|
455
|
-
{ key: "metering", version: "1.0.0" },
|
|
456
|
-
{ key: "learning-journey", version: "1.0.0" }
|
|
457
|
-
]
|
|
458
|
-
},
|
|
459
|
-
policies: [{ key: "policy-safe.policy.gate", version: "1.0.0" }],
|
|
460
|
-
knowledge: [{ key: "policy-safe.knowledge.rules", version: "1.0.0" }],
|
|
461
|
-
jobs: [{ key: "policy-safe.job.pipeline-watch", version: "1.0.0" }],
|
|
462
|
-
docs: [
|
|
463
|
-
"docs.examples.policy-safe-knowledge-assistant.goal",
|
|
464
|
-
"docs.examples.policy-safe-knowledge-assistant.usage"
|
|
465
|
-
]
|
|
466
|
-
});
|
|
467
|
-
|
|
468
|
-
// src/seed/fixtures.ts
|
|
469
|
-
var DEMO_FIXTURES = {
|
|
470
|
-
jurisdictions: ["EU", "FR"],
|
|
471
|
-
locales: ["en-GB", "fr-FR"],
|
|
472
|
-
demoOrgId: "org_demo",
|
|
473
|
-
demoUserId: "user_demo",
|
|
474
|
-
sources: {
|
|
475
|
-
EU_SOURCE_1: {
|
|
476
|
-
jurisdiction: "EU",
|
|
477
|
-
authority: "DemoAuthority",
|
|
478
|
-
title: "EU Demo Source v1",
|
|
479
|
-
fetchedAt: new Date("2026-01-01T00:00:00.000Z"),
|
|
480
|
-
hash: "hash_eu_v1",
|
|
481
|
-
fileId: "file_eu_v1"
|
|
482
|
-
},
|
|
483
|
-
EU_SOURCE_2: {
|
|
484
|
-
jurisdiction: "EU",
|
|
485
|
-
authority: "DemoAuthority",
|
|
486
|
-
title: "EU Demo Source v2",
|
|
487
|
-
fetchedAt: new Date("2026-02-01T00:00:00.000Z"),
|
|
488
|
-
hash: "hash_eu_v2",
|
|
489
|
-
fileId: "file_eu_v2"
|
|
490
|
-
}
|
|
491
|
-
},
|
|
492
|
-
rules: {
|
|
493
|
-
EU_RULE_TAX: {
|
|
494
|
-
id: "rule_eu_tax",
|
|
495
|
-
jurisdiction: "EU",
|
|
496
|
-
topicKey: "tax_reporting"
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
};
|
|
500
|
-
// src/ui/hooks/usePolicySafeKnowledgeAssistant.ts
|
|
501
|
-
import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
|
|
502
|
-
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
503
|
-
"use client";
|
|
504
|
-
function isCitationLike(value) {
|
|
505
|
-
if (!value || typeof value !== "object")
|
|
506
|
-
return false;
|
|
507
|
-
const v = value;
|
|
508
|
-
return typeof v.kbSnapshotId === "string" && typeof v.sourceId === "string";
|
|
509
|
-
}
|
|
510
|
-
function toCitations(value) {
|
|
511
|
-
if (!Array.isArray(value))
|
|
512
|
-
return [];
|
|
513
|
-
return value.filter(isCitationLike).map((c) => ({
|
|
514
|
-
kbSnapshotId: c.kbSnapshotId,
|
|
515
|
-
sourceId: c.sourceId,
|
|
516
|
-
excerpt: c.excerpt
|
|
517
|
-
}));
|
|
518
|
-
}
|
|
519
|
-
function usePolicySafeKnowledgeAssistant() {
|
|
520
|
-
const { handlers, projectId } = useTemplateRuntime();
|
|
521
|
-
const api = handlers.policySafeKnowledgeAssistant;
|
|
522
|
-
const [state, setState] = useState({
|
|
523
|
-
context: null,
|
|
524
|
-
loading: true,
|
|
525
|
-
error: null,
|
|
526
|
-
lastAnswer: null,
|
|
527
|
-
lastRuleId: null,
|
|
528
|
-
lastRuleVersionId: null,
|
|
529
|
-
lastSnapshotId: null,
|
|
530
|
-
lastReviewTaskId: null
|
|
531
|
-
});
|
|
532
|
-
const refreshContext = useCallback(async () => {
|
|
533
|
-
try {
|
|
534
|
-
setState((s) => ({ ...s, loading: true, error: null }));
|
|
535
|
-
const ctx = await api.getUserContext({ projectId });
|
|
536
|
-
setState((s) => ({
|
|
537
|
-
...s,
|
|
538
|
-
context: {
|
|
539
|
-
locale: ctx.locale,
|
|
540
|
-
jurisdiction: ctx.jurisdiction,
|
|
541
|
-
allowedScope: ctx.allowedScope,
|
|
542
|
-
kbSnapshotId: ctx.kbSnapshotId
|
|
543
|
-
},
|
|
544
|
-
loading: false
|
|
545
|
-
}));
|
|
546
|
-
} catch (e) {
|
|
547
|
-
setState((s) => ({
|
|
548
|
-
...s,
|
|
549
|
-
loading: false,
|
|
550
|
-
error: e instanceof Error ? e : new Error("Unknown error")
|
|
551
|
-
}));
|
|
552
|
-
}
|
|
553
|
-
}, [api, projectId]);
|
|
554
|
-
useEffect(() => {
|
|
555
|
-
refreshContext();
|
|
556
|
-
}, [refreshContext]);
|
|
557
|
-
const setContext = useCallback(async (input) => {
|
|
558
|
-
const ctx = await api.setUserContext({ projectId, ...input });
|
|
559
|
-
setState((s) => ({
|
|
560
|
-
...s,
|
|
561
|
-
context: {
|
|
562
|
-
locale: ctx.locale,
|
|
563
|
-
jurisdiction: ctx.jurisdiction,
|
|
564
|
-
allowedScope: ctx.allowedScope,
|
|
565
|
-
kbSnapshotId: ctx.kbSnapshotId
|
|
566
|
-
}
|
|
567
|
-
}));
|
|
568
|
-
}, [api, projectId]);
|
|
569
|
-
const askAssistant = useCallback(async (question) => {
|
|
570
|
-
const answerUnknown = await api.answer({ projectId, question });
|
|
571
|
-
const answer = answerUnknown;
|
|
572
|
-
setState((s) => ({
|
|
573
|
-
...s,
|
|
574
|
-
lastAnswer: {
|
|
575
|
-
refused: answer.refused,
|
|
576
|
-
refusalReason: answer.refusalReason,
|
|
577
|
-
sections: answer.sections,
|
|
578
|
-
citations: toCitations(answerUnknown.citations)
|
|
579
|
-
}
|
|
580
|
-
}));
|
|
581
|
-
}, [api, projectId]);
|
|
582
|
-
const createDemoRule = useCallback(async () => {
|
|
583
|
-
const rule = await api.createRule({
|
|
584
|
-
projectId,
|
|
585
|
-
jurisdiction: state.context?.jurisdiction ?? "EU",
|
|
586
|
-
topicKey: "tax_reporting"
|
|
587
|
-
});
|
|
588
|
-
setState((s) => ({ ...s, lastRuleId: rule.id }));
|
|
589
|
-
return rule.id;
|
|
590
|
-
}, [api, projectId, state.context?.jurisdiction]);
|
|
591
|
-
const upsertRuleVersion = useCallback(async (input) => {
|
|
592
|
-
const rv = await api.upsertRuleVersion({
|
|
593
|
-
projectId,
|
|
594
|
-
ruleId: input.ruleId,
|
|
595
|
-
content: input.content,
|
|
596
|
-
sourceRefs: [{ sourceDocumentId: "src_demo", excerpt: "demo excerpt" }]
|
|
597
|
-
});
|
|
598
|
-
setState((s) => ({ ...s, lastRuleVersionId: rv.id }));
|
|
599
|
-
return rv.id;
|
|
600
|
-
}, [api, projectId]);
|
|
601
|
-
const approveRuleVersion = useCallback(async (ruleVersionId) => {
|
|
602
|
-
await api.approveRuleVersion({ ruleVersionId, approver: "demo_expert" });
|
|
603
|
-
}, [api]);
|
|
604
|
-
const publishSnapshot = useCallback(async () => {
|
|
605
|
-
const snap = await api.publishSnapshot({
|
|
606
|
-
projectId,
|
|
607
|
-
jurisdiction: state.context?.jurisdiction ?? "EU",
|
|
608
|
-
asOfDate: new Date("2026-02-01T00:00:00.000Z")
|
|
609
|
-
});
|
|
610
|
-
setState((s) => ({ ...s, lastSnapshotId: snap.id }));
|
|
611
|
-
await refreshContext();
|
|
612
|
-
return snap.id;
|
|
613
|
-
}, [api, projectId, refreshContext, state.context?.jurisdiction]);
|
|
614
|
-
const simulateHighRiskChangeAndApprove = useCallback(async (ruleVersionId) => {
|
|
615
|
-
const cand = await api.createChangeCandidate({
|
|
616
|
-
projectId,
|
|
617
|
-
jurisdiction: state.context?.jurisdiction ?? "EU",
|
|
618
|
-
diffSummary: "Simulated change (demo)",
|
|
619
|
-
riskLevel: "high",
|
|
620
|
-
proposedRuleVersionIds: [ruleVersionId]
|
|
621
|
-
});
|
|
622
|
-
const review = await api.createReviewTask({ changeCandidateId: cand.id });
|
|
623
|
-
setState((s) => ({ ...s, lastReviewTaskId: review.id }));
|
|
624
|
-
await api.submitDecision({
|
|
625
|
-
reviewTaskId: review.id,
|
|
626
|
-
decision: "approve",
|
|
627
|
-
decidedByRole: "expert",
|
|
628
|
-
decidedBy: "demo_expert"
|
|
629
|
-
});
|
|
630
|
-
await api.publishIfReady({
|
|
631
|
-
jurisdiction: state.context?.jurisdiction ?? "EU"
|
|
632
|
-
});
|
|
633
|
-
return review.id;
|
|
634
|
-
}, [api, projectId, state.context?.jurisdiction]);
|
|
635
|
-
const derived = useMemo(() => ({ projectId }), [projectId]);
|
|
636
|
-
return {
|
|
637
|
-
state,
|
|
638
|
-
derived,
|
|
639
|
-
actions: {
|
|
640
|
-
refreshContext,
|
|
641
|
-
setContext,
|
|
642
|
-
askAssistant,
|
|
643
|
-
createDemoRule,
|
|
644
|
-
upsertRuleVersion,
|
|
645
|
-
approveRuleVersion,
|
|
646
|
-
publishSnapshot,
|
|
647
|
-
simulateHighRiskChangeAndApprove
|
|
648
|
-
}
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
// src/ui/PolicySafeKnowledgeAssistantDashboard.tsx
|
|
653
|
-
import {
|
|
654
|
-
Button,
|
|
655
|
-
ErrorState,
|
|
656
|
-
LoaderBlock,
|
|
657
|
-
StatCard,
|
|
658
|
-
StatCardGroup
|
|
659
|
-
} from "@contractspec/lib.design-system";
|
|
660
|
-
import { Card } from "@contractspec/lib.ui-kit-web/ui/card";
|
|
661
|
-
import { Input } from "@contractspec/lib.ui-kit-web/ui/input";
|
|
662
|
-
import {
|
|
663
|
-
Select,
|
|
664
|
-
SelectContent,
|
|
665
|
-
SelectItem,
|
|
666
|
-
SelectTrigger,
|
|
667
|
-
SelectValue
|
|
668
|
-
} from "@contractspec/lib.ui-kit-web/ui/select";
|
|
669
|
-
import { Textarea } from "@contractspec/lib.ui-kit-web/ui/textarea";
|
|
670
|
-
import { useCallback as useCallback2, useMemo as useMemo2, useState as useState2 } from "react";
|
|
671
|
-
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
672
|
-
"use client";
|
|
673
|
-
function PolicySafeKnowledgeAssistantDashboard() {
|
|
674
|
-
const { state, actions } = usePolicySafeKnowledgeAssistant();
|
|
675
|
-
const [question, setQuestion] = useState2("reporting obligations");
|
|
676
|
-
const [content, setContent] = useState2("EU: Reporting obligations v2 (updated)");
|
|
677
|
-
const [locale, setLocale] = useState2("en-GB");
|
|
678
|
-
const [jurisdiction, setJurisdiction] = useState2("EU");
|
|
679
|
-
const [allowedScope, setAllowedScope] = useState2("education_only");
|
|
680
|
-
const snapshotId = state.context?.kbSnapshotId ?? state.lastSnapshotId ?? null;
|
|
681
|
-
const stats = useMemo2(() => {
|
|
682
|
-
return [
|
|
683
|
-
{ label: "Locale", value: state.context?.locale ?? "—" },
|
|
684
|
-
{ label: "Jurisdiction", value: state.context?.jurisdiction ?? "—" },
|
|
685
|
-
{ label: "Scope", value: state.context?.allowedScope ?? "—" },
|
|
686
|
-
{ label: "KB Snapshot", value: snapshotId ?? "—" }
|
|
687
|
-
];
|
|
688
|
-
}, [
|
|
689
|
-
snapshotId,
|
|
690
|
-
state.context?.allowedScope,
|
|
691
|
-
state.context?.jurisdiction,
|
|
692
|
-
state.context?.locale
|
|
693
|
-
]);
|
|
694
|
-
const handleSetContext = useCallback2(async () => {
|
|
695
|
-
await actions.setContext({ locale, jurisdiction, allowedScope });
|
|
696
|
-
}, [actions, allowedScope, jurisdiction, locale]);
|
|
697
|
-
const handleAsk = useCallback2(async () => {
|
|
698
|
-
await actions.askAssistant(question);
|
|
699
|
-
}, [actions, question]);
|
|
700
|
-
const handleAdminPublishFlow = useCallback2(async () => {
|
|
701
|
-
const ruleId = state.lastRuleId ?? await actions.createDemoRule();
|
|
702
|
-
const rvId = await actions.upsertRuleVersion({ ruleId, content });
|
|
703
|
-
await actions.approveRuleVersion(rvId);
|
|
704
|
-
await actions.simulateHighRiskChangeAndApprove(rvId);
|
|
705
|
-
await actions.publishSnapshot();
|
|
706
|
-
}, [actions, content, state.lastRuleId]);
|
|
707
|
-
if (state.loading && !state.context) {
|
|
708
|
-
return /* @__PURE__ */ jsxDEV(LoaderBlock, {
|
|
709
|
-
label: "Loading demo..."
|
|
710
|
-
}, undefined, false, undefined, this);
|
|
711
|
-
}
|
|
712
|
-
if (state.error) {
|
|
713
|
-
return /* @__PURE__ */ jsxDEV(ErrorState, {
|
|
714
|
-
title: "Failed to load demo",
|
|
715
|
-
description: state.error.message,
|
|
716
|
-
onRetry: actions.refreshContext,
|
|
717
|
-
retryLabel: "Retry"
|
|
718
|
-
}, undefined, false, undefined, this);
|
|
719
|
-
}
|
|
720
|
-
return /* @__PURE__ */ jsxDEV("div", {
|
|
721
|
-
className: "space-y-6",
|
|
722
|
-
children: [
|
|
723
|
-
/* @__PURE__ */ jsxDEV(StatCardGroup, {
|
|
724
|
-
children: stats.map((s) => /* @__PURE__ */ jsxDEV(StatCard, {
|
|
725
|
-
label: s.label,
|
|
726
|
-
value: String(s.value)
|
|
727
|
-
}, s.label, false, undefined, this))
|
|
728
|
-
}, undefined, false, undefined, this),
|
|
729
|
-
/* @__PURE__ */ jsxDEV(Card, {
|
|
730
|
-
className: "p-4",
|
|
731
|
-
children: [
|
|
732
|
-
/* @__PURE__ */ jsxDEV("h3", {
|
|
733
|
-
className: "font-semibold text-lg",
|
|
734
|
-
children: "1) Onboarding (explicit locale + jurisdiction)"
|
|
735
|
-
}, undefined, false, undefined, this),
|
|
736
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
737
|
-
className: "mt-3 grid gap-3 md:grid-cols-3",
|
|
738
|
-
children: [
|
|
739
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
740
|
-
children: [
|
|
741
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
742
|
-
className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
|
|
743
|
-
children: "Locale"
|
|
744
|
-
}, undefined, false, undefined, this),
|
|
745
|
-
/* @__PURE__ */ jsxDEV(Input, {
|
|
746
|
-
value: locale,
|
|
747
|
-
onChange: (e) => setLocale(e.target.value)
|
|
748
|
-
}, undefined, false, undefined, this)
|
|
749
|
-
]
|
|
750
|
-
}, undefined, true, undefined, this),
|
|
751
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
752
|
-
children: [
|
|
753
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
754
|
-
className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
|
|
755
|
-
children: "Jurisdiction"
|
|
756
|
-
}, undefined, false, undefined, this),
|
|
757
|
-
/* @__PURE__ */ jsxDEV(Input, {
|
|
758
|
-
value: jurisdiction,
|
|
759
|
-
onChange: (e) => setJurisdiction(e.target.value)
|
|
760
|
-
}, undefined, false, undefined, this)
|
|
761
|
-
]
|
|
762
|
-
}, undefined, true, undefined, this),
|
|
763
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
764
|
-
children: [
|
|
765
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
766
|
-
className: "mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",
|
|
767
|
-
children: "Allowed scope"
|
|
768
|
-
}, undefined, false, undefined, this),
|
|
769
|
-
/* @__PURE__ */ jsxDEV(Select, {
|
|
770
|
-
value: allowedScope,
|
|
771
|
-
onValueChange: (v) => setAllowedScope(v),
|
|
772
|
-
children: [
|
|
773
|
-
/* @__PURE__ */ jsxDEV(SelectTrigger, {
|
|
774
|
-
children: /* @__PURE__ */ jsxDEV(SelectValue, {
|
|
775
|
-
placeholder: "Select scope"
|
|
776
|
-
}, undefined, false, undefined, this)
|
|
777
|
-
}, undefined, false, undefined, this),
|
|
778
|
-
/* @__PURE__ */ jsxDEV(SelectContent, {
|
|
779
|
-
children: [
|
|
780
|
-
/* @__PURE__ */ jsxDEV(SelectItem, {
|
|
781
|
-
value: "education_only",
|
|
782
|
-
children: "education_only"
|
|
783
|
-
}, undefined, false, undefined, this),
|
|
784
|
-
/* @__PURE__ */ jsxDEV(SelectItem, {
|
|
785
|
-
value: "generic_info",
|
|
786
|
-
children: "generic_info"
|
|
787
|
-
}, undefined, false, undefined, this),
|
|
788
|
-
/* @__PURE__ */ jsxDEV(SelectItem, {
|
|
789
|
-
value: "escalation_required",
|
|
790
|
-
children: "escalation_required"
|
|
791
|
-
}, undefined, false, undefined, this)
|
|
792
|
-
]
|
|
793
|
-
}, undefined, true, undefined, this)
|
|
794
|
-
]
|
|
795
|
-
}, undefined, true, undefined, this)
|
|
796
|
-
]
|
|
797
|
-
}, undefined, true, undefined, this)
|
|
798
|
-
]
|
|
799
|
-
}, undefined, true, undefined, this),
|
|
800
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
801
|
-
className: "mt-4 flex gap-2",
|
|
802
|
-
children: [
|
|
803
|
-
/* @__PURE__ */ jsxDEV(Button, {
|
|
804
|
-
onPress: handleSetContext,
|
|
805
|
-
children: "Save context"
|
|
806
|
-
}, undefined, false, undefined, this),
|
|
807
|
-
/* @__PURE__ */ jsxDEV(Button, {
|
|
808
|
-
variant: "outline",
|
|
809
|
-
onPress: actions.refreshContext,
|
|
810
|
-
children: "Refresh"
|
|
811
|
-
}, undefined, false, undefined, this)
|
|
812
|
-
]
|
|
813
|
-
}, undefined, true, undefined, this)
|
|
814
|
-
]
|
|
815
|
-
}, undefined, true, undefined, this),
|
|
816
|
-
/* @__PURE__ */ jsxDEV(Card, {
|
|
817
|
-
className: "p-4",
|
|
818
|
-
children: [
|
|
819
|
-
/* @__PURE__ */ jsxDEV("h3", {
|
|
820
|
-
className: "font-semibold text-lg",
|
|
821
|
-
children: "2) Ask the assistant (must cite KB snapshot)"
|
|
822
|
-
}, undefined, false, undefined, this),
|
|
823
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
824
|
-
className: "mt-3 flex flex-col gap-3",
|
|
825
|
-
children: [
|
|
826
|
-
/* @__PURE__ */ jsxDEV(Input, {
|
|
827
|
-
value: question,
|
|
828
|
-
onChange: (e) => setQuestion(e.target.value)
|
|
829
|
-
}, undefined, false, undefined, this),
|
|
830
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
831
|
-
className: "flex gap-2",
|
|
832
|
-
children: /* @__PURE__ */ jsxDEV(Button, {
|
|
833
|
-
onPress: handleAsk,
|
|
834
|
-
children: "Ask"
|
|
835
|
-
}, undefined, false, undefined, this)
|
|
836
|
-
}, undefined, false, undefined, this)
|
|
837
|
-
]
|
|
838
|
-
}, undefined, true, undefined, this),
|
|
839
|
-
state.lastAnswer ? /* @__PURE__ */ jsxDEV("div", {
|
|
840
|
-
className: "mt-4 space-y-3",
|
|
841
|
-
children: [
|
|
842
|
-
state.lastAnswer.refused ? /* @__PURE__ */ jsxDEV("div", {
|
|
843
|
-
className: "text-red-600 text-sm",
|
|
844
|
-
children: [
|
|
845
|
-
"Refused: ",
|
|
846
|
-
state.lastAnswer.refusalReason ?? "UNKNOWN"
|
|
847
|
-
]
|
|
848
|
-
}, undefined, true, undefined, this) : null,
|
|
849
|
-
state.lastAnswer.sections.map((s, idx) => /* @__PURE__ */ jsxDEV("div", {
|
|
850
|
-
children: [
|
|
851
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
852
|
-
className: "font-semibold text-sm",
|
|
853
|
-
children: s.heading
|
|
854
|
-
}, undefined, false, undefined, this),
|
|
855
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
856
|
-
className: "text-muted-foreground text-sm",
|
|
857
|
-
children: s.body
|
|
858
|
-
}, undefined, false, undefined, this)
|
|
859
|
-
]
|
|
860
|
-
}, `${s.heading}-${idx}`, true, undefined, this)),
|
|
861
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
862
|
-
className: "font-semibold text-sm",
|
|
863
|
-
children: "Citations"
|
|
864
|
-
}, undefined, false, undefined, this),
|
|
865
|
-
/* @__PURE__ */ jsxDEV("ul", {
|
|
866
|
-
className: "list-disc pl-5 text-muted-foreground text-sm",
|
|
867
|
-
children: state.lastAnswer.citations.map((c) => /* @__PURE__ */ jsxDEV("li", {
|
|
868
|
-
children: [
|
|
869
|
-
c.kbSnapshotId,
|
|
870
|
-
" — ",
|
|
871
|
-
c.sourceId
|
|
872
|
-
]
|
|
873
|
-
}, `${c.kbSnapshotId}-${c.sourceId}`, true, undefined, this))
|
|
874
|
-
}, undefined, false, undefined, this)
|
|
875
|
-
]
|
|
876
|
-
}, undefined, true, undefined, this) : null
|
|
877
|
-
]
|
|
878
|
-
}, undefined, true, undefined, this),
|
|
879
|
-
/* @__PURE__ */ jsxDEV(Card, {
|
|
880
|
-
className: "p-4",
|
|
881
|
-
children: [
|
|
882
|
-
/* @__PURE__ */ jsxDEV("h3", {
|
|
883
|
-
className: "font-semibold text-lg",
|
|
884
|
-
children: "3) Admin: publish a new snapshot (HITL)"
|
|
885
|
-
}, undefined, false, undefined, this),
|
|
886
|
-
/* @__PURE__ */ jsxDEV("div", {
|
|
887
|
-
className: "mt-3 space-y-3",
|
|
888
|
-
children: [
|
|
889
|
-
/* @__PURE__ */ jsxDEV(Textarea, {
|
|
890
|
-
value: content,
|
|
891
|
-
onChange: (e) => setContent(e.target.value)
|
|
892
|
-
}, undefined, false, undefined, this),
|
|
893
|
-
/* @__PURE__ */ jsxDEV(Button, {
|
|
894
|
-
onPress: handleAdminPublishFlow,
|
|
895
|
-
children: "Simulate change → review → approve → publish snapshot"
|
|
896
|
-
}, undefined, false, undefined, this)
|
|
897
|
-
]
|
|
898
|
-
}, undefined, true, undefined, this)
|
|
899
|
-
]
|
|
900
|
-
}, undefined, true, undefined, this),
|
|
901
|
-
/* @__PURE__ */ jsxDEV(Card, {
|
|
902
|
-
className: "p-4",
|
|
903
|
-
children: [
|
|
904
|
-
/* @__PURE__ */ jsxDEV("h3", {
|
|
905
|
-
className: "font-semibold text-lg",
|
|
906
|
-
children: "4) Learning hub (patterns)"
|
|
907
|
-
}, undefined, false, undefined, this),
|
|
908
|
-
/* @__PURE__ */ jsxDEV("p", {
|
|
909
|
-
className: "mt-2 text-muted-foreground text-sm",
|
|
910
|
-
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."
|
|
911
|
-
}, undefined, false, undefined, this)
|
|
912
|
-
]
|
|
913
|
-
}, undefined, true, undefined, this)
|
|
914
|
-
]
|
|
915
|
-
}, undefined, true, undefined, this);
|
|
916
|
-
}
|
|
917
|
-
export {
|
|
918
|
-
example_default as example,
|
|
919
|
-
createPolicySafeKnowledgeAssistantHandlers,
|
|
920
|
-
buildPolicySafeAnswer,
|
|
921
|
-
PolicySafeKnowledgeAssistantFeature,
|
|
922
|
-
PolicySafeKnowledgeAssistantDashboard,
|
|
923
|
-
DEMO_FIXTURES
|
|
924
|
-
};
|
|
14
|
+
5) Learning hub: drills session, ambient tip, quest start + step completion.`}];b(x);import{defineExample as l}from"@contractspec/lib.contracts-spec";var o=l({meta:{key:"policy-safe-knowledge-assistant",version:"1.0.0",title:"Policy-safe Knowledge Assistant",description:"All-in-one template: locale/jurisdiction gating + versioned KB snapshots + HITL update pipeline + learning hub.",kind:"template",visibility:"public",stability:"experimental",owners:["@platform.core"],tags:["assistant","knowledge","policy","hitl","learning"]},docs:{goalDocId:"docs.examples.policy-safe-knowledge-assistant.goal",usageDocId:"docs.examples.policy-safe-knowledge-assistant.usage"},entrypoints:{packageName:"@contractspec/example.policy-safe-knowledge-assistant",feature:"./policy-safe-knowledge-assistant.feature",docs:"./docs"},surfaces:{templates:!0,sandbox:{enabled:!0,modes:["playground","specs","builder","markdown","evolution"]},studio:{enabled:!0,installable:!0},mcp:{enabled:!0}}}),c=o;import{enforceAllowedScope as r,enforceCitations as d,validateEnvelope as a}from"@contractspec/example.locale-jurisdiction-gate/policy/guard";async function k(E){let U=a(E.envelope);if(!U.ok)return{locale:E.envelope.locale??"en-GB",jurisdiction:E.envelope.regulatoryContext?.jurisdiction??"UNKNOWN",allowedScope:E.envelope.allowedScope??"education_only",sections:[{heading:"Request blocked",body:U.error.message}],citations:[],disclaimers:["This system refuses to answer without a valid envelope."],riskFlags:[U.error.code],refused:!0,refusalReason:U.error.code};let Z=await E.kbSearch({snapshotId:U.value.kbSnapshotId,jurisdiction:U.value.regulatoryContext?.jurisdiction??"UNKNOWN",query:E.question}),N=Z.items.map((H)=>({kbSnapshotId:U.value.kbSnapshotId,sourceType:"ruleVersion",sourceId:H.ruleVersionId,title:"Curated rule version",excerpt:H.excerpt})),z={locale:U.value.locale,jurisdiction:U.value.regulatoryContext?.jurisdiction??"UNKNOWN",allowedScope:U.value.allowedScope,sections:[{heading:"Answer (KB-derived)",body:Z.items.length>0?`This answer is derived from ${Z.items.length} curated rule version(s) in the referenced snapshot.`:"No curated knowledge found in the referenced snapshot."}],citations:N,disclaimers:["Educational demo only."],riskFlags:[]},W=r(U.value.allowedScope,z);if(!W.ok)return{...z,sections:[{heading:"Escalation required",body:W.error.message}],refused:!0,refusalReason:W.error.code,riskFlags:[...z.riskFlags??[],W.error.code]};let Y=d(z);if(!Y.ok)return{...z,sections:[{heading:"Request blocked",body:Y.error.message}],citations:[],refused:!0,refusalReason:Y.error.code,riskFlags:[...z.riskFlags??[],Y.error.code]};return z}import{web as u}from"@contractspec/lib.runtime-sandbox";var{generateId:K}=u;function I(E){if(!E)return[];try{let U=JSON.parse(E);return Array.isArray(U)?U.filter((Z)=>typeof Z==="string"):[]}catch{return[]}}function V(){return new Date().toISOString()}function J0(E){async function U(_){let O=(await E.query('SELECT * FROM psa_user_context WHERE "projectId" = $1 LIMIT 1',[_.projectId])).rows[0];if(!O)return{projectId:_.projectId,locale:"en-GB",jurisdiction:"EU",allowedScope:"education_only",kbSnapshotId:null};return{projectId:O.projectId,locale:O.locale,jurisdiction:O.jurisdiction,allowedScope:O.allowedScope,kbSnapshotId:O.kbSnapshotId}}async function Z(_){if((await E.query('SELECT "projectId" FROM psa_user_context WHERE "projectId" = $1 LIMIT 1',[_.projectId])).rows.length)await E.execute('UPDATE psa_user_context SET locale = $1, jurisdiction = $2, "allowedScope" = $3 WHERE "projectId" = $4',[_.locale,_.jurisdiction,_.allowedScope,_.projectId]);else await E.execute('INSERT INTO psa_user_context ("projectId", locale, jurisdiction, "allowedScope", "kbSnapshotId") VALUES ($1, $2, $3, $4, $5)',[_.projectId,_.locale,_.jurisdiction,_.allowedScope,null]);return await U({projectId:_.projectId})}async function N(_){let D=K("psa_rule");return await E.execute('INSERT INTO psa_rule (id, "projectId", jurisdiction, "topicKey") VALUES ($1, $2, $3, $4)',[D,_.projectId,_.jurisdiction,_.topicKey]),{id:D,..._}}async function z(_){if(!_.sourceRefs.length)throw Error("SOURCE_REFS_REQUIRED");let O=(await E.query("SELECT * FROM psa_rule WHERE id = $1 LIMIT 1",[_.ruleId])).rows[0];if(!O)throw Error("RULE_NOT_FOUND");let T=await E.query('SELECT MAX(version) as maxVersion FROM psa_rule_version WHERE "ruleId" = $1',[_.ruleId]),M=Number(T.rows[0]?.maxVersion??0)+1,$=K("psa_rv"),R=V();return await E.execute(`INSERT INTO psa_rule_version (id, "ruleId", jurisdiction, "topicKey", version, content, status, "sourceRefsJson", "approvedBy", "approvedAt", "createdAt")
|
|
15
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,[$,_.ruleId,O.jurisdiction,O.topicKey,M,_.content,"draft",JSON.stringify(_.sourceRefs),null,null,R]),{id:$,ruleId:_.ruleId,jurisdiction:O.jurisdiction,topicKey:O.topicKey,version:M,content:_.content,status:"draft",sourceRefs:_.sourceRefs,createdAt:new Date(R)}}async function W(_){let D=V();return await E.execute('UPDATE psa_rule_version SET status = $1, "approvedBy" = $2, "approvedAt" = $3 WHERE id = $4',["approved",_.approver,D,_.ruleVersionId]),{ruleVersionId:_.ruleVersionId,status:"approved"}}async function Y(_){let O=(await E.query("SELECT id FROM psa_rule_version WHERE jurisdiction = $1 AND status = 'approved' ORDER BY id ASC",[_.jurisdiction])).rows.map((M)=>M.id).filter(Boolean);if(!O.length)throw Error("NO_APPROVED_RULES");let T=K("psa_snap"),X=V();return await E.execute(`INSERT INTO psa_snapshot (id, jurisdiction, "asOfDate", "includedRuleVersionIdsJson", "publishedAt")
|
|
16
|
+
VALUES ($1, $2, $3, $4, $5)`,[T,_.jurisdiction,_.asOfDate.toISOString(),JSON.stringify(O),X]),await E.execute('UPDATE psa_user_context SET "kbSnapshotId" = $1 WHERE "projectId" = $2',[T,_.projectId]),{id:T,jurisdiction:_.jurisdiction,includedRuleVersionIds:O}}async function H(_){let O=(await E.query("SELECT * FROM psa_snapshot WHERE id = $1 LIMIT 1",[_.snapshotId])).rows[0];if(!O)throw Error("SNAPSHOT_NOT_FOUND");if(O.jurisdiction!==_.jurisdiction)throw Error("JURISDICTION_MISMATCH");let T=I(O.includedRuleVersionIdsJson),X=_.query.toLowerCase().split(/\s+/).map(($)=>$.trim()).filter(Boolean),M=[];for(let $ of T){let P=(await E.query("SELECT * FROM psa_rule_version WHERE id = $1 LIMIT 1",[$])).rows[0];if(!P)continue;let f=P.content.toLowerCase();if(!(X.length?X.every((j)=>f.includes(j)):!0))continue;M.push({ruleVersionId:P.id,excerpt:P.content.slice(0,140)})}return{items:M}}async function Q(_){let D=await U({projectId:_.projectId});if(!D.kbSnapshotId)return await k({envelope:{traceId:K("trace"),locale:D.locale,kbSnapshotId:"",allowedScope:D.allowedScope,regulatoryContext:{jurisdiction:D.jurisdiction}},question:_.question,kbSearch:async()=>({items:[]})});return await k({envelope:{traceId:K("trace"),locale:D.locale,kbSnapshotId:D.kbSnapshotId,allowedScope:D.allowedScope,regulatoryContext:{jurisdiction:D.jurisdiction}},question:_.question,kbSearch:async(O)=>await H(O)})}async function q(_){let D=K("psa_change");return await E.execute(`INSERT INTO psa_change_candidate (id, "projectId", jurisdiction, "detectedAt", "diffSummary", "riskLevel", "proposedRuleVersionIdsJson")
|
|
17
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)`,[D,_.projectId,_.jurisdiction,V(),_.diffSummary,_.riskLevel,JSON.stringify(_.proposedRuleVersionIds)]),{id:D}}async function J(_){let O=(await E.query("SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1",[_.changeCandidateId])).rows[0];if(!O)throw Error("CHANGE_CANDIDATE_NOT_FOUND");let T=O.riskLevel==="high"?"expert":"curator",X=K("psa_review");return await E.execute(`INSERT INTO psa_review_task (id, "changeCandidateId", status, "assignedRole", decision, "decidedAt", "decidedBy")
|
|
18
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)`,[X,_.changeCandidateId,"open",T,null,null,null]),{id:X,assignedRole:T}}async function y(_){let O=(await E.query("SELECT * FROM psa_review_task WHERE id = $1 LIMIT 1",[_.reviewTaskId])).rows[0];if(!O)throw Error("REVIEW_TASK_NOT_FOUND");let X=(await E.query("SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1",[O.changeCandidateId])).rows[0];if(!X)throw Error("CHANGE_CANDIDATE_NOT_FOUND");if(X.riskLevel==="high"&&_.decision==="approve"&&_.decidedByRole!=="expert")throw Error("FORBIDDEN_ROLE");let M=V();return await E.execute('UPDATE psa_review_task SET status = $1, decision = $2, "decidedAt" = $3, "decidedBy" = $4 WHERE id = $5',["decided",_.decision,M,_.decidedBy,_.reviewTaskId]),{id:_.reviewTaskId,status:"decided"}}async function B(_){let D=await E.query("SELECT COUNT(*) as count FROM psa_review_task WHERE status != 'decided'",[]);if(Number(D.rows[0]?.count??0)>0)throw Error("NOT_READY");let T=await E.query("SELECT * FROM psa_review_task",[]);for(let X of T.rows){if(X.decision!=="approve")continue;let $=(await E.query("SELECT * FROM psa_change_candidate WHERE id = $1 LIMIT 1",[X.changeCandidateId])).rows[0];if(!$)continue;if($.jurisdiction!==_.jurisdiction)continue;let R=I($.proposedRuleVersionIdsJson);for(let P of R){let f=await E.query("SELECT status FROM psa_rule_version WHERE id = $1 LIMIT 1",[P]);if(String(f.rows[0]?.status??"")!=="approved")throw Error("NOT_READY")}}return{published:!0}}return{getUserContext:U,setUserContext:Z,createRule:N,upsertRuleVersion:z,approveRuleVersion:W,publishSnapshot:Y,searchKb:H,answer:Q,createChangeCandidate:q,createReviewTask:J,submitDecision:y,publishIfReady:B}}import{defineFeature as p}from"@contractspec/lib.contracts-spec";var P0=p({meta:{key:"policy-safe-knowledge-assistant",version:"1.0.0",title:"Policy-safe Knowledge Assistant",description:"All-in-one example composing locale/jurisdiction gate + versioned KB + HITL pipeline + learning hub.",domain:"knowledge",owners:["@examples"],tags:["assistant","knowledge","policy","hitl","learning"],stability:"experimental"},operations:[{key:"assistant.answer",version:"1.0.0"},{key:"assistant.explainConcept",version:"1.0.0"},{key:"kb.ingestSource",version:"1.0.0"},{key:"kb.upsertRuleVersion",version:"1.0.0"},{key:"kb.approveRuleVersion",version:"1.0.0"},{key:"kb.publishSnapshot",version:"1.0.0"},{key:"kb.search",version:"1.0.0"},{key:"kbPipeline.runWatch",version:"1.0.0"},{key:"kbPipeline.createReviewTask",version:"1.0.0"},{key:"kbPipeline.submitDecision",version:"1.0.0"},{key:"kbPipeline.publishIfReady",version:"1.0.0"}],events:[{key:"assistant.answer.requested",version:"1.0.0"},{key:"assistant.answer.blocked",version:"1.0.0"},{key:"assistant.answer.delivered",version:"1.0.0"},{key:"kb.source.ingested",version:"1.0.0"},{key:"kb.ruleVersion.created",version:"1.0.0"},{key:"kb.ruleVersion.approved",version:"1.0.0"},{key:"kb.snapshot.published",version:"1.0.0"},{key:"kb.change.detected",version:"1.0.0"},{key:"kb.review.requested",version:"1.0.0"},{key:"kb.review.decided",version:"1.0.0"}],presentations:[],opToPresentation:[],presentationsTargets:[],capabilities:{requires:[{key:"identity",version:"1.0.0"},{key:"audit-trail",version:"1.0.0"},{key:"notifications",version:"1.0.0"},{key:"jobs",version:"1.0.0"},{key:"feature-flags",version:"1.0.0"},{key:"files",version:"1.0.0"},{key:"metering",version:"1.0.0"},{key:"learning-journey",version:"1.0.0"}]},policies:[{key:"policy-safe.policy.gate",version:"1.0.0"}],knowledge:[{key:"policy-safe.knowledge.rules",version:"1.0.0"}],jobs:[{key:"policy-safe.job.pipeline-watch",version:"1.0.0"}],docs:["docs.examples.policy-safe-knowledge-assistant.goal","docs.examples.policy-safe-knowledge-assistant.usage"]});var y0={jurisdictions:["EU","FR"],locales:["en-GB","fr-FR"],demoOrgId:"org_demo",demoUserId:"user_demo",sources:{EU_SOURCE_1:{jurisdiction:"EU",authority:"DemoAuthority",title:"EU Demo Source v1",fetchedAt:new Date("2026-01-01T00:00:00.000Z"),hash:"hash_eu_v1",fileId:"file_eu_v1"},EU_SOURCE_2:{jurisdiction:"EU",authority:"DemoAuthority",title:"EU Demo Source v2",fetchedAt:new Date("2026-02-01T00:00:00.000Z"),hash:"hash_eu_v2",fileId:"file_eu_v2"}},rules:{EU_RULE_TAX:{id:"rule_eu_tax",jurisdiction:"EU",topicKey:"tax_reporting"}}};import{useTemplateRuntime as i}from"@contractspec/lib.example-shared-ui";import{useCallback as L,useEffect as s,useMemo as n,useState as e}from"react";function t(E){if(!E||typeof E!=="object")return!1;let U=E;return typeof U.kbSnapshotId==="string"&&typeof U.sourceId==="string"}function _0(E){if(!Array.isArray(E))return[];return E.filter(t).map((U)=>({kbSnapshotId:U.kbSnapshotId,sourceId:U.sourceId,excerpt:U.excerpt}))}function v(){let{handlers:E,projectId:U}=i(),Z=E.policySafeKnowledgeAssistant,[N,z]=e({context:null,loading:!0,error:null,lastAnswer:null,lastRuleId:null,lastRuleVersionId:null,lastSnapshotId:null,lastReviewTaskId:null}),W=L(async()=>{try{z((O)=>({...O,loading:!0,error:null}));let D=await Z.getUserContext({projectId:U});z((O)=>({...O,context:{locale:D.locale,jurisdiction:D.jurisdiction,allowedScope:D.allowedScope,kbSnapshotId:D.kbSnapshotId},loading:!1}))}catch(D){z((O)=>({...O,loading:!1,error:D instanceof Error?D:Error("Unknown error")}))}},[Z,U]);s(()=>{W()},[W]);let Y=L(async(D)=>{let O=await Z.setUserContext({projectId:U,...D});z((T)=>({...T,context:{locale:O.locale,jurisdiction:O.jurisdiction,allowedScope:O.allowedScope,kbSnapshotId:O.kbSnapshotId}}))},[Z,U]),H=L(async(D)=>{let O=await Z.answer({projectId:U,question:D}),T=O;z((X)=>({...X,lastAnswer:{refused:T.refused,refusalReason:T.refusalReason,sections:T.sections,citations:_0(O.citations)}}))},[Z,U]),Q=L(async()=>{let D=await Z.createRule({projectId:U,jurisdiction:N.context?.jurisdiction??"EU",topicKey:"tax_reporting"});return z((O)=>({...O,lastRuleId:D.id})),D.id},[Z,U,N.context?.jurisdiction]),q=L(async(D)=>{let O=await Z.upsertRuleVersion({projectId:U,ruleId:D.ruleId,content:D.content,sourceRefs:[{sourceDocumentId:"src_demo",excerpt:"demo excerpt"}]});return z((T)=>({...T,lastRuleVersionId:O.id})),O.id},[Z,U]),J=L(async(D)=>{await Z.approveRuleVersion({ruleVersionId:D,approver:"demo_expert"})},[Z]),y=L(async()=>{let D=await Z.publishSnapshot({projectId:U,jurisdiction:N.context?.jurisdiction??"EU",asOfDate:new Date("2026-02-01T00:00:00.000Z")});return z((O)=>({...O,lastSnapshotId:D.id})),await W(),D.id},[Z,U,W,N.context?.jurisdiction]),B=L(async(D)=>{let O=await Z.createChangeCandidate({projectId:U,jurisdiction:N.context?.jurisdiction??"EU",diffSummary:"Simulated change (demo)",riskLevel:"high",proposedRuleVersionIds:[D]}),T=await Z.createReviewTask({changeCandidateId:O.id});return z((X)=>({...X,lastReviewTaskId:T.id})),await Z.submitDecision({reviewTaskId:T.id,decision:"approve",decidedByRole:"expert",decidedBy:"demo_expert"}),await Z.publishIfReady({jurisdiction:N.context?.jurisdiction??"EU"}),T.id},[Z,U,N.context?.jurisdiction]),_=n(()=>({projectId:U}),[U]);return{state:N,derived:_,actions:{refreshContext:W,setContext:Y,askAssistant:H,createDemoRule:Q,upsertRuleVersion:q,approveRuleVersion:J,publishSnapshot:y,simulateHighRiskChangeAndApprove:B}}}import{Button as m,ErrorState as E0,LoaderBlock as U0,StatCard as O0,StatCardGroup as D0}from"@contractspec/lib.design-system";import{Card as A}from"@contractspec/lib.ui-kit-web/ui/card";import{Input as g}from"@contractspec/lib.ui-kit-web/ui/input";import{Select as X0,SelectContent as Z0,SelectItem as S,SelectTrigger as F0,SelectValue as T0}from"@contractspec/lib.ui-kit-web/ui/select";import{Textarea as z0}from"@contractspec/lib.ui-kit-web/ui/textarea";import{useCallback as C,useMemo as G0,useState as h}from"react";import{jsx as F,jsxs as G}from"react/jsx-runtime";function j0(){let{state:E,actions:U}=v(),[Z,N]=h("reporting obligations"),[z,W]=h("EU: Reporting obligations v2 (updated)"),[Y,H]=h("en-GB"),[Q,q]=h("EU"),[J,y]=h("education_only"),B=E.context?.kbSnapshotId??E.lastSnapshotId??null,_=G0(()=>{return[{label:"Locale",value:E.context?.locale??"—"},{label:"Jurisdiction",value:E.context?.jurisdiction??"—"},{label:"Scope",value:E.context?.allowedScope??"—"},{label:"KB Snapshot",value:B??"—"}]},[B,E.context?.allowedScope,E.context?.jurisdiction,E.context?.locale]),D=C(async()=>{await U.setContext({locale:Y,jurisdiction:Q,allowedScope:J})},[U,J,Q,Y]),O=C(async()=>{await U.askAssistant(Z)},[U,Z]),T=C(async()=>{let X=E.lastRuleId??await U.createDemoRule(),M=await U.upsertRuleVersion({ruleId:X,content:z});await U.approveRuleVersion(M),await U.simulateHighRiskChangeAndApprove(M),await U.publishSnapshot()},[U,z,E.lastRuleId]);if(E.loading&&!E.context)return F(U0,{label:"Loading demo..."});if(E.error)return F(E0,{title:"Failed to load demo",description:E.error.message,onRetry:U.refreshContext,retryLabel:"Retry"});return G("div",{className:"space-y-6",children:[F(D0,{children:_.map((X)=>F(O0,{label:X.label,value:String(X.value)},X.label))}),G(A,{className:"p-4",children:[F("h3",{className:"font-semibold text-lg",children:"1) Onboarding (explicit locale + jurisdiction)"}),G("div",{className:"mt-3 grid gap-3 md:grid-cols-3",children:[G("div",{children:[F("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Locale"}),F(g,{value:Y,onChange:(X)=>H(X.target.value)})]}),G("div",{children:[F("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Jurisdiction"}),F(g,{value:Q,onChange:(X)=>q(X.target.value)})]}),G("div",{children:[F("div",{className:"mb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide",children:"Allowed scope"}),G(X0,{value:J,onValueChange:(X)=>y(X),children:[F(F0,{children:F(T0,{placeholder:"Select scope"})}),G(Z0,{children:[F(S,{value:"education_only",children:"education_only"}),F(S,{value:"generic_info",children:"generic_info"}),F(S,{value:"escalation_required",children:"escalation_required"})]})]})]})]}),G("div",{className:"mt-4 flex gap-2",children:[F(m,{onPress:D,children:"Save context"}),F(m,{variant:"outline",onPress:U.refreshContext,children:"Refresh"})]})]}),G(A,{className:"p-4",children:[F("h3",{className:"font-semibold text-lg",children:"2) Ask the assistant (must cite KB snapshot)"}),G("div",{className:"mt-3 flex flex-col gap-3",children:[F(g,{value:Z,onChange:(X)=>N(X.target.value)}),F("div",{className:"flex gap-2",children:F(m,{onPress:O,children:"Ask"})})]}),E.lastAnswer?G("div",{className:"mt-4 space-y-3",children:[E.lastAnswer.refused?G("div",{className:"text-red-600 text-sm",children:["Refused: ",E.lastAnswer.refusalReason??"UNKNOWN"]}):null,E.lastAnswer.sections.map((X,M)=>G("div",{children:[F("div",{className:"font-semibold text-sm",children:X.heading}),F("div",{className:"text-muted-foreground text-sm",children:X.body})]},`${X.heading}-${M}`)),F("div",{className:"font-semibold text-sm",children:"Citations"}),F("ul",{className:"list-disc pl-5 text-muted-foreground text-sm",children:E.lastAnswer.citations.map((X)=>G("li",{children:[X.kbSnapshotId," — ",X.sourceId]},`${X.kbSnapshotId}-${X.sourceId}`))})]}):null]}),G(A,{className:"p-4",children:[F("h3",{className:"font-semibold text-lg",children:"3) Admin: publish a new snapshot (HITL)"}),G("div",{className:"mt-3 space-y-3",children:[F(z0,{value:z,onChange:(X)=>W(X.target.value)}),F(m,{onPress:T,children:"Simulate change → review → approve → publish snapshot"})]})]}),G(A,{className:"p-4",children:[F("h3",{className:"font-semibold text-lg",children:"4) Learning hub (patterns)"}),F("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{c as example,J0 as createPolicySafeKnowledgeAssistantHandlers,k as buildPolicySafeAnswer,P0 as PolicySafeKnowledgeAssistantFeature,j0 as PolicySafeKnowledgeAssistantDashboard,y0 as DEMO_FIXTURES};
|