@contractspec/example.policy-safe-knowledge-assistant 1.57.0 → 1.58.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 (88) hide show
  1. package/.turbo/turbo-build.log +58 -60
  2. package/.turbo/turbo-prebuild.log +1 -0
  3. package/CHANGELOG.md +21 -0
  4. package/dist/browser/docs/index.js +38 -0
  5. package/dist/browser/docs/policy-safe-knowledge-assistant.docblock.js +38 -0
  6. package/dist/browser/example.js +37 -0
  7. package/dist/browser/handlers/index.js +334 -0
  8. package/dist/browser/handlers/policy-safe-knowledge-assistant.handlers.js +334 -0
  9. package/dist/browser/index.js +917 -0
  10. package/dist/browser/orchestrator/buildAnswer.js +73 -0
  11. package/dist/browser/policy-safe-knowledge-assistant.feature.js +57 -0
  12. package/dist/browser/seed/fixtures.js +35 -0
  13. package/dist/browser/seed/index.js +35 -0
  14. package/dist/browser/seeders/index.js +12 -0
  15. package/dist/browser/ui/PolicySafeKnowledgeAssistantDashboard.js +420 -0
  16. package/dist/browser/ui/hooks/usePolicySafeKnowledgeAssistant.js +154 -0
  17. package/dist/browser/ui/index.js +420 -0
  18. package/dist/docs/index.d.ts +2 -1
  19. package/dist/docs/index.d.ts.map +1 -0
  20. package/dist/docs/index.js +39 -1
  21. package/dist/docs/policy-safe-knowledge-assistant.docblock.d.ts +2 -1
  22. package/dist/docs/policy-safe-knowledge-assistant.docblock.d.ts.map +1 -0
  23. package/dist/docs/policy-safe-knowledge-assistant.docblock.js +37 -33
  24. package/dist/example.d.ts +2 -6
  25. package/dist/example.d.ts.map +1 -1
  26. package/dist/example.js +36 -51
  27. package/dist/handlers/index.d.ts +2 -2
  28. package/dist/handlers/index.d.ts.map +1 -0
  29. package/dist/handlers/index.js +334 -2
  30. package/dist/handlers/policy-safe-knowledge-assistant.handlers.d.ts +124 -121
  31. package/dist/handlers/policy-safe-knowledge-assistant.handlers.d.ts.map +1 -1
  32. package/dist/handlers/policy-safe-knowledge-assistant.handlers.js +325 -254
  33. package/dist/index.d.ts +11 -8
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +918 -10
  36. package/dist/integration.test.d.ts +2 -0
  37. package/dist/integration.test.d.ts.map +1 -0
  38. package/dist/node/docs/index.js +38 -0
  39. package/dist/node/docs/policy-safe-knowledge-assistant.docblock.js +38 -0
  40. package/dist/node/example.js +37 -0
  41. package/dist/node/handlers/index.js +334 -0
  42. package/dist/node/handlers/policy-safe-knowledge-assistant.handlers.js +334 -0
  43. package/dist/node/index.js +917 -0
  44. package/dist/node/orchestrator/buildAnswer.js +73 -0
  45. package/dist/node/policy-safe-knowledge-assistant.feature.js +57 -0
  46. package/dist/node/seed/fixtures.js +35 -0
  47. package/dist/node/seed/index.js +35 -0
  48. package/dist/node/seeders/index.js +12 -0
  49. package/dist/node/ui/PolicySafeKnowledgeAssistantDashboard.js +420 -0
  50. package/dist/node/ui/hooks/usePolicySafeKnowledgeAssistant.js +154 -0
  51. package/dist/node/ui/index.js +420 -0
  52. package/dist/orchestrator/buildAnswer.d.ts +40 -42
  53. package/dist/orchestrator/buildAnswer.d.ts.map +1 -1
  54. package/dist/orchestrator/buildAnswer.js +72 -75
  55. package/dist/policy-safe-knowledge-assistant.feature.d.ts +1 -6
  56. package/dist/policy-safe-knowledge-assistant.feature.d.ts.map +1 -1
  57. package/dist/policy-safe-knowledge-assistant.feature.js +56 -148
  58. package/dist/seed/fixtures.d.ts +28 -31
  59. package/dist/seed/fixtures.d.ts.map +1 -1
  60. package/dist/seed/fixtures.js +35 -33
  61. package/dist/seed/index.d.ts +2 -2
  62. package/dist/seed/index.d.ts.map +1 -0
  63. package/dist/seed/index.js +36 -3
  64. package/dist/seeders/index.d.ts +4 -8
  65. package/dist/seeders/index.d.ts.map +1 -1
  66. package/dist/seeders/index.js +11 -14
  67. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.d.ts +1 -6
  68. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.d.ts.map +1 -1
  69. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js +415 -225
  70. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.d.ts +49 -51
  71. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.d.ts.map +1 -1
  72. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js +147 -185
  73. package/dist/ui/index.d.ts +2 -2
  74. package/dist/ui/index.d.ts.map +1 -0
  75. package/dist/ui/index.js +420 -2
  76. package/package.json +173 -44
  77. package/tsdown.config.js +1 -2
  78. package/.turbo/turbo-build$colon$bundle.log +0 -60
  79. package/dist/docs/policy-safe-knowledge-assistant.docblock.js.map +0 -1
  80. package/dist/example.js.map +0 -1
  81. package/dist/handlers/policy-safe-knowledge-assistant.handlers.js.map +0 -1
  82. package/dist/orchestrator/buildAnswer.js.map +0 -1
  83. package/dist/policy-safe-knowledge-assistant.feature.js.map +0 -1
  84. package/dist/seed/fixtures.js.map +0 -1
  85. package/dist/seeders/index.js.map +0 -1
  86. package/dist/ui/PolicySafeKnowledgeAssistantDashboard.js.map +0 -1
  87. package/dist/ui/hooks/usePolicySafeKnowledgeAssistant.js.map +0 -1
  88. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,917 @@
1
+ // src/docs/policy-safe-knowledge-assistant.docblock.ts
2
+ import { registerDocBlocks } from "@contractspec/lib.contracts/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
13
+ - Assistant answers are structured and must cite a KB snapshot (or refuse).
14
+ - Locale + jurisdiction are mandatory inputs for every assistant call.
15
+ - Automation proposes KB patches; humans verify; publishing stays blocked until approvals.
16
+ - Learning hub demonstrates drills + coaching + quests without spam.
17
+
18
+ ## Offline-first
19
+ - 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)
31
+ 1) Onboard: set locale + jurisdiction.
32
+ 2) Publish snapshot: ingest source -> propose rule -> approve -> publish.
33
+ 3) Ask assistant: must pass gate and cite snapshot.
34
+ 4) Simulate change: watcher -> review -> publish new snapshot.
35
+ 5) Learning hub: drills session, ambient tip, quest start + step completion.`
36
+ }
37
+ ];
38
+ registerDocBlocks(docBlocks);
39
+ // src/example.ts
40
+ import { defineExample } from "@contractspec/lib.contracts";
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";
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
+ });
460
+
461
+ // src/seed/fixtures.ts
462
+ var DEMO_FIXTURES = {
463
+ jurisdictions: ["EU", "FR"],
464
+ locales: ["en-GB", "fr-FR"],
465
+ demoOrgId: "org_demo",
466
+ demoUserId: "user_demo",
467
+ sources: {
468
+ EU_SOURCE_1: {
469
+ jurisdiction: "EU",
470
+ authority: "DemoAuthority",
471
+ title: "EU Demo Source v1",
472
+ fetchedAt: new Date("2026-01-01T00:00:00.000Z"),
473
+ hash: "hash_eu_v1",
474
+ fileId: "file_eu_v1"
475
+ },
476
+ EU_SOURCE_2: {
477
+ jurisdiction: "EU",
478
+ authority: "DemoAuthority",
479
+ title: "EU Demo Source v2",
480
+ fetchedAt: new Date("2026-02-01T00:00:00.000Z"),
481
+ hash: "hash_eu_v2",
482
+ fileId: "file_eu_v2"
483
+ }
484
+ },
485
+ rules: {
486
+ EU_RULE_TAX: {
487
+ id: "rule_eu_tax",
488
+ jurisdiction: "EU",
489
+ topicKey: "tax_reporting"
490
+ }
491
+ }
492
+ };
493
+ // src/ui/hooks/usePolicySafeKnowledgeAssistant.ts
494
+ import { useCallback, useEffect, useMemo, useState } from "react";
495
+ import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
496
+ "use client";
497
+ function isCitationLike(value) {
498
+ if (!value || typeof value !== "object")
499
+ return false;
500
+ const v = value;
501
+ return typeof v.kbSnapshotId === "string" && typeof v.sourceId === "string";
502
+ }
503
+ function toCitations(value) {
504
+ if (!Array.isArray(value))
505
+ return [];
506
+ return value.filter(isCitationLike).map((c) => ({
507
+ kbSnapshotId: c.kbSnapshotId,
508
+ sourceId: c.sourceId,
509
+ excerpt: c.excerpt
510
+ }));
511
+ }
512
+ function usePolicySafeKnowledgeAssistant() {
513
+ const { handlers, projectId } = useTemplateRuntime();
514
+ const api = handlers.policySafeKnowledgeAssistant;
515
+ const [state, setState] = useState({
516
+ context: null,
517
+ loading: true,
518
+ error: null,
519
+ lastAnswer: null,
520
+ lastRuleId: null,
521
+ lastRuleVersionId: null,
522
+ lastSnapshotId: null,
523
+ lastReviewTaskId: null
524
+ });
525
+ const refreshContext = useCallback(async () => {
526
+ try {
527
+ setState((s) => ({ ...s, loading: true, error: null }));
528
+ const ctx = await api.getUserContext({ projectId });
529
+ setState((s) => ({
530
+ ...s,
531
+ context: {
532
+ locale: ctx.locale,
533
+ jurisdiction: ctx.jurisdiction,
534
+ allowedScope: ctx.allowedScope,
535
+ kbSnapshotId: ctx.kbSnapshotId
536
+ },
537
+ loading: false
538
+ }));
539
+ } catch (e) {
540
+ setState((s) => ({
541
+ ...s,
542
+ loading: false,
543
+ error: e instanceof Error ? e : new Error("Unknown error")
544
+ }));
545
+ }
546
+ }, [api, projectId]);
547
+ useEffect(() => {
548
+ refreshContext();
549
+ }, [refreshContext]);
550
+ const setContext = useCallback(async (input) => {
551
+ const ctx = await api.setUserContext({ projectId, ...input });
552
+ setState((s) => ({
553
+ ...s,
554
+ context: {
555
+ locale: ctx.locale,
556
+ jurisdiction: ctx.jurisdiction,
557
+ allowedScope: ctx.allowedScope,
558
+ kbSnapshotId: ctx.kbSnapshotId
559
+ }
560
+ }));
561
+ }, [api, projectId]);
562
+ const askAssistant = useCallback(async (question) => {
563
+ const answerUnknown = await api.answer({ projectId, question });
564
+ const answer = answerUnknown;
565
+ setState((s) => ({
566
+ ...s,
567
+ lastAnswer: {
568
+ refused: answer.refused,
569
+ refusalReason: answer.refusalReason,
570
+ sections: answer.sections,
571
+ citations: toCitations(answerUnknown.citations)
572
+ }
573
+ }));
574
+ }, [api, projectId]);
575
+ const createDemoRule = useCallback(async () => {
576
+ const rule = await api.createRule({
577
+ projectId,
578
+ jurisdiction: state.context?.jurisdiction ?? "EU",
579
+ topicKey: "tax_reporting"
580
+ });
581
+ setState((s) => ({ ...s, lastRuleId: rule.id }));
582
+ return rule.id;
583
+ }, [api, projectId, state.context?.jurisdiction]);
584
+ const upsertRuleVersion = useCallback(async (input) => {
585
+ const rv = await api.upsertRuleVersion({
586
+ projectId,
587
+ ruleId: input.ruleId,
588
+ content: input.content,
589
+ sourceRefs: [{ sourceDocumentId: "src_demo", excerpt: "demo excerpt" }]
590
+ });
591
+ setState((s) => ({ ...s, lastRuleVersionId: rv.id }));
592
+ return rv.id;
593
+ }, [api, projectId]);
594
+ const approveRuleVersion = useCallback(async (ruleVersionId) => {
595
+ await api.approveRuleVersion({ ruleVersionId, approver: "demo_expert" });
596
+ }, [api]);
597
+ const publishSnapshot = useCallback(async () => {
598
+ const snap = await api.publishSnapshot({
599
+ projectId,
600
+ jurisdiction: state.context?.jurisdiction ?? "EU",
601
+ asOfDate: new Date("2026-02-01T00:00:00.000Z")
602
+ });
603
+ setState((s) => ({ ...s, lastSnapshotId: snap.id }));
604
+ await refreshContext();
605
+ return snap.id;
606
+ }, [api, projectId, refreshContext, state.context?.jurisdiction]);
607
+ const simulateHighRiskChangeAndApprove = useCallback(async (ruleVersionId) => {
608
+ const cand = await api.createChangeCandidate({
609
+ projectId,
610
+ jurisdiction: state.context?.jurisdiction ?? "EU",
611
+ diffSummary: "Simulated change (demo)",
612
+ riskLevel: "high",
613
+ proposedRuleVersionIds: [ruleVersionId]
614
+ });
615
+ const review = await api.createReviewTask({ changeCandidateId: cand.id });
616
+ setState((s) => ({ ...s, lastReviewTaskId: review.id }));
617
+ await api.submitDecision({
618
+ reviewTaskId: review.id,
619
+ decision: "approve",
620
+ decidedByRole: "expert",
621
+ decidedBy: "demo_expert"
622
+ });
623
+ await api.publishIfReady({
624
+ jurisdiction: state.context?.jurisdiction ?? "EU"
625
+ });
626
+ return review.id;
627
+ }, [api, projectId, state.context?.jurisdiction]);
628
+ const derived = useMemo(() => ({ projectId }), [projectId]);
629
+ return {
630
+ state,
631
+ derived,
632
+ actions: {
633
+ refreshContext,
634
+ setContext,
635
+ askAssistant,
636
+ createDemoRule,
637
+ upsertRuleVersion,
638
+ approveRuleVersion,
639
+ publishSnapshot,
640
+ simulateHighRiskChangeAndApprove
641
+ }
642
+ };
643
+ }
644
+
645
+ // src/ui/PolicySafeKnowledgeAssistantDashboard.tsx
646
+ import { useCallback as useCallback2, useMemo as useMemo2, useState as useState2 } from "react";
647
+ import {
648
+ Button,
649
+ ErrorState,
650
+ LoaderBlock,
651
+ StatCard,
652
+ StatCardGroup
653
+ } from "@contractspec/lib.design-system";
654
+ import { Card } from "@contractspec/lib.ui-kit-web/ui/card";
655
+ import { Input } from "@contractspec/lib.ui-kit-web/ui/input";
656
+ import { Textarea } from "@contractspec/lib.ui-kit-web/ui/textarea";
657
+ import {
658
+ Select,
659
+ SelectContent,
660
+ SelectItem,
661
+ SelectTrigger,
662
+ SelectValue
663
+ } from "@contractspec/lib.ui-kit-web/ui/select";
664
+ import { jsxDEV } from "react/jsx-dev-runtime";
665
+ "use client";
666
+ function PolicySafeKnowledgeAssistantDashboard() {
667
+ const { state, actions } = usePolicySafeKnowledgeAssistant();
668
+ const [question, setQuestion] = useState2("reporting obligations");
669
+ const [content, setContent] = useState2("EU: Reporting obligations v2 (updated)");
670
+ const [locale, setLocale] = useState2("en-GB");
671
+ const [jurisdiction, setJurisdiction] = useState2("EU");
672
+ const [allowedScope, setAllowedScope] = useState2("education_only");
673
+ const snapshotId = state.context?.kbSnapshotId ?? state.lastSnapshotId ?? null;
674
+ const stats = useMemo2(() => {
675
+ return [
676
+ { label: "Locale", value: state.context?.locale ?? "—" },
677
+ { label: "Jurisdiction", value: state.context?.jurisdiction ?? "—" },
678
+ { label: "Scope", value: state.context?.allowedScope ?? "—" },
679
+ { label: "KB Snapshot", value: snapshotId ?? "—" }
680
+ ];
681
+ }, [
682
+ snapshotId,
683
+ state.context?.allowedScope,
684
+ state.context?.jurisdiction,
685
+ state.context?.locale
686
+ ]);
687
+ const handleSetContext = useCallback2(async () => {
688
+ await actions.setContext({ locale, jurisdiction, allowedScope });
689
+ }, [actions, allowedScope, jurisdiction, locale]);
690
+ const handleAsk = useCallback2(async () => {
691
+ await actions.askAssistant(question);
692
+ }, [actions, question]);
693
+ const handleAdminPublishFlow = useCallback2(async () => {
694
+ const ruleId = state.lastRuleId ?? await actions.createDemoRule();
695
+ const rvId = await actions.upsertRuleVersion({ ruleId, content });
696
+ await actions.approveRuleVersion(rvId);
697
+ await actions.simulateHighRiskChangeAndApprove(rvId);
698
+ await actions.publishSnapshot();
699
+ }, [actions, content, state.lastRuleId]);
700
+ if (state.loading && !state.context) {
701
+ return /* @__PURE__ */ jsxDEV(LoaderBlock, {
702
+ label: "Loading demo..."
703
+ }, undefined, false, undefined, this);
704
+ }
705
+ if (state.error) {
706
+ return /* @__PURE__ */ jsxDEV(ErrorState, {
707
+ title: "Failed to load demo",
708
+ description: state.error.message,
709
+ onRetry: actions.refreshContext,
710
+ retryLabel: "Retry"
711
+ }, undefined, false, undefined, this);
712
+ }
713
+ return /* @__PURE__ */ jsxDEV("div", {
714
+ className: "space-y-6",
715
+ children: [
716
+ /* @__PURE__ */ jsxDEV(StatCardGroup, {
717
+ children: stats.map((s) => /* @__PURE__ */ jsxDEV(StatCard, {
718
+ label: s.label,
719
+ value: String(s.value)
720
+ }, s.label, false, undefined, this))
721
+ }, undefined, false, undefined, this),
722
+ /* @__PURE__ */ jsxDEV(Card, {
723
+ className: "p-4",
724
+ children: [
725
+ /* @__PURE__ */ jsxDEV("h3", {
726
+ className: "text-lg font-semibold",
727
+ children: "1) Onboarding (explicit locale + jurisdiction)"
728
+ }, undefined, false, undefined, this),
729
+ /* @__PURE__ */ jsxDEV("div", {
730
+ className: "mt-3 grid gap-3 md:grid-cols-3",
731
+ children: [
732
+ /* @__PURE__ */ jsxDEV("div", {
733
+ children: [
734
+ /* @__PURE__ */ jsxDEV("div", {
735
+ className: "text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase",
736
+ children: "Locale"
737
+ }, undefined, false, undefined, this),
738
+ /* @__PURE__ */ jsxDEV(Input, {
739
+ value: locale,
740
+ onChange: (e) => setLocale(e.target.value)
741
+ }, undefined, false, undefined, this)
742
+ ]
743
+ }, undefined, true, undefined, this),
744
+ /* @__PURE__ */ jsxDEV("div", {
745
+ children: [
746
+ /* @__PURE__ */ jsxDEV("div", {
747
+ className: "text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase",
748
+ children: "Jurisdiction"
749
+ }, undefined, false, undefined, this),
750
+ /* @__PURE__ */ jsxDEV(Input, {
751
+ value: jurisdiction,
752
+ onChange: (e) => setJurisdiction(e.target.value)
753
+ }, undefined, false, undefined, this)
754
+ ]
755
+ }, undefined, true, undefined, this),
756
+ /* @__PURE__ */ jsxDEV("div", {
757
+ children: [
758
+ /* @__PURE__ */ jsxDEV("div", {
759
+ className: "text-muted-foreground mb-1 text-xs font-semibold tracking-wide uppercase",
760
+ children: "Allowed scope"
761
+ }, undefined, false, undefined, this),
762
+ /* @__PURE__ */ jsxDEV(Select, {
763
+ value: allowedScope,
764
+ onValueChange: (v) => setAllowedScope(v),
765
+ children: [
766
+ /* @__PURE__ */ jsxDEV(SelectTrigger, {
767
+ children: /* @__PURE__ */ jsxDEV(SelectValue, {
768
+ placeholder: "Select scope"
769
+ }, undefined, false, undefined, this)
770
+ }, undefined, false, undefined, this),
771
+ /* @__PURE__ */ jsxDEV(SelectContent, {
772
+ children: [
773
+ /* @__PURE__ */ jsxDEV(SelectItem, {
774
+ value: "education_only",
775
+ children: "education_only"
776
+ }, undefined, false, undefined, this),
777
+ /* @__PURE__ */ jsxDEV(SelectItem, {
778
+ value: "generic_info",
779
+ children: "generic_info"
780
+ }, undefined, false, undefined, this),
781
+ /* @__PURE__ */ jsxDEV(SelectItem, {
782
+ value: "escalation_required",
783
+ children: "escalation_required"
784
+ }, undefined, false, undefined, this)
785
+ ]
786
+ }, undefined, true, undefined, this)
787
+ ]
788
+ }, undefined, true, undefined, this)
789
+ ]
790
+ }, undefined, true, undefined, this)
791
+ ]
792
+ }, undefined, true, undefined, this),
793
+ /* @__PURE__ */ jsxDEV("div", {
794
+ className: "mt-4 flex gap-2",
795
+ children: [
796
+ /* @__PURE__ */ jsxDEV(Button, {
797
+ onPress: handleSetContext,
798
+ children: "Save context"
799
+ }, undefined, false, undefined, this),
800
+ /* @__PURE__ */ jsxDEV(Button, {
801
+ variant: "outline",
802
+ onPress: actions.refreshContext,
803
+ children: "Refresh"
804
+ }, undefined, false, undefined, this)
805
+ ]
806
+ }, undefined, true, undefined, this)
807
+ ]
808
+ }, undefined, true, undefined, this),
809
+ /* @__PURE__ */ jsxDEV(Card, {
810
+ className: "p-4",
811
+ children: [
812
+ /* @__PURE__ */ jsxDEV("h3", {
813
+ className: "text-lg font-semibold",
814
+ children: "2) Ask the assistant (must cite KB snapshot)"
815
+ }, undefined, false, undefined, this),
816
+ /* @__PURE__ */ jsxDEV("div", {
817
+ className: "mt-3 flex flex-col gap-3",
818
+ children: [
819
+ /* @__PURE__ */ jsxDEV(Input, {
820
+ value: question,
821
+ onChange: (e) => setQuestion(e.target.value)
822
+ }, undefined, false, undefined, this),
823
+ /* @__PURE__ */ jsxDEV("div", {
824
+ className: "flex gap-2",
825
+ children: /* @__PURE__ */ jsxDEV(Button, {
826
+ onPress: handleAsk,
827
+ children: "Ask"
828
+ }, undefined, false, undefined, this)
829
+ }, undefined, false, undefined, this)
830
+ ]
831
+ }, undefined, true, undefined, this),
832
+ state.lastAnswer ? /* @__PURE__ */ jsxDEV("div", {
833
+ className: "mt-4 space-y-3",
834
+ children: [
835
+ state.lastAnswer.refused ? /* @__PURE__ */ jsxDEV("div", {
836
+ className: "text-sm text-red-600",
837
+ children: [
838
+ "Refused: ",
839
+ state.lastAnswer.refusalReason ?? "UNKNOWN"
840
+ ]
841
+ }, undefined, true, undefined, this) : null,
842
+ state.lastAnswer.sections.map((s, idx) => /* @__PURE__ */ jsxDEV("div", {
843
+ children: [
844
+ /* @__PURE__ */ jsxDEV("div", {
845
+ className: "text-sm font-semibold",
846
+ children: s.heading
847
+ }, undefined, false, undefined, this),
848
+ /* @__PURE__ */ jsxDEV("div", {
849
+ className: "text-muted-foreground text-sm",
850
+ children: s.body
851
+ }, undefined, false, undefined, this)
852
+ ]
853
+ }, `${s.heading}-${idx}`, true, undefined, this)),
854
+ /* @__PURE__ */ jsxDEV("div", {
855
+ className: "text-sm font-semibold",
856
+ children: "Citations"
857
+ }, undefined, false, undefined, this),
858
+ /* @__PURE__ */ jsxDEV("ul", {
859
+ className: "text-muted-foreground list-disc pl-5 text-sm",
860
+ children: state.lastAnswer.citations.map((c) => /* @__PURE__ */ jsxDEV("li", {
861
+ children: [
862
+ c.kbSnapshotId,
863
+ " — ",
864
+ c.sourceId
865
+ ]
866
+ }, `${c.kbSnapshotId}-${c.sourceId}`, true, undefined, this))
867
+ }, undefined, false, undefined, this)
868
+ ]
869
+ }, undefined, true, undefined, this) : null
870
+ ]
871
+ }, undefined, true, undefined, this),
872
+ /* @__PURE__ */ jsxDEV(Card, {
873
+ className: "p-4",
874
+ children: [
875
+ /* @__PURE__ */ jsxDEV("h3", {
876
+ className: "text-lg font-semibold",
877
+ children: "3) Admin: publish a new snapshot (HITL)"
878
+ }, undefined, false, undefined, this),
879
+ /* @__PURE__ */ jsxDEV("div", {
880
+ className: "mt-3 space-y-3",
881
+ children: [
882
+ /* @__PURE__ */ jsxDEV(Textarea, {
883
+ value: content,
884
+ onChange: (e) => setContent(e.target.value)
885
+ }, undefined, false, undefined, this),
886
+ /* @__PURE__ */ jsxDEV(Button, {
887
+ onPress: handleAdminPublishFlow,
888
+ children: "Simulate change → review → approve → publish snapshot"
889
+ }, undefined, false, undefined, this)
890
+ ]
891
+ }, undefined, true, undefined, this)
892
+ ]
893
+ }, undefined, true, undefined, this),
894
+ /* @__PURE__ */ jsxDEV(Card, {
895
+ className: "p-4",
896
+ children: [
897
+ /* @__PURE__ */ jsxDEV("h3", {
898
+ className: "text-lg font-semibold",
899
+ children: "4) Learning hub (patterns)"
900
+ }, undefined, false, undefined, this),
901
+ /* @__PURE__ */ jsxDEV("p", {
902
+ className: "text-muted-foreground mt-2 text-sm",
903
+ 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."
904
+ }, undefined, false, undefined, this)
905
+ ]
906
+ }, undefined, true, undefined, this)
907
+ ]
908
+ }, undefined, true, undefined, this);
909
+ }
910
+ export {
911
+ example_default as example,
912
+ createPolicySafeKnowledgeAssistantHandlers,
913
+ buildPolicySafeAnswer,
914
+ PolicySafeKnowledgeAssistantFeature,
915
+ PolicySafeKnowledgeAssistantDashboard,
916
+ DEMO_FIXTURES
917
+ };