@hippo-digital/hippocampus 2.9.0 → 2.10.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.
package/lib/trace.js ADDED
@@ -0,0 +1,571 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const crypto = require('crypto')
4
+ const { spawnSync } = require('child_process')
5
+ const { COLLECTION_FILES } = require('./collections')
6
+ const { META_FILENAME } = require('./schema-version')
7
+
8
+ // The trace export: the chain as it stood on one day, in a form that can be
9
+ // committed and attached to a safety case.
10
+ //
11
+ // A trace only counts if it shows who did each step, and if it can be handed
12
+ // over as it stood on a given day. The viewer answers "what is this connected
13
+ // to?" for one record at a time; this answers it for every requirement and
14
+ // every component at once, lists every break in the chain, and records exactly
15
+ // which source files it was made from.
16
+ //
17
+ // Rows: one per requirement (need, decision, screen, component, evaluation),
18
+ // one per component (what changed it), and one per hazard (its causes, the
19
+ // controls against it, what builds each control and the finding that verified
20
+ // it). The hazard log export writes the hazards again in the log's own layout.
21
+
22
+ const list = (value) => (Array.isArray(value) ? value : [])
23
+
24
+ function linksOf (knowledge, type) {
25
+ return list(knowledge.relationships).filter((rel) => rel.type === type)
26
+ }
27
+
28
+ function who (record) {
29
+ return {
30
+ draftedBy: record.draftedBy || null,
31
+ reviewedBy: record.reviewedBy || null,
32
+ reviewedOn: record.reviewedOn || null,
33
+ signedOffBy: record.signedOffBy || null,
34
+ signedOffOn: record.signedOffOn || null
35
+ }
36
+ }
37
+
38
+ function label (knowledge, id) {
39
+ const entity = knowledge.index && knowledge.index.entities[id]
40
+ return entity ? entity.label : id
41
+ }
42
+
43
+ /**
44
+ * One row per requirement and one per component, plus every gap found.
45
+ * Reads a knowledge base as getKnowledge() returns it (with its index).
46
+ */
47
+ function buildTrace (knowledge) {
48
+ const index = knowledge.index
49
+ const derives = linksOf(knowledge, 'derives-from')
50
+ const basedOn = linksOf(knowledge, 'based-on-insight')
51
+ const weighed = linksOf(knowledge, 'weighed-against')
52
+ const verified = linksOf(knowledge, 'verified-by')
53
+ const realised = linksOf(knowledge, 'realised-in')
54
+
55
+ const requirementRows = list(knowledge.requirements).map((requirement) => {
56
+ const needIds = [...new Set([
57
+ ...list(requirement.needIds),
58
+ ...derives.filter((rel) => rel.from === requirement.id).map((rel) => rel.to)
59
+ ])]
60
+ const insightIds = [...new Set([
61
+ ...list(requirement.insightIds),
62
+ ...basedOn.filter((rel) => rel.from === requirement.id).map((rel) => rel.to)
63
+ ])]
64
+ const decisions = weighed.filter((rel) => rel.to === requirement.id).map((rel) => {
65
+ const decision = index.decisions[rel.from] || {}
66
+ return {
67
+ id: rel.from,
68
+ title: decision.title || rel.from,
69
+ status: decision.status || null,
70
+ outcome: rel.outcome || null,
71
+ decidedBy: decision.decidedBy || null,
72
+ decidedOn: decision.decidedOn || null
73
+ }
74
+ })
75
+ const screens = list(knowledge.screens)
76
+ .filter((screen) => list(screen.needIds).some((id) => needIds.includes(id)))
77
+ .map((screen) => ({ id: screen.id, title: screen.title, route: screen.route }))
78
+ const reasonIds = new Set([requirement.id, ...decisions.map((d) => d.id)])
79
+ const components = realised.filter((rel) => reasonIds.has(rel.from)).map((rel) => ({
80
+ id: rel.to,
81
+ title: label(knowledge, rel.to),
82
+ via: rel.from,
83
+ commit: rel.commit || null,
84
+ pr: rel.pr || null
85
+ }))
86
+ const evaluations = verified.filter((rel) => rel.from === requirement.id).map((rel) => {
87
+ const insight = index.insights[rel.to] || {}
88
+ return {
89
+ id: rel.to,
90
+ title: insight.title || rel.to,
91
+ outcome: rel.outcome || null,
92
+ rating: insight.rating || null,
93
+ signedOffBy: insight.signedOffBy || null,
94
+ signedOffOn: insight.signedOffOn || null
95
+ }
96
+ })
97
+ return {
98
+ id: requirement.id,
99
+ statement: requirement.statement,
100
+ kind: requirement.kind || null,
101
+ status: requirement.status || null,
102
+ needs: needIds.map((id) => ({ id, title: label(knowledge, id) })),
103
+ insights: insightIds.map((id) => ({ id, title: label(knowledge, id) })),
104
+ decisions,
105
+ screens,
106
+ components,
107
+ evaluations,
108
+ purposes: linksOf(knowledge, 'bounded-by').filter((rel) => rel.from === requirement.id).map((rel) => ({ id: rel.to, title: label(knowledge, rel.to) })),
109
+ outsideReferences: list(requirement.outsideReferences),
110
+ ...who(requirement)
111
+ }
112
+ })
113
+
114
+ const componentRows = list(knowledge.components).map((component) => ({
115
+ id: component.id,
116
+ title: component.title,
117
+ prototypePath: component.prototypePath,
118
+ guide: component.guide || null,
119
+ productionPath: component.productionPath || null,
120
+ portedFromCommit: component.portedFromCommit || null,
121
+ reasons: realised.filter((rel) => rel.to === component.id).map((rel) => {
122
+ const entity = index.entities[rel.from]
123
+ return {
124
+ id: rel.from,
125
+ type: entity ? entity.type : null,
126
+ title: entity ? entity.label : rel.from,
127
+ commit: rel.commit || null,
128
+ pr: rel.pr || null,
129
+ note: rel.note || null
130
+ }
131
+ }),
132
+ ...who(component)
133
+ }))
134
+
135
+ const mitigates = linksOf(knowledge, 'mitigates')
136
+ const implemented = linksOf(knowledge, 'implemented-by')
137
+ const identified = linksOf(knowledge, 'identified-from')
138
+ const hazardRows = list(knowledge.hazards).map((hazard) => ({
139
+ id: hazard.id,
140
+ title: hazard.title,
141
+ logNumber: hazard.logNumber || null,
142
+ dateAdded: hazard.dateAdded || null,
143
+ effect: hazard.effect || null,
144
+ hazard: hazard.hazard,
145
+ harm: hazard.harm,
146
+ status: hazard.status,
147
+ owner: hazard.owner || null,
148
+ causes: list(hazard.causes),
149
+ initialRisk: hazard.initialRisk || null,
150
+ residualRisk: hazard.residualRisk || null,
151
+ assessedBy: hazard.assessedBy || null,
152
+ assessedOn: hazard.assessedOn || null,
153
+ identifiedFrom: identified.filter((rel) => rel.from === hazard.id).map((rel) => ({ id: rel.to, title: label(knowledge, rel.to), cause: rel.cause ?? null })),
154
+ controls: mitigates.filter((rel) => rel.to === hazard.id).map((rel) => {
155
+ const control = index.controls[rel.from] || {}
156
+ return {
157
+ id: rel.from,
158
+ title: control.statement || rel.from,
159
+ kind: control.kind || null,
160
+ stage: control.stage || null,
161
+ status: control.status || null,
162
+ cause: rel.cause ?? null,
163
+ builtBy: implemented.filter((link) => link.from === rel.from).map((link) => ({ id: link.to, title: label(knowledge, link.to) })),
164
+ verifiedBy: verified.filter((link) => link.from === rel.from).map((link) => ({ id: link.to, title: label(knowledge, link.to), outcome: link.outcome || null })),
165
+ outsideReferences: list(control.outsideReferences)
166
+ }
167
+ }),
168
+ outsideReferences: list(hazard.outsideReferences),
169
+ reference: hazard.reference || null,
170
+ ...who(hazard)
171
+ }))
172
+
173
+ return {
174
+ requirements: requirementRows,
175
+ components: componentRows,
176
+ hazards: hazardRows,
177
+ gaps: findGaps(knowledge, requirementRows, componentRows, hazardRows)
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Every break in the chain. Each is a fact about the knowledge base, not a
183
+ * failure: a requirement written this week has not been evaluated yet. The
184
+ * list is what someone signing a release reads, so each line says what is
185
+ * missing in words, with the record it is missing from.
186
+ */
187
+ function findGaps (knowledge, requirementRows, componentRows, hazardRows = []) {
188
+ const gaps = []
189
+ const add = (kind, id, message) => gaps.push({ kind, id, message })
190
+ const links = list(knowledge.relationships)
191
+ const accepted = list(knowledge.decisions).filter((decision) => decision.status === 'accepted')
192
+
193
+ // The intended purpose. A project that has started on purpose or hazards,
194
+ // or has asked for the stricter checks, is expected to have an agreed one;
195
+ // before then a missing purpose is not a gap anyone is working on.
196
+ const purposes = list(knowledge.intendedPurposes)
197
+ const agreedPurpose = purposes.find((purpose) => purpose.status === 'agreed')
198
+ const strict = Boolean(knowledge.project && knowledge.project.strictTraceability)
199
+ if (!agreedPurpose && (strict || purposes.length || list(knowledge.hazards).length)) {
200
+ add('no-agreed-purpose', (purposes[0] && purposes[0].id) || (knowledge.project && knowledge.project.id) || 'project', 'There is no agreed intended purpose')
201
+ }
202
+ if (agreedPurpose) {
203
+ const assessed = new Set(links.filter((rel) => rel.type === 'assessed-against-purpose').map((rel) => rel.from))
204
+ for (const decision of accepted) {
205
+ if (!assessed.has(decision.id)) add('decision-not-assessed-against-purpose', decision.id, 'Accepted decision has not been assessed against the intended purpose')
206
+ }
207
+ }
208
+
209
+ for (const row of requirementRows) {
210
+ if (row.status === 'retired') continue
211
+ // Organisational and market requirements come from the organisation, not
212
+ // from a user need, and are met by the service rather than one screen.
213
+ const userRequirement = String(row.kind || '').startsWith('user-')
214
+ if (userRequirement && !row.needs.length) add('requirement-without-need', row.id, 'Requirement traces back to no user need')
215
+ // As `validate` counts it: a user requirement is the one a usability
216
+ // evaluation can check. An organisational rule is checked by its owner.
217
+ if (userRequirement && !row.evaluations.length) add('requirement-not-evaluated', row.id, 'Requirement has no evaluation (verified-by)')
218
+ for (const evaluation of row.evaluations) {
219
+ if (evaluation.outcome === 'fails' || evaluation.outcome === 'partly') {
220
+ add('requirement-not-met', row.id, `Evaluation ${evaluation.id} found it ${evaluation.outcome === 'fails' ? 'not met' : 'partly met'}`)
221
+ }
222
+ }
223
+ if (userRequirement && !row.screens.length) add('requirement-without-screen', row.id, 'No screen addresses the needs this requirement comes from')
224
+ }
225
+
226
+ for (const decision of list(knowledge.decisions)) {
227
+ if (decision.status === 'accepted' && !decision.decidedBy) add('decision-without-decider', decision.id, 'Accepted decision does not say who decided')
228
+ if (decision.status === 'accepted' && !decision.decidedOn) add('decision-without-date', decision.id, 'Accepted decision does not say when')
229
+ }
230
+
231
+ const hazardFindings = new Set(links.filter((rel) => rel.type === 'identified-from').map((rel) => rel.to))
232
+ for (const insight of list(knowledge.insights)) {
233
+ const severe = insight.rating === 'catastrophic' || insight.rating === 'critical'
234
+ if (severe && !insight.signedOffBy) {
235
+ add('rating-not-signed-off', insight.id, `Finding rated ${insight.rating} has not been signed off`)
236
+ }
237
+ if ((severe || insight.qualityDimension === 'harm') && !hazardFindings.has(insight.id)) {
238
+ add('finding-without-hazard', insight.id, severe ? `Finding rated ${insight.rating} is linked to no hazard` : 'Finding about harm is linked to no hazard')
239
+ }
240
+ }
241
+
242
+ const verifiedFrom = new Set(links.filter((rel) => rel.type === 'verified-by').map((rel) => rel.from))
243
+ for (const requirement of list(knowledge.requirements)) {
244
+ const aboutHarm = requirement.qualityDimension === 'harm' || (requirement.measure && requirement.measure.dimension === 'harm')
245
+ if (aboutHarm && requirement.status !== 'retired' && !verifiedFrom.has(requirement.id)) {
246
+ add('harm-requirement-not-evaluated', requirement.id, 'Requirement about harm has never been evaluated')
247
+ }
248
+ }
249
+
250
+ const assumptions = Object.fromEntries(list(knowledge.assumptions).map((a) => [a.id, a]))
251
+ const evidence = Object.fromEntries(list(knowledge.evidence).map((e) => [e.id, e]))
252
+ for (const decision of accepted) {
253
+ for (const rel of links.filter((link) => link.from === decision.id)) {
254
+ if (rel.type === 'rests-on' && assumptions[rel.to] && assumptions[rel.to].risk === 'high') {
255
+ add('decision-rests-on-high-risk-assumption', decision.id, `Accepted decision rests on high-risk assumption ${rel.to}`)
256
+ }
257
+ // A challenge is not a citation: evidence that calls the decision into
258
+ // question is exactly what should stay linked, confirmed or not.
259
+ if (rel.type !== 'challenged-by' && evidence[rel.to] && !evidence[rel.to].sourceConfirmedBy) {
260
+ add('decision-cites-unconfirmed-evidence', decision.id, `Accepted decision cites evidence ${rel.to}, whose source has not confirmed the write-up`)
261
+ }
262
+ }
263
+ }
264
+
265
+ for (const row of hazardRows) {
266
+ if (!row.causes.length) add('hazard-without-cause', row.id, 'Hazard lists no cause')
267
+ if (!row.controls.length && row.status !== 'transferred') add('hazard-without-control', row.id, 'No control mitigates this hazard')
268
+ if (!row.initialRisk) add('hazard-without-initial-risk', row.id, row.status === 'proposed' ? 'Proposed hazard: nobody has rated its risk yet' : 'Hazard has no initial risk')
269
+ if ((row.initialRisk || row.residualRisk) && !row.assessedBy) add('risk-without-assessor', row.id, 'Risk is rated, but nobody is named as the assessor')
270
+ }
271
+
272
+ for (const control of list(knowledge.controls)) {
273
+ const built = links.some((rel) => rel.type === 'implemented-by' && rel.from === control.id)
274
+ // Training and business-process controls are often delivered outside the
275
+ // service; a reference to where is enough to say something builds them.
276
+ if (!built && (control.kind === 'hit-design' || !list(control.outsideReferences).length)) {
277
+ add('control-not-built', control.id, 'Nothing builds this control (implemented-by)')
278
+ }
279
+ if (!verifiedFrom.has(control.id)) add('control-not-verified', control.id, 'No finding has verified this control (verified-by)')
280
+ }
281
+
282
+ for (const row of componentRows) {
283
+ if (!row.reasons.length) add('component-without-reason', row.id, 'No realised-in link says why this component is as it is')
284
+ }
285
+
286
+ for (const collection of Object.keys(COLLECTION_FILES)) {
287
+ if (collection === 'project' || collection === 'projectContext') continue
288
+ for (const record of list(knowledge[collection])) {
289
+ if (record.draftedBy && !record.reviewedBy) add('drafted-not-reviewed', record.id, `Drafted by ${record.draftedBy}; nobody has reviewed it`)
290
+ }
291
+ }
292
+
293
+ return gaps
294
+ }
295
+
296
+ /**
297
+ * What the table was made from: when, by which package, at which commit, and
298
+ * a fingerprint of every source file. Matching the fingerprints later is what
299
+ * shows the table still describes the knowledge base - or exactly which files
300
+ * have changed since.
301
+ */
302
+ function buildBaseline ({ knowledgeSourceDir, root, packageVersion, release, now = new Date() }) {
303
+ const names = [...Object.values(COLLECTION_FILES), META_FILENAME]
304
+ const files = names
305
+ .filter((name) => fs.existsSync(path.join(knowledgeSourceDir, name)))
306
+ .sort()
307
+ .map((name) => {
308
+ const bytes = fs.readFileSync(path.join(knowledgeSourceDir, name))
309
+ return {
310
+ path: path.relative(root, path.join(knowledgeSourceDir, name)).split(path.sep).join('/'),
311
+ sha256: crypto.createHash('sha256').update(bytes).digest('hex'),
312
+ bytes: bytes.length
313
+ }
314
+ })
315
+ return {
316
+ release: release || null,
317
+ generatedAt: now.toISOString(),
318
+ packageVersion,
319
+ git: gitState(root, knowledgeSourceDir),
320
+ files
321
+ }
322
+ }
323
+
324
+ function gitState (root, knowledgeSourceDir) {
325
+ const run = (args) => {
326
+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' })
327
+ return result.status === 0 ? result.stdout.trim() : null
328
+ }
329
+ const commit = run(['rev-parse', 'HEAD'])
330
+ if (!commit) return { commit: null, note: 'Not a git repository, or git is not installed' }
331
+ const changed = run(['status', '--porcelain', '--', path.relative(root, knowledgeSourceDir) || '.'])
332
+ return {
333
+ commit,
334
+ branch: run(['rev-parse', '--abbrev-ref', 'HEAD']),
335
+ // Uncommitted changes to the knowledge base mean the commit alone does not
336
+ // describe what the table was made from. The fingerprints still do.
337
+ sourceUncommitted: Boolean(changed)
338
+ }
339
+ }
340
+
341
+ /** Files whose fingerprint no longer matches, and files added or removed since. */
342
+ function compareBaseline (baseline, { knowledgeSourceDir, root }) {
343
+ const current = buildBaseline({ knowledgeSourceDir, root, packageVersion: null })
344
+ const before = new Map(baseline.files.map((file) => [file.path, file.sha256]))
345
+ const now = new Map(current.files.map((file) => [file.path, file.sha256]))
346
+ const changed = [...before.keys()].filter((file) => now.has(file) && now.get(file) !== before.get(file))
347
+ const removed = [...before.keys()].filter((file) => !now.has(file))
348
+ const added = [...now.keys()].filter((file) => !before.has(file))
349
+ return { changed, removed, added, matches: !changed.length && !removed.length && !added.length }
350
+ }
351
+
352
+ // --- writing ---------------------------------------------------------------
353
+
354
+ // A cell that starts with = + - @ is a formula to a spreadsheet. Text from a
355
+ // knowledge base is never meant as one, so it is quoted out.
356
+ function csvCell (value) {
357
+ let text = Array.isArray(value) ? value.join('; ') : (value == null ? '' : String(value))
358
+ if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`
359
+ return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
360
+ }
361
+
362
+ function toCsv (header, rows) {
363
+ return [header, ...rows].map((row) => row.map(csvCell).join(',')).join('\r\n') + '\r\n'
364
+ }
365
+
366
+ const ids = (items) => items.map((item) => item.id)
367
+ const withOutcome = (items) => items.map((item) => (item.outcome ? `${item.id} (${item.outcome})` : item.id))
368
+
369
+ function requirementsCsv (trace) {
370
+ return toCsv(
371
+ ['Requirement', 'Statement', 'Kind', 'Status', 'Needs', 'Based on findings', 'Decisions (outcome)', 'Decided by', 'Screens', 'Components', 'Evaluations (outcome)', 'Intended purpose', 'Outside references', 'Drafted by', 'Reviewed by', 'Reviewed on', 'Signed off by', 'Signed off on'],
372
+ trace.requirements.map((row) => [
373
+ row.id, row.statement, row.kind, row.status,
374
+ ids(row.needs), ids(row.insights), withOutcome(row.decisions),
375
+ [...new Set(row.decisions.map((d) => d.decidedBy).filter(Boolean))],
376
+ ids(row.screens), ids(row.components), withOutcome(row.evaluations),
377
+ ids(row.purposes), row.outsideReferences.map((r) => `${r.system} ${r.id}`),
378
+ row.draftedBy, row.reviewedBy, row.reviewedOn, row.signedOffBy, row.signedOffOn
379
+ ])
380
+ )
381
+ }
382
+
383
+ function componentsCsv (trace) {
384
+ return toCsv(
385
+ ['Component', 'Title', 'Prototype file', 'Usage guide', 'Production file', 'Ported from commit', 'Changed because of', 'Commits', 'Pull requests', 'Drafted by', 'Reviewed by', 'Reviewed on'],
386
+ trace.components.map((row) => [
387
+ row.id, row.title, row.prototypePath, row.guide, row.productionPath, row.portedFromCommit,
388
+ row.reasons.map((r) => r.id), row.reasons.map((r) => r.commit).filter(Boolean), row.reasons.map((r) => r.pr).filter(Boolean),
389
+ row.draftedBy, row.reviewedBy, row.reviewedOn
390
+ ])
391
+ )
392
+ }
393
+
394
+ const riskText = (risk) => (risk ? `${risk.risk} (${risk.severity}, ${risk.likelihood})` : '')
395
+
396
+ function hazardsCsv (trace) {
397
+ return toCsv(
398
+ ['Hazard', 'Title', 'Log number', 'Status', 'Initial risk', 'Residual risk', 'Assessed by', 'Assessed on', 'Causes', 'Controls', 'Built by', 'Verified by (outcome)', 'Identified from', 'Outside references', 'Reference'],
399
+ trace.hazards.map((row) => [
400
+ row.id, row.title, row.logNumber, row.status, riskText(row.initialRisk), riskText(row.residualRisk), row.assessedBy, row.assessedOn,
401
+ row.causes.map((c) => `${c.number}. ${c.statement}`),
402
+ row.controls.map((c) => `${c.id}${c.cause != null ? ` (cause ${c.cause})` : ''}`),
403
+ [...new Set(row.controls.flatMap((c) => c.builtBy.map((b) => b.id)))],
404
+ row.controls.flatMap((c) => c.verifiedBy.map((v) => (v.outcome ? `${v.id} (${v.outcome})` : v.id))),
405
+ row.identifiedFrom.map((i) => i.id),
406
+ row.outsideReferences.map((r) => `${r.system} ${r.id}`),
407
+ row.reference
408
+ ])
409
+ )
410
+ }
411
+
412
+ // The hazards in the layout a clinical safety officer's hazard log uses (the
413
+ // NHS DCB0129 template): one row per hazard, causes numbered, controls split
414
+ // into existing and additional and named by kind, the risk before and after.
415
+ // It is how proposals found in design work reach the log, which stays the
416
+ // master: every row says whether it is already in the log or proposed.
417
+ const CONTROL_KIND = { 'hit-design': 'HIT design', 'user-training': 'User training', 'business-process': 'Business process' }
418
+
419
+ function hazardLogCsv (trace) {
420
+ const controlsAt = (row, stage) => row.controls
421
+ .filter((c) => c.stage === stage)
422
+ .map((c) => `${CONTROL_KIND[c.kind] || c.kind}: ${c.title}${c.cause != null ? ` (cause ${c.cause})` : ''}${c.status === 'proposed' ? ' [proposed]' : ''}`)
423
+ return toCsv(
424
+ ['No.', 'Date Added', 'Effect', 'Hazard', 'Harm', 'Possible Causes', 'Existing Controls',
425
+ 'Initial Severity', 'Initial Likelihood', 'Initial Risk', 'Initial Justification',
426
+ 'Additional Controls', 'Residual Severity', 'Residual Likelihood', 'Residual Risk', 'Residual Justification',
427
+ 'Owner', 'Status', 'In the log', 'Knowledge base id'],
428
+ trace.hazards.map((row) => {
429
+ const initial = row.initialRisk || {}
430
+ const residual = row.residualRisk || {}
431
+ return [
432
+ row.logNumber, row.dateAdded, row.effect, row.hazard, row.harm,
433
+ row.causes.map((c) => `${c.number}. ${c.statement}`).join('\n'),
434
+ controlsAt(row, 'existing').join('\n'),
435
+ initial.severity, initial.likelihood, initial.risk, initial.justification,
436
+ controlsAt(row, 'additional').join('\n'),
437
+ residual.severity, residual.likelihood, residual.risk, residual.justification,
438
+ row.owner, row.status,
439
+ row.logNumber != null && row.status !== 'proposed' ? 'Yes' : 'No - proposed',
440
+ row.id
441
+ ]
442
+ })
443
+ )
444
+ }
445
+
446
+ function gapsCsv (trace) {
447
+ return toCsv(['Gap', 'Record', 'What is missing'], trace.gaps.map((gap) => [gap.kind, gap.id, gap.message]))
448
+ }
449
+
450
+ function escapeHtml (value) {
451
+ return String(value == null ? '' : value)
452
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
453
+ }
454
+
455
+ function cellList (items, show) {
456
+ if (!items.length) return '<span class="none">None</span>'
457
+ return `<ul>${items.map((item) => `<li>${show(item)}</li>`).join('')}</ul>`
458
+ }
459
+
460
+ const named = (item) => `<code>${escapeHtml(item.id)}</code> ${escapeHtml(item.title || '')}`
461
+ const outcome = (item) => `${named(item)}${item.outcome ? ` <strong>(${escapeHtml(item.outcome)})</strong>` : ''}`
462
+
463
+ // A page that opens anywhere, with nothing to fetch: it is attached to a safety
464
+ // case and read years later, long after any viewer that made it has gone.
465
+ function toHtml (trace, baseline, { title }) {
466
+ const gapCounts = {}
467
+ for (const gap of trace.gaps) gapCounts[gap.kind] = (gapCounts[gap.kind] || 0) + 1
468
+ const whoCell = (row) => [
469
+ row.draftedBy && `Drafted: ${escapeHtml(row.draftedBy)}`,
470
+ row.reviewedBy && `Reviewed: ${escapeHtml(row.reviewedBy)}${row.reviewedOn ? ` (${escapeHtml(row.reviewedOn)})` : ''}`,
471
+ row.signedOffBy && `Signed off: ${escapeHtml(row.signedOffBy)}${row.signedOffOn ? ` (${escapeHtml(row.signedOffOn)})` : ''}`
472
+ ].filter(Boolean).join('<br>') || '<span class="none">Not recorded</span>'
473
+
474
+ return `<!doctype html>
475
+ <html lang="en">
476
+ <head>
477
+ <meta charset="utf-8">
478
+ <meta name="viewport" content="width=device-width, initial-scale=1">
479
+ <title>${escapeHtml(title)}</title>
480
+ <style>
481
+ body { font-family: Arial, Helvetica, sans-serif; color: #212b32; margin: 24px; line-height: 1.4; }
482
+ h1 { font-size: 28px; margin: 0 0 8px; }
483
+ h2 { font-size: 22px; margin: 32px 0 8px; }
484
+ p.meta { color: #4c6272; margin: 0 0 4px; }
485
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
486
+ th, td { border-bottom: 1px solid #d8dde0; padding: 8px; text-align: left; vertical-align: top; }
487
+ th { background: #f0f4f5; }
488
+ ul { margin: 0; padding-left: 18px; }
489
+ code { font-size: 13px; }
490
+ .none { color: #4c6272; }
491
+ </style>
492
+ </head>
493
+ <body>
494
+ <h1>${escapeHtml(title)}</h1>
495
+ <p class="meta">Generated ${escapeHtml(baseline.generatedAt)} by Hippocampus ${escapeHtml(baseline.packageVersion)}${baseline.release ? `, release ${escapeHtml(baseline.release)}` : ''}.</p>
496
+ <p class="meta">Git commit ${escapeHtml(baseline.git.commit || 'unknown')}${baseline.git.sourceUncommitted ? ' - the knowledge base had uncommitted changes; the fingerprints in baseline.json describe what was read' : ''}.</p>
497
+
498
+ <h2>Gaps (${trace.gaps.length})</h2>
499
+ ${trace.gaps.length
500
+ ? `<table><thead><tr><th scope="col">Gap</th><th scope="col">Count</th></tr></thead><tbody>${Object.entries(gapCounts).map(([kind, count]) => `<tr><td>${escapeHtml(kind)}</td><td>${count}</td></tr>`).join('')}</tbody></table>
501
+ <p class="meta">Every gap, with its record, is in gaps.csv.</p>`
502
+ : '<p>None found.</p>'}
503
+
504
+ <h2>Requirements (${trace.requirements.length})</h2>
505
+ <table>
506
+ <thead><tr><th scope="col">Requirement</th><th scope="col">Needs</th><th scope="col">Decisions</th><th scope="col">Screens</th><th scope="col">Components</th><th scope="col">Evaluations</th><th scope="col">Who</th></tr></thead>
507
+ <tbody>
508
+ ${trace.requirements.map((row) => `<tr>
509
+ <td><code>${escapeHtml(row.id)}</code><br>${escapeHtml(row.statement)}</td>
510
+ <td>${cellList(row.needs, named)}</td>
511
+ <td>${cellList(row.decisions, outcome)}</td>
512
+ <td>${cellList(row.screens, named)}</td>
513
+ <td>${cellList(row.components, named)}</td>
514
+ <td>${cellList(row.evaluations, outcome)}</td>
515
+ <td>${whoCell(row)}</td>
516
+ </tr>`).join('\n')}
517
+ </tbody>
518
+ </table>
519
+
520
+ <h2>Components (${trace.components.length})</h2>
521
+ ${trace.components.length
522
+ ? `<table>
523
+ <thead><tr><th scope="col">Component</th><th scope="col">Files</th><th scope="col">Changed because of</th><th scope="col">Who</th></tr></thead>
524
+ <tbody>
525
+ ${trace.components.map((row) => `<tr>
526
+ <td><code>${escapeHtml(row.id)}</code><br>${escapeHtml(row.title)}</td>
527
+ <td>Prototype: <code>${escapeHtml(row.prototypePath)}</code>${row.guide ? `<br>Guide: <code>${escapeHtml(row.guide)}</code>` : ''}${row.productionPath ? `<br>Production: <code>${escapeHtml(row.productionPath)}</code>` : ''}${row.portedFromCommit ? `<br>Ported from <code>${escapeHtml(row.portedFromCommit)}</code>` : ''}</td>
528
+ <td>${cellList(row.reasons, (r) => `${named(r)}${r.commit ? ` - commit <code>${escapeHtml(r.commit)}</code>` : ''}${r.pr ? ` - ${escapeHtml(r.pr)}` : ''}`)}</td>
529
+ <td>${whoCell(row)}</td>
530
+ </tr>`).join('\n')}
531
+ </tbody>
532
+ </table>`
533
+ : '<p>No components recorded.</p>'}
534
+
535
+ <h2>Hazards (${trace.hazards.length})</h2>
536
+ ${trace.hazards.length
537
+ ? `<table>
538
+ <thead><tr><th scope="col">Hazard</th><th scope="col">Risk</th><th scope="col">Causes</th><th scope="col">Controls, what builds them, what verified them</th><th scope="col">Identified from</th><th scope="col">Who</th></tr></thead>
539
+ <tbody>
540
+ ${trace.hazards.map((row) => `<tr>
541
+ <td><code>${escapeHtml(row.id)}</code>${row.logNumber != null ? ` (log ${escapeHtml(row.logNumber)})` : ''}<br>${escapeHtml(row.title)}<br><span class="none">${escapeHtml(row.status)}</span></td>
542
+ <td>${row.initialRisk ? `Initial ${escapeHtml(riskText(row.initialRisk))}` : '<span class="none">Not rated</span>'}${row.residualRisk ? `<br>Residual ${escapeHtml(riskText(row.residualRisk))}` : ''}${row.assessedBy ? `<br>Assessed by ${escapeHtml(row.assessedBy)}${row.assessedOn ? ` (${escapeHtml(row.assessedOn)})` : ''}` : ''}</td>
543
+ <td>${cellList(row.causes, (c) => `${escapeHtml(c.number)}. ${escapeHtml(c.statement)}`)}</td>
544
+ <td>${cellList(row.controls, (c) => `${named(c)} <span class="none">${escapeHtml([c.kind, c.stage, c.status].filter(Boolean).join(', '))}</span>${c.builtBy.length ? `<br>Built by ${c.builtBy.map((b) => `<code>${escapeHtml(b.id)}</code>`).join(', ')}` : ''}${c.verifiedBy.length ? `<br>Verified by ${c.verifiedBy.map((v) => `<code>${escapeHtml(v.id)}</code>${v.outcome ? ` (${escapeHtml(v.outcome)})` : ''}`).join(', ')}` : ''}`)}</td>
545
+ <td>${cellList(row.identifiedFrom, named)}</td>
546
+ <td>${whoCell(row)}</td>
547
+ </tr>`).join('\n')}
548
+ </tbody>
549
+ </table>`
550
+ : '<p>No hazards recorded.</p>'}
551
+ </body>
552
+ </html>
553
+ `
554
+ }
555
+
556
+ function writeTraceExport ({ outDir, trace, baseline, title }) {
557
+ fs.mkdirSync(outDir, { recursive: true })
558
+ const files = {
559
+ 'trace.html': toHtml(trace, baseline, { title }),
560
+ 'trace-requirements.csv': requirementsCsv(trace),
561
+ 'trace-components.csv': componentsCsv(trace),
562
+ 'trace-hazards.csv': hazardsCsv(trace),
563
+ 'hazard-log.csv': hazardLogCsv(trace),
564
+ 'gaps.csv': gapsCsv(trace),
565
+ 'baseline.json': `${JSON.stringify(baseline, null, 2)}\n`
566
+ }
567
+ for (const [name, content] of Object.entries(files)) fs.writeFileSync(path.join(outDir, name), content)
568
+ return Object.keys(files)
569
+ }
570
+
571
+ module.exports = { buildTrace, findGaps, buildBaseline, compareBaseline, writeTraceExport, csvCell, toHtml }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "A design-knowledge base for NHS Prototype Kit projects: research, insights, needs, journeys and screens, traceable end to end.",
5
5
  "license": "MIT",
6
6
  "main": "index.js",
@@ -21,7 +21,7 @@ const fs = require('fs')
21
21
  const path = require('path')
22
22
  const { openWorkbook, readSheetGrid } = require('./lib/xlsx-grid')
23
23
  const { KnowledgeSchema } = require('../lib/schema')
24
- const { readMeta, migrateInMemory } = require('../lib/schema-version')
24
+ const { readMeta, migrateInMemory, recordLevelNeeded } = require('../lib/schema-version')
25
25
  const { createContextOrExit } = require('../lib/context')
26
26
  const ctx = createContextOrExit()
27
27
  const { knowledgeSourceDir } = ctx.paths
@@ -195,6 +195,8 @@ function main () {
195
195
  for (const [file, data] of Object.entries(proposed)) {
196
196
  fs.writeFileSync(path.join(knowledgeSourceDir, file), `${JSON.stringify(data, null, 2)}\n`)
197
197
  }
198
+ const level = recordLevelNeeded(knowledgeSourceDir, migrated)
199
+ if (level) console.log(`This knowledge base now needs Hippocampus ${level} or later. Recorded in _meta.json.`)
198
200
  console.log(`\nImported from ${path.relative(ctx.root, path.resolve(args.workbook))}. Run npx hippocampus validate to confirm.`)
199
201
  }
200
202
 
package/scripts/init.js CHANGED
@@ -144,7 +144,8 @@ function listTemplateFiles (dir, prefix = '') {
144
144
  const EMPTY_COLLECTIONS = [
145
145
  'users', 'needs', 'scenarios', 'journeys', 'screens', 'evidence', 'decisions',
146
146
  'assumptions', 'research-rounds', 'participants', 'insights', 'design-actions',
147
- 'goals', 'quality-objectives', 'requirements', 'principles',
147
+ 'goals', 'quality-objectives', 'requirements', 'principles', 'components',
148
+ 'intended-purposes', 'hazards', 'controls',
148
149
  'relationships'
149
150
  ]
150
151