@hippo-digital/hippocampus 2.8.1 → 2.9.1

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.
@@ -3,28 +3,11 @@ const path = require('path')
3
3
  const { KnowledgeSchema } = require('./schema')
4
4
  const { readMeta, migrateInMemory } = require('./schema-version')
5
5
  const { buildFlowMap } = require('./flow-map')
6
+ const { COLLECTION_FILES } = require('./collections')
6
7
 
7
- const files = {
8
- project: 'project.json',
9
- projectContext: 'project-context.json',
10
- users: 'users.json',
11
- needs: 'needs.json',
12
- scenarios: 'scenarios.json',
13
- journeys: 'journeys.json',
14
- screens: 'screens.json',
15
- evidence: 'evidence.json',
16
- decisions: 'decisions.json',
17
- assumptions: 'assumptions.json',
18
- researchRounds: 'research-rounds.json',
19
- participants: 'participants.json',
20
- insights: 'insights.json',
21
- designActions: 'design-actions.json',
22
- goals: 'goals.json',
23
- qualityObjectives: 'quality-objectives.json',
24
- requirements: 'requirements.json',
25
- principles: 'principles.json',
26
- relationships: 'relationships.json'
27
- }
8
+ // The file list is shared with every command that reads or writes a knowledge
9
+ // base, so they cannot disagree about what one is made of.
10
+ const files = COLLECTION_FILES
28
11
 
29
12
  function createKnowledgeStore (paths) {
30
13
  function readJson (filename) {
@@ -200,7 +183,9 @@ const OUTWARD = {
200
183
  'verified-by': 'Evaluated by',
201
184
  'weighed-against': 'Requirements this was weighed against',
202
185
  'applies-principle': 'Principles applied',
203
- 'observed-on': 'Seen on screens'
186
+ 'observed-on': 'Seen on screens',
187
+ 'rests-on': 'Rests on assumptions',
188
+ 'challenged-by': 'Challenged by'
204
189
  }
205
190
 
206
191
  const INWARD = {
@@ -225,7 +210,9 @@ const INWARD = {
225
210
  'verified-by': 'Requirements this evaluated',
226
211
  'weighed-against': 'Options weighed against this',
227
212
  'applies-principle': 'Applied by',
228
- 'observed-on': 'Findings seen here'
213
+ 'observed-on': 'Findings seen here',
214
+ 'rests-on': 'Work that rests on this',
215
+ 'challenged-by': 'Challenges'
229
216
  }
230
217
 
231
218
  function outwardLabel (type) { return OUTWARD[type] || type }
@@ -242,69 +229,6 @@ function findRecord (knowledge, id) {
242
229
  return null
243
230
  }
244
231
 
245
- function buildIndex (knowledge) {
246
- const index = {
247
- users: byId(knowledge.users),
248
- needs: byId(knowledge.needs),
249
- scenarios: byId(knowledge.scenarios),
250
- journeys: byId(knowledge.journeys),
251
- screens: byId(knowledge.screens),
252
- evidence: byId(knowledge.evidence),
253
- decisions: byId(knowledge.decisions),
254
- assumptions: byId(knowledge.assumptions),
255
- researchRounds: byId(knowledge.researchRounds),
256
- participants: byId(knowledge.participants),
257
- insights: byId(knowledge.insights),
258
- designActions: byId(knowledge.designActions),
259
- goals: byId(knowledge.goals || []),
260
- qualityObjectives: byId(knowledge.qualityObjectives || []),
261
- requirements: byId(knowledge.requirements || []),
262
- principles: byId(knowledge.principles || []),
263
- relationships: byId(knowledge.relationships)
264
- }
265
- index.entities = buildEntityIndex(knowledge)
266
- return index
267
- }
268
-
269
- function byId (items) {
270
- return Object.fromEntries(items.map((item) => [item.id, item]))
271
- }
272
-
273
- function buildEntityIndex (knowledge) {
274
- const entityCollections = {
275
- users: { type: 'User', labelKey: 'label' },
276
- needs: { type: 'Need', labelKey: 'statement' },
277
- scenarios: { type: 'Scenario', labelKey: 'title' },
278
- journeys: { type: 'Journey', labelKey: 'title' },
279
- screens: { type: 'Screen', labelKey: 'title' },
280
- evidence: { type: 'Evidence', labelKey: 'title' },
281
- decisions: { type: 'Decision', labelKey: 'title' },
282
- assumptions: { type: 'Assumption', labelKey: 'statement' },
283
- researchRounds: { type: 'Research round', labelKey: 'title' },
284
- participants: { type: 'Participant', labelKey: 'label' },
285
- insights: { type: 'Insight', labelKey: 'title' },
286
- designActions: { type: 'Design action', labelKey: 'title' },
287
- goals: { type: 'Goal', labelKey: 'statement' },
288
- qualityObjectives: { type: 'Quality objective', labelKey: 'statement' },
289
- requirements: { type: 'Requirement', labelKey: 'statement' },
290
- principles: { type: 'Principle', labelKey: 'title' }
291
- }
292
-
293
- const entities = {}
294
- for (const [collection, config] of Object.entries(entityCollections)) {
295
- for (const item of knowledge[collection] || []) {
296
- entities[item.id] = {
297
- id: item.id,
298
- type: config.type,
299
- label: item[config.labelKey],
300
- collection,
301
- item
302
- }
303
- }
304
- }
305
- return entities
306
- }
307
-
308
232
  function getJourney (journeyId) {
309
233
  const knowledge = getKnowledge()
310
234
  return knowledge.index.journeys[journeyId]
@@ -550,9 +474,11 @@ function getResearchViewModel () {
550
474
  action.insightIds.some((insightId) => roundInsightIds.has(insightId)))
551
475
  const outstanding = designActions.filter(isOutstanding)
552
476
 
477
+ const inRound = knowledge.participants.filter((participant) => participant.roundIds.includes(round.id))
553
478
  return {
554
479
  ...round,
555
- participants: knowledge.participants.filter((participant) => participant.roundIds.includes(round.id)),
480
+ participants: inRound.filter((participant) => participant.kind !== 'reviewer'),
481
+ reviewers: inRound.filter((participant) => participant.kind === 'reviewer'),
556
482
  insights,
557
483
  designActions,
558
484
  outstanding,
@@ -565,9 +491,13 @@ function getResearchViewModel () {
565
491
  // reach it. Sorted by date rather than by file order, which was neither.
566
492
  rounds.sort((a, b) => String(b.date || '').localeCompare(String(a.date || '')))
567
493
 
494
+ // Reviewers in an expert review are not research participants. Counting them
495
+ // as such is how a clinical safety officer once became one of 92 people the
496
+ // research rested on.
568
497
  return {
569
498
  rounds,
570
- participants: knowledge.participants,
499
+ participants: knowledge.participants.filter((participant) => participant.kind !== 'reviewer'),
500
+ reviewers: knowledge.participants.filter((participant) => participant.kind === 'reviewer'),
571
501
  insights: knowledge.insights,
572
502
  designActions: knowledge.designActions,
573
503
  outstandingTotal: knowledge.designActions.filter(isOutstanding).length
@@ -832,25 +762,73 @@ function sourcesUpdatedAt () {
832
762
  }
833
763
 
834
764
  function validateKnowledge () {
835
- const errors = []
836
765
  let knowledge
837
766
 
838
767
  try {
768
+ readMeta(paths.knowledgeSourceDir)
839
769
  knowledge = loadKnowledgeData()
840
770
  } catch (error) {
841
771
  return { valid: false, errors: [`Could not load knowledge data: ${error.message}`], sourcesUpdatedAt: sourcesUpdatedAt() }
842
772
  }
843
773
 
774
+ const errors = checkKnowledgeData(knowledge)
775
+ return { valid: errors.length === 0, errors, sourcesUpdatedAt: sourcesUpdatedAt() }
776
+ }
777
+
778
+ function sortByLabel (items, key) {
779
+ return items.sort((a, b) => a[key].localeCompare(b[key]))
780
+ }
781
+
782
+ function sortByTypeThenLabel (items) {
783
+ return items.sort((a, b) => `${a.type}:${a.label}`.localeCompare(`${b.type}:${b.label}`))
784
+ }
785
+
786
+ function relationshipLabel (type) {
787
+ return type.replace(/-/g, ' ')
788
+ }
789
+
790
+ function uniqueById (items) {
791
+ return Object.values(Object.fromEntries(items.map((item) => [item.id, item])))
792
+ }
793
+
794
+ function uniqueEdges (edges) {
795
+ return Object.values(Object.fromEntries(edges.map((edge) => [`${edge.from}:${edge.label}:${edge.to}`, edge])))
796
+ }
797
+
798
+ return {
799
+ getKnowledge,
800
+ getJourney,
801
+ getUserKnowledgeGraph,
802
+ getGraphExplorer,
803
+ getTraceExplorer,
804
+ getEvidenceImpact,
805
+ getRecordDetail,
806
+ getServiceTitle,
807
+ getResearchViewModel,
808
+ buildBlueprintViewModel,
809
+ buildJourneyFlowDiagram,
810
+ validateKnowledge
811
+ }
812
+ }
813
+
814
+
815
+ /**
816
+ * Every rule `hippocampus validate` applies, run on knowledge already in
817
+ * memory. Returns the list of errors; empty means valid.
818
+ *
819
+ * Kept apart from reading the files so a draft can be checked against the
820
+ * knowledge base it would join before anything is written - the only way a
821
+ * promote command can refuse a bad draft without leaving source half-changed.
822
+ */
823
+ function checkKnowledgeData (raw) {
824
+ const errors = []
825
+ let knowledge = raw
844
826
  const schemaResult = KnowledgeSchema.safeParse(knowledge)
845
827
  if (!schemaResult.success) {
846
- return {
847
- valid: false,
848
- errors: schemaResult.error.issues.map((issue) => {
849
- const fieldPath = issue.path.length ? issue.path.join('.') : 'knowledge'
850
- return `${fieldPath}: ${issue.message}`
851
- }),
852
- sourcesUpdatedAt: sourcesUpdatedAt()
853
- }
828
+ return schemaResult.error.issues.map((issue) => {
829
+ const fieldPath = issue.path.length ? issue.path.join('.') : 'knowledge'
830
+ return `${fieldPath}: ${issue.message}`
831
+ })
854
832
  }
855
833
 
856
834
  knowledge = schemaResult.data
@@ -961,7 +939,70 @@ function validateKnowledge () {
961
939
  }
962
940
  }
963
941
 
964
- return { valid: errors.length === 0, errors, sourcesUpdatedAt: sourcesUpdatedAt() }
942
+ return errors
943
+ }
944
+
945
+ function buildIndex (knowledge) {
946
+ const index = {
947
+ users: byId(knowledge.users),
948
+ needs: byId(knowledge.needs),
949
+ scenarios: byId(knowledge.scenarios),
950
+ journeys: byId(knowledge.journeys),
951
+ screens: byId(knowledge.screens),
952
+ evidence: byId(knowledge.evidence),
953
+ decisions: byId(knowledge.decisions),
954
+ assumptions: byId(knowledge.assumptions),
955
+ researchRounds: byId(knowledge.researchRounds),
956
+ participants: byId(knowledge.participants),
957
+ insights: byId(knowledge.insights),
958
+ designActions: byId(knowledge.designActions),
959
+ goals: byId(knowledge.goals || []),
960
+ qualityObjectives: byId(knowledge.qualityObjectives || []),
961
+ requirements: byId(knowledge.requirements || []),
962
+ principles: byId(knowledge.principles || []),
963
+ relationships: byId(knowledge.relationships)
964
+ }
965
+ index.entities = buildEntityIndex(knowledge)
966
+ return index
967
+ }
968
+
969
+ function byId (items) {
970
+ return Object.fromEntries(items.map((item) => [item.id, item]))
971
+ }
972
+
973
+ function buildEntityIndex (knowledge) {
974
+ const entityCollections = {
975
+ users: { type: 'User', labelKey: 'label' },
976
+ needs: { type: 'Need', labelKey: 'statement' },
977
+ scenarios: { type: 'Scenario', labelKey: 'title' },
978
+ journeys: { type: 'Journey', labelKey: 'title' },
979
+ screens: { type: 'Screen', labelKey: 'title' },
980
+ evidence: { type: 'Evidence', labelKey: 'title' },
981
+ decisions: { type: 'Decision', labelKey: 'title' },
982
+ assumptions: { type: 'Assumption', labelKey: 'statement' },
983
+ researchRounds: { type: 'Research round', labelKey: 'title' },
984
+ participants: { type: 'Participant', labelKey: 'label' },
985
+ insights: { type: 'Insight', labelKey: 'title' },
986
+ designActions: { type: 'Design action', labelKey: 'title' },
987
+ goals: { type: 'Goal', labelKey: 'statement' },
988
+ qualityObjectives: { type: 'Quality objective', labelKey: 'statement' },
989
+ requirements: { type: 'Requirement', labelKey: 'statement' },
990
+ principles: { type: 'Principle', labelKey: 'title' }
991
+ }
992
+
993
+ const entities = {}
994
+ for (const [collection, config] of Object.entries(entityCollections)) {
995
+ for (const item of knowledge[collection] || []) {
996
+ entities[item.id] = {
997
+ id: item.id,
998
+ type: config.type,
999
+ label: item[config.labelKey],
1000
+ collection,
1001
+ item
1002
+ }
1003
+ }
1004
+ }
1005
+ return entities
965
1006
  }
966
1007
 
967
1008
  // Where each of the requirements-layer links may start and end. The older link
@@ -975,7 +1016,9 @@ const RELATIONSHIP_ENDS = {
975
1016
  'verified-by': { from: ['requirements'], to: ['insights'] },
976
1017
  'weighed-against': { from: ['decisions'], to: ['requirements'] },
977
1018
  'applies-principle': { from: ['screens', 'requirements', 'decisions', 'journeys'], to: ['principles'] },
978
- 'observed-on': { from: ['insights'], to: ['screens'] }
1019
+ 'observed-on': { from: ['insights'], to: ['screens'] },
1020
+ 'rests-on': { from: ['designActions', 'decisions', 'requirements'], to: ['assumptions'] },
1021
+ 'challenged-by': { from: ['assumptions', 'decisions', 'requirements'], to: ['evidence', 'insights'] }
979
1022
  }
980
1023
 
981
1024
  /**
@@ -1010,44 +1053,11 @@ function requireRef (errors, type, id, field, value, lookup) {
1010
1053
  if (!lookup[value]) errors.push(`${type} ${id}: ${field} references missing id ${value}`)
1011
1054
  }
1012
1055
 
1013
- function sortByLabel (items, key) {
1014
- return items.sort((a, b) => a[key].localeCompare(b[key]))
1015
- }
1016
-
1017
- function sortByTypeThenLabel (items) {
1018
- return items.sort((a, b) => `${a.type}:${a.label}`.localeCompare(`${b.type}:${b.label}`))
1019
- }
1020
-
1021
- function relationshipLabel (type) {
1022
- return type.replace(/-/g, ' ')
1023
- }
1024
-
1025
- function uniqueById (items) {
1026
- return Object.values(Object.fromEntries(items.map((item) => [item.id, item])))
1027
- }
1028
-
1029
- function uniqueEdges (edges) {
1030
- return Object.values(Object.fromEntries(edges.map((edge) => [`${edge.from}:${edge.label}:${edge.to}`, edge])))
1031
- }
1032
-
1033
- return {
1034
- getKnowledge,
1035
- getJourney,
1036
- getUserKnowledgeGraph,
1037
- getGraphExplorer,
1038
- getTraceExplorer,
1039
- getEvidenceImpact,
1040
- getRecordDetail,
1041
- getServiceTitle,
1042
- getResearchViewModel,
1043
- buildBlueprintViewModel,
1044
- buildJourneyFlowDiagram,
1045
- validateKnowledge
1046
- }
1047
- }
1048
-
1049
1056
  // No default store. A store is always built from an explicitly resolved root,
1050
1057
  // so nothing can quietly read the wrong project.
1051
1058
  module.exports = {
1052
- createKnowledgeStore
1059
+ createKnowledgeStore,
1060
+ checkKnowledgeData,
1061
+ buildIndex,
1062
+ RELATIONSHIP_ENDS
1053
1063
  }
@@ -9,6 +9,28 @@ const path = require('path')
9
9
  const CURRENT_SCHEMA_VERSION = 1
10
10
  const META_FILENAME = '_meta.json'
11
11
 
12
+ // Additive changes inside schemaVersion 1 still have one sharp edge: a new
13
+ // value in a list the schema checks - a link type, a research method - fails
14
+ // validation in a package that predates it, with an error about an enum that
15
+ // tells nobody to upgrade. So a knowledge base that uses such a value records
16
+ // the package level it needs, and this code refuses one that needs more than it
17
+ // has, with a message that says so.
18
+ //
19
+ // Raise this when a release adds a value or record type that older packages
20
+ // would reject, and list what needs it in FEATURES_NEEDING.
21
+ const FEATURE_LEVEL = '2.9.0'
22
+
23
+ // What, in a knowledge base, needs which level. Checked by every command that
24
+ // writes records (draft promote, promote research, import design-actions), so
25
+ // the level is written only once something actually needs it. validate warns
26
+ // when a hand edit has added one without it, and migrate records it.
27
+ const FEATURES_NEEDING = {
28
+ '2.9.0': {
29
+ relationshipTypes: ['rests-on', 'challenged-by'],
30
+ researchMethods: ['expert-review']
31
+ }
32
+ }
33
+
12
34
  // Keyed by the version they migrate FROM. Empty on purpose: version 1 is the
13
35
  // first, and the runner exists so the first real migration is a data change
14
36
  // rather than an architecture change made under pressure.
@@ -35,9 +57,77 @@ function readMeta (knowledgeSourceDir) {
35
57
  throw new Error(`${META_FILENAME} has no usable schemaVersion: ${metaPath}`)
36
58
  }
37
59
 
60
+ if (meta.requiresPackage && compareVersions(meta.requiresPackage, FEATURE_LEVEL) > 0) {
61
+ throw new Error(
62
+ `This knowledge base uses features from Hippocampus ${meta.requiresPackage}, ` +
63
+ `but this version understands up to ${FEATURE_LEVEL}.\n${metaPath}\n` +
64
+ 'Upgrade @hippo-digital/hippocampus rather than reading it with older code.'
65
+ )
66
+ }
67
+
38
68
  return { ...meta, schemaVersion, implicit: false, metaPath }
39
69
  }
40
70
 
71
+ function compareVersions (a, b) {
72
+ const pa = String(a).split('-')[0].split('.').map(Number)
73
+ const pb = String(b).split('-')[0].split('.').map(Number)
74
+ for (let i = 0; i < 3; i++) {
75
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0)
76
+ }
77
+ return 0
78
+ }
79
+
80
+ // Each versioned feature this knowledge uses, with the level it needs.
81
+ function featuresUsed (knowledge) {
82
+ const linkTypes = new Set((knowledge.relationships || []).map((r) => r.type))
83
+ const methods = new Set((knowledge.researchRounds || []).flatMap((r) => r.methods || []))
84
+ const used = []
85
+ for (const [level, uses] of Object.entries(FEATURES_NEEDING)) {
86
+ for (const type of uses.relationshipTypes || []) if (linkTypes.has(type)) used.push({ level, feature: `${type} links` })
87
+ for (const method of uses.researchMethods || []) if (methods.has(method)) used.push({ level, feature: `the ${method} method` })
88
+ }
89
+ return used
90
+ }
91
+
92
+ // The lowest level that can read this knowledge, from what it actually uses.
93
+ function levelNeeded (knowledge) {
94
+ let needed = null
95
+ for (const { level } of featuresUsed(knowledge)) {
96
+ if (!needed || compareVersions(level, needed) > 0) needed = level
97
+ }
98
+ return needed
99
+ }
100
+
101
+ // What the knowledge needs and _meta.json does not yet say: { level, features }
102
+ // or null. Records added by hand, or by a command older than this check, are
103
+ // the usual cause, and an older package then fails on them with a schema error
104
+ // instead of asking for an upgrade.
105
+ function unrecordedLevel (knowledgeSourceDir, knowledge) {
106
+ const needed = levelNeeded(knowledge)
107
+ if (!needed) return null
108
+ const metaPath = path.join(knowledgeSourceDir, META_FILENAME)
109
+ const recorded = fs.existsSync(metaPath) ? JSON.parse(fs.readFileSync(metaPath, 'utf8')).requiresPackage : null
110
+ if (recorded && compareVersions(recorded, needed) >= 0) return null
111
+ const features = featuresUsed(knowledge)
112
+ .filter(({ level }) => !recorded || compareVersions(level, recorded) > 0)
113
+ .map(({ feature }) => feature)
114
+ return { level: needed, features }
115
+ }
116
+
117
+ // Writes requiresPackage into _meta.json when the knowledge now needs a higher
118
+ // level than it records. Never lowers it: removing the last use of a feature
119
+ // is not worth a write, and an over-cautious level costs an upgrade at most.
120
+ function recordLevelNeeded (knowledgeSourceDir, knowledge) {
121
+ const needed = levelNeeded(knowledge)
122
+ if (!needed) return null
123
+ const metaPath = path.join(knowledgeSourceDir, META_FILENAME)
124
+ const current = fs.existsSync(metaPath) ? JSON.parse(fs.readFileSync(metaPath, 'utf8')) : { schemaVersion: CURRENT_SCHEMA_VERSION }
125
+ if (current.requiresPackage && compareVersions(current.requiresPackage, needed) >= 0) return null
126
+ const meta = { ...current, requiresPackage: needed, updatedAt: new Date().toISOString() }
127
+ fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n')
128
+ return needed
129
+ }
130
+
41
131
  /**
42
132
  * Brings data up to the version this code understands, in memory.
43
133
  *
@@ -77,10 +167,14 @@ function migrateInMemory (knowledge, meta) {
77
167
 
78
168
  function writeMeta (knowledgeSourceDir, { generator } = {}) {
79
169
  const metaPath = path.join(knowledgeSourceDir, META_FILENAME)
170
+ // Keep what the file already says it needs: migrating the format must not
171
+ // forget that the data uses newer features.
172
+ const previous = fs.existsSync(metaPath) ? JSON.parse(fs.readFileSync(metaPath, 'utf8')) : {}
80
173
  const meta = {
81
174
  schemaVersion: CURRENT_SCHEMA_VERSION,
82
175
  generator: generator || 'hippocampus',
83
- updatedAt: new Date().toISOString()
176
+ updatedAt: new Date().toISOString(),
177
+ ...(previous.requiresPackage ? { requiresPackage: previous.requiresPackage } : {})
84
178
  }
85
179
  fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n')
86
180
  return meta
@@ -89,6 +183,13 @@ function writeMeta (knowledgeSourceDir, { generator } = {}) {
89
183
  module.exports = {
90
184
  CURRENT_SCHEMA_VERSION,
91
185
  META_FILENAME,
186
+ FEATURE_LEVEL,
187
+ FEATURES_NEEDING,
188
+ compareVersions,
189
+ featuresUsed,
190
+ levelNeeded,
191
+ unrecordedLevel,
192
+ recordLevelNeeded,
92
193
  migrations,
93
194
  readMeta,
94
195
  migrateInMemory,
package/lib/schema.js CHANGED
@@ -10,6 +10,14 @@ const stringList = z.array(nonEmptyString).min(1)
10
10
  // find a record it wrote earlier and update it rather than add a second copy.
11
11
  const reference = nonEmptyString.optional()
12
12
 
13
+ // A calendar date, written the way every other date in the knowledge base is.
14
+ const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use YYYY-MM-DD dates')
15
+
16
+ // Who is accountable for a record, or who decided it. A name or a role: which of
17
+ // the two a project records is an information governance question, so the
18
+ // package accepts either and says nothing about it.
19
+ const person = nonEmptyString.optional()
20
+
13
21
  // How much a finding matters - a different question from how sure we are of it,
14
22
  // which is `confidence`. A finding can be critical and only weakly evidenced;
15
23
  // folding the two together makes the most severe item in a log read as middling.
@@ -292,12 +300,18 @@ const EvidenceSchema = z.object({
292
300
  impact
293
301
  }).passthrough()
294
302
 
303
+ // Who decided, and when, used to be a sentence appended to the consequence. A
304
+ // trace has to be able to answer both questions without parsing prose, and a
305
+ // check has to be able to find an accepted decision with no decider.
295
306
  const DecisionSchema = z.object({
296
307
  id,
297
308
  title: nonEmptyString,
298
309
  status: z.enum(['proposed', 'accepted', 'superseded', 'rejected']),
299
310
  decision: nonEmptyString,
300
311
  consequence: nonEmptyString,
312
+ decidedBy: person,
313
+ decidedOn: isoDate.optional(),
314
+ owner: person,
301
315
  reference
302
316
  }).passthrough()
303
317
 
@@ -390,6 +404,11 @@ const researchMethod = z.enum([
390
404
  'preference-test',
391
405
  'desk-research',
392
406
  'analytics',
407
+ // A clinical, safety or other expert walks through the design and says what
408
+ // worries them. It is not usability testing - nobody is observed doing a
409
+ // task - so its findings say what an expert judged, and its reviewers are
410
+ // not research participants.
411
+ 'expert-review',
393
412
  'other'
394
413
  ])
395
414
 
@@ -401,6 +420,11 @@ const ResearchRoundSchema = z.object({
401
420
  sourceType: nonEmptyString,
402
421
  sourcePath: nonEmptyString.optional(),
403
422
  summary: nonEmptyString,
423
+ // IEC 62366-1 separates evaluation done while designing, to find problems
424
+ // (formative), from the planned final check that users can do the critical
425
+ // tasks safely (summative). Most rounds are formative; saying so is what
426
+ // makes a summative round stand out as the one the evidence rests on.
427
+ evaluation: z.enum(['formative', 'summative']).optional(),
404
428
  reference
405
429
  }).passthrough()
406
430
 
@@ -413,6 +437,10 @@ const ParticipantSchema = z.object({
413
437
  // The user group the participant was recruited as. Recorded at recruitment,
414
438
  // it replaces guessing the group from the job title afterwards.
415
439
  userId: id.optional(),
440
+ // A reviewer took part in an expert review: a clinical safety officer, say.
441
+ // They are not research participants, and counting them as such inflates
442
+ // how much research a finding rests on.
443
+ kind: z.enum(['research-participant', 'reviewer']).optional(),
416
444
  reference
417
445
  }).passthrough()
418
446
 
@@ -432,6 +460,7 @@ const InsightSchema = z.object({
432
460
  // clinical safety officer's. `signedOffBy` records who made it.
433
461
  rating: z.enum(['positive', 'minor', 'major', 'critical', 'catastrophic']).optional(),
434
462
  signedOffBy: nonEmptyString.optional(),
463
+ signedOffOn: isoDate.optional(),
435
464
  qualityDimension: qualityDimension.optional(),
436
465
  reference,
437
466
  impact
@@ -444,6 +473,7 @@ const DesignActionSchema = z.object({
444
473
  action: nonEmptyString,
445
474
  rationale: nonEmptyString,
446
475
  insightIds: z.array(id).min(1),
476
+ owner: person,
447
477
  reference
448
478
  }).passthrough()
449
479
 
@@ -485,7 +515,14 @@ const RelationshipSchema = z.object({
485
515
  'verified-by', // requirement -> insight that evaluated it (outcome)
486
516
  'weighed-against', // decision -> requirement (outcome)
487
517
  'applies-principle', // screen, requirement or decision -> principle
488
- 'observed-on' // insight -> screen the finding was seen on
518
+ 'observed-on', // insight -> screen the finding was seen on
519
+ // Assumptions. Work points at the assumption it relies on, so "if this
520
+ // assumption is wrong, what is affected?" is the same walk as for
521
+ // evidence. An assumption, decision or requirement points at the evidence
522
+ // or finding that weakens it - "supported-by" for a contradiction reads
523
+ // as the opposite of what it means.
524
+ 'rests-on', // design action, decision or requirement -> assumption
525
+ 'challenged-by' // assumption, decision or requirement -> evidence or insight
489
526
  ]),
490
527
  to: id,
491
528
  // How a decision fares against a requirement, or what an evaluation found.
@@ -521,6 +558,20 @@ const ProjectContextImportDraftSchema = z.object({
521
558
  }).strict()).min(1)
522
559
  }).strict()
523
560
 
561
+ // One draft for any records. A draft names what it adds, collection by
562
+ // collection, and can name the drafts that must be promoted before it, so an
563
+ // order that used to live in a review note is checked instead of remembered.
564
+ const DraftSchema = z.object({
565
+ draft: z.object({
566
+ title: nonEmptyString,
567
+ createdOn: isoDate.optional(),
568
+ summary: nonEmptyString.optional(),
569
+ after: z.array(nonEmptyString).optional(),
570
+ reviewNote: nonEmptyString.optional()
571
+ }).passthrough(),
572
+ records: z.record(z.string(), z.array(z.object({ id }).passthrough()))
573
+ }).strict()
574
+
524
575
  const KnowledgeSchema = z.object({
525
576
  project: ProjectSchema,
526
577
  projectContext: ProjectContextSchema,
@@ -574,5 +625,6 @@ module.exports = {
574
625
  KnowledgeSchema,
575
626
  ResearchImportDraftSchema,
576
627
  ProjectContextImportDraftSchema,
628
+ DraftSchema,
577
629
  recordSchemas
578
630
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "2.8.1",
3
+ "version": "2.9.1",
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",
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Say what a draft would add and whether the knowledge base would still be
4
+ * valid with it, without changing anything in hippocampus/source.
5
+ *
6
+ * npx hippocampus draft check --draft hippocampus/imports/<folder>/<draft>.json [--note <review.md>] [--no-note]
7
+ *
8
+ * Writes what it found into the draft's review note (its `reviewNote`, or a
9
+ * .review.md beside it), between two markers, so the reviewer reads the
10
+ * tool's account of the draft and not only the author's.
11
+ */
12
+ const { createContextOrExit } = require('../lib/context')
13
+ const { analyseDraft, resolveFromRoot, relative, summaryLines, writeNote, parseArgs } = require('./lib/draft')
14
+
15
+ const ctx = createContextOrExit()
16
+
17
+ function main () {
18
+ const args = parseArgs(process.argv.slice(2))
19
+ if (!args.draft || args.draft === true) {
20
+ throw new Error('Usage: npx hippocampus draft check --draft hippocampus/imports/<folder>/<draft>.json [--note <review.md>] [--no-note]')
21
+ }
22
+ const draftPath = resolveFromRoot(ctx, args.draft)
23
+ if (!draftPath) throw new Error(`No draft at ${args.draft}.`)
24
+
25
+ const result = analyseDraft(ctx, draftPath)
26
+ for (const line of summaryLines(ctx, draftPath, result)) console.log(line)
27
+ if (result.alreadyPromoted) console.log('Every record in this draft is already in the knowledge base: it has been promoted.')
28
+ for (const note of result.notes) console.log(note)
29
+
30
+ if (args.note !== false && !args.noNote && result.draft) {
31
+ const written = writeNote(ctx, draftPath, result, typeof args.note === 'string' ? args.note : null)
32
+ if (written) console.log(`Wrote what was found into ${relative(ctx, written)}.`)
33
+ }
34
+
35
+ if (result.problems.length) {
36
+ console.error(`\n${result.problems.length} problem${result.problems.length === 1 ? '' : 's'}:`)
37
+ for (const problem of result.problems) console.error(`- ${problem}`)
38
+ process.exit(1)
39
+ }
40
+ if (!result.alreadyPromoted) console.log('\nNo problems. Promote it with `npx hippocampus draft promote --draft <draft> --reviewer "<name or role>"` once it has been reviewed.')
41
+ }
42
+
43
+ try {
44
+ main()
45
+ } catch (error) {
46
+ console.error(error.message)
47
+ process.exit(1)
48
+ }