@hippo-digital/hippocampus 2.4.0 → 2.5.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 (35) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +19 -0
  3. package/assets/dist/hippocampus.css +1 -1
  4. package/assets/hippocampus.scss +34 -1
  5. package/docs/agent-roadmap.md +6 -1
  6. package/docs/agent-workflow.md +6 -1
  7. package/docs/ask-whats-already-known.md +159 -0
  8. package/docs/colour-pairings.md +6 -0
  9. package/docs/components.md +7 -1
  10. package/docs/custom-agents-usage.md +6 -1
  11. package/docs/design-actions-and-decisions.md +5 -0
  12. package/docs/diagrams/README.md +44 -0
  13. package/docs/diagrams/evidence-flow.mmd +56 -0
  14. package/docs/diagrams/mermaid.config.json +20 -0
  15. package/docs/hippocampus-for-designers-and-researchers.md +7 -1
  16. package/docs/hippocampus-technical.md +7 -1
  17. package/docs/images/evidence-flow.svg +1 -0
  18. package/docs/import-a-research-round.md +229 -0
  19. package/docs/prompt-architecture-guardrails.md +6 -1
  20. package/docs/repeatable-research-round-ingestion.md +6 -1
  21. package/docs/research-knowledge-graph.md +7 -1
  22. package/docs/research-source-file-conventions.md +7 -2
  23. package/docs/review-and-promote-a-draft.md +203 -0
  24. package/docs/source-model.md +7 -1
  25. package/docs/start-here.md +206 -0
  26. package/lib/create-router.js +26 -3
  27. package/lib/docs.js +288 -30
  28. package/package.json +1 -1
  29. package/scripts/import-research-deck.js +31 -6
  30. package/scripts/known.js +2 -2
  31. package/scripts/promote-research-draft.js +76 -6
  32. package/scripts/smoke-routes.js +8 -1
  33. package/views/hippocampus/doc.html +15 -0
  34. package/views/hippocampus/docs.html +42 -13
  35. package/views/hippocampus/research.html +9 -4
@@ -103,6 +103,11 @@ function buildDraft (args, slides) {
103
103
  const relationships = []
104
104
  const seenParticipants = new Map()
105
105
  const quotes = []
106
+ // An action has to respond to an insight - the schema says so - so one found
107
+ // before any insight cannot be kept as a record. It used to be kept anyway
108
+ // with no insight, which failed the whole file on schema validation: nothing
109
+ // imported, and sync marked the file failed and never tried it again.
110
+ const unlinkedActions = []
106
111
 
107
112
  const addParticipant = (label, role) => {
108
113
  const key = label.toLowerCase()
@@ -141,6 +146,10 @@ function buildDraft (args, slides) {
141
146
 
142
147
  const addAction = (statement, sourceSection) => {
143
148
  if (!isSubstantive(statement)) return null
149
+ if (!insights.length) {
150
+ unlinkedActions.push(statement)
151
+ return null
152
+ }
144
153
  const item = {
145
154
  id: kebab(`${args.artefactId} action ${designActions.length + 1}`),
146
155
  title: truncate(statement, 120),
@@ -158,6 +167,13 @@ function buildDraft (args, slides) {
158
167
  return item
159
168
  }
160
169
 
170
+ // The participant codes a line cites, as the ids addParticipant gives them.
171
+ // This once built `<round> participant <code>`, left over from when
172
+ // participants were per round; nothing matched, the filter below dropped
173
+ // every link, and every insight imported with no participants while the fit
174
+ // said "good". Lines with an explicit "Insight:" prefix passed none at all.
175
+ const citedParticipants = (line) => (line.match(PARTICIPANT_TOKEN) || []).map((token) => kebab(`participant ${token}`))
176
+
161
177
  for (const slide of slides) {
162
178
  const mode = modeFor(slide.title)
163
179
 
@@ -179,14 +195,14 @@ function buildDraft (args, slides) {
179
195
  }
180
196
 
181
197
  const explicitInsight = parsePrefixedLine(line, ['Insight', 'Finding', 'Observation'])
182
- if (explicitInsight) { addInsight(explicitInsight, slide.title, []); continue }
198
+ if (explicitInsight) { addInsight(explicitInsight, slide.title, citedParticipants(line)); continue }
183
199
 
184
200
  const explicitAction = parsePrefixedLine(line, ['Action', 'Design action', 'Recommendation'])
185
201
  if (explicitAction) { addAction(explicitAction, slide.title); continue }
186
202
 
187
203
  // Otherwise fall back to the heading's mode.
188
204
  if (line === slide.title || isSpeakerNote(line)) continue
189
- if (mode === 'insight') addInsight(line, slide.title, (line.match(PARTICIPANT_TOKEN) || []).map((t) => kebab(`${args.roundId} participant ${t}`)))
205
+ if (mode === 'insight') addInsight(line, slide.title, citedParticipants(line))
190
206
  else if (mode === 'action') addAction(line, slide.title)
191
207
  else if (mode === 'participant' && /\b\d+\s+\w/.test(line)) addInsight(`Sample composition: ${line}`, slide.title, [])
192
208
  }
@@ -202,9 +218,15 @@ function buildDraft (args, slides) {
202
218
  sourceDeck: path.relative(ctx.root, path.resolve(args.deck)),
203
219
  importedAt: new Date().toISOString(),
204
220
  warnings: [
205
- ...assessFit({ participants, insights, designActions, slides, quotes }),
221
+ ...assessFit({ participants, insights, designActions, slides, quotes, unlinkedActions }),
206
222
  ...(args.dateDerived === 'false'
207
223
  ? [`The round date ${args.date} is today's date, not the date of the research. No date was found in the file or folder name. Set it before promoting.`]
224
+ : []),
225
+ ...(unlinkedActions.length === 1
226
+ ? ['1 design action was found before any insight and left out, because an action has to respond to an insight. It is in the extracted text below; add it in review, linked to the insight it responds to.']
227
+ : []),
228
+ ...(unlinkedActions.length > 1
229
+ ? [`${unlinkedActions.length} design actions were found before any insight and left out, because an action has to respond to an insight. They are in the extracted text below; add them in review, each linked to the insight it responds to.`]
208
230
  : [])
209
231
  ],
210
232
  researchRounds: [
@@ -283,11 +305,11 @@ function validateDraft (draft) {
283
305
  throw new Error(`Imported draft does not match ResearchImportDraftSchema:\n- ${issues.join('\n- ')}`)
284
306
  }
285
307
 
286
- function assessFit ({ participants, insights, designActions, slides, quotes }) {
308
+ function assessFit ({ participants, insights, designActions, slides, quotes, unlinkedActions = [] }) {
287
309
  const warnings = []
288
310
  if (!participants.length) warnings.push('No participants were detected. Use participant codes such as P12 in the artefact, or lines like "Participant: P1 - Policy administrator".')
289
311
  if (!insights.length) warnings.push('No insights were detected. Put findings under a section titled "Insights", "Findings" or "What we learned", or prefix lines with "Insight:".')
290
- if (!designActions.length) warnings.push('No design actions were detected. Put them under a section titled "Design actions" or "Recommendations", or prefix lines with "Action:".')
312
+ if (!designActions.length && !unlinkedActions.length) warnings.push('No design actions were detected. Put them under a section titled "Design actions" or "Recommendations", or prefix lines with "Action:".')
291
313
  if (slides.length && insights.length / slides.length < 0.2) warnings.push('Low insight density for the number of sections. Check whether findings use unsupported headings.')
292
314
  if (quotes && quotes.length && !quotes.some((quote) => quote.participants.length)) {
293
315
  warnings.push(`${quotes.length} quotes were found but none carry a participant code. Attribute quotes as 'P12 - "quote"' so evidence can be traced to a person.`)
@@ -401,9 +423,12 @@ function appendSection (lines, title, items, renderItem) {
401
423
  }
402
424
  }
403
425
 
426
+ // A list marker in front of the prefix is still the prefix: notes are written
427
+ // as "- Insight: ...", and requiring the line to start with the word itself
428
+ // skipped every bulleted line in a Markdown or text note.
404
429
  function parsePrefixedLine (line, prefixes) {
405
430
  for (const prefix of prefixes) {
406
- const match = line.match(new RegExp(`^${escapeRegExp(prefix)}\\s*[:\\-]\\s*(.+)$`, 'i'))
431
+ const match = line.match(new RegExp(`^(?:[-*\\u2022]\\s+|\\d+[.)]\\s+)?${escapeRegExp(prefix)}\\s*[:\\-]\\s*(.+)$`, 'i'))
407
432
  if (match) return match[1].trim()
408
433
  }
409
434
  return null
package/scripts/known.js CHANGED
@@ -69,14 +69,14 @@ function section (title, items, render, note) {
69
69
  }
70
70
 
71
71
  console.log(`What the knowledge base holds on: ${result.terms.join(', ')}`)
72
- console.log(`(${ctx.root}, ${result.coverage.rounds.length} research rounds)`)
72
+ console.log(`(${ctx.root}, ${result.coverage.rounds.length} research round${result.coverage.rounds.length === 1 ? '' : 's'})`)
73
73
 
74
74
  if (result.nothingFound) {
75
75
  console.log('\nNo record names this.')
76
76
  }
77
77
 
78
78
  section('Findings', result.findings, (f) => f.kind === 'insight'
79
- ? ` insight ${f.id} [${f.confidence}, ${f.participants} participants, ${roundLabel(f.round)}]\n ${clip(f.label)}`
79
+ ? ` insight ${f.id} [${f.confidence}, ${f.participants} participant${f.participants === 1 ? '' : 's'}, ${roundLabel(f.round)}]\n ${clip(f.label)}`
80
80
  : ` evidence ${f.id} [${f.confidence}, ${f.sourceType}]\n ${clip(f.label)}`,
81
81
  'oldest round first; each is a separate claim')
82
82
 
@@ -4,7 +4,7 @@ const { spawnSync } = require('child_process')
4
4
  const { ResearchImportDraftSchema } = require('../lib/schema')
5
5
  const { createContextOrExit } = require('../lib/context')
6
6
  const ctx = createContextOrExit()
7
- const { knowledgeSourceDir, researchImportsDir } = ctx.paths
7
+ const { knowledgeSourceDir, researchImportsDir, researchManifestPath } = ctx.paths
8
8
 
9
9
  const dataDir = knowledgeSourceDir
10
10
 
@@ -18,12 +18,20 @@ const collections = {
18
18
 
19
19
  function main () {
20
20
  const args = parseArgs(process.argv.slice(2))
21
- if (!args.draft) {
22
- throw new Error(`Usage: npx hippocampus promote research -- --draft ${path.relative(ctx.root, path.join(researchImportsDir, 'round-id.json'))} [--dry-run]`)
21
+ if (!args.draft || args.draft === true) {
22
+ throw new Error(`Usage: npx hippocampus promote research --draft ${path.relative(ctx.root, path.join(researchImportsDir, '<draft>.json'))} [--dry-run]`)
23
23
  }
24
24
 
25
- const draft = validateDraft(readJson(path.resolve(args.draft)))
25
+ const draftPath = resolveDraft(args.draft)
26
+ const draft = validateDraft(readJson(draftPath))
26
27
  const current = readCurrentCollections()
28
+
29
+ if (alreadyPromoted(current, draft)) {
30
+ console.log(`Already promoted: every insight and design action in ${path.relative(ctx.root, draftPath)} is already in hippocampus/source. Nothing was written.`)
31
+ if (!args.dryRun) markPromoted(draftPath)
32
+ return
33
+ }
34
+
27
35
  const reused = reconcileSharedRecords(current, draft)
28
36
  const proposed = mergeCollections(current, draft)
29
37
  validateNoDuplicateIds(current, draft)
@@ -54,12 +62,67 @@ function main () {
54
62
  })
55
63
 
56
64
  if (validation.status !== 0) {
57
- throw new Error('Promotion wrote source files, but knowledge validation failed. Review the promoted data.')
65
+ throw new Error('Promotion wrote source files, but knowledge validation failed. Review the promoted data: `git diff hippocampus/source` shows what changed.')
58
66
  }
59
67
 
68
+ markPromoted(draftPath)
60
69
  console.log('Research draft promoted and knowledge validation passed.')
61
70
  }
62
71
 
72
+ /**
73
+ * Every place a draft path is printed - sync's report, the review file, this
74
+ * command's usage - writes it from the project root. So that is where it is
75
+ * looked for when it is not where the command was run, rather than failing
76
+ * from a subfolder with a stack trace about a file that is plainly there.
77
+ */
78
+ function resolveDraft (value) {
79
+ const found = [path.resolve(value), path.resolve(ctx.root, value)].find((candidate) => fs.existsSync(candidate))
80
+ if (found) return found
81
+
82
+ const drafts = fs.existsSync(researchImportsDir)
83
+ ? fs.readdirSync(researchImportsDir).filter((name) => name.endsWith('.json')).sort()
84
+ : []
85
+ const where = path.relative(ctx.root, researchImportsDir)
86
+ throw new Error([
87
+ `No draft at ${value}.`,
88
+ drafts.length
89
+ ? `Drafts in ${where}:\n${drafts.map((name) => ` ${path.join(where, name)}`).join('\n')}`
90
+ : `There are no drafts in ${where}. Run \`npx hippocampus research sync\` to import the files in the inbox.`
91
+ ].join('\n'))
92
+ }
93
+
94
+ /**
95
+ * A draft whose findings are all in source already has been promoted: by
96
+ * hand before promotion recorded itself in the manifest, or twice. Saying so
97
+ * is more use than failing on the first duplicate id.
98
+ */
99
+ function alreadyPromoted (current, draft) {
100
+ const records = [
101
+ ...(draft.insights || []).map((item) => ['insights', item.id]),
102
+ ...(draft.designActions || []).map((item) => ['designActions', item.id])
103
+ ]
104
+ if (!records.length) return false
105
+ const existing = { insights: idSet(current.insights), designActions: idSet(current.designActions) }
106
+ return records.every(([key, id]) => existing[key].has(id))
107
+ }
108
+
109
+ /**
110
+ * `research sync` keeps the list of what it has imported and promoted.
111
+ * Promoting with this command used to leave that list saying "imported", so
112
+ * the next sync offered the draft again and a yes failed on duplicate ids.
113
+ */
114
+ function markPromoted (draftPath) {
115
+ if (!fs.existsSync(researchManifestPath)) return
116
+ const manifest = readJson(researchManifestPath)
117
+ const item = (manifest.artefacts || []).find((artefact) =>
118
+ artefact.draftPath && path.resolve(ctx.root, artefact.draftPath) === draftPath)
119
+ if (!item || item.status === 'promoted') return
120
+ item.status = 'promoted'
121
+ item.promotedAt = new Date().toISOString()
122
+ manifest.updatedAt = item.promotedAt
123
+ writeJson(researchManifestPath, manifest)
124
+ }
125
+
63
126
  /**
64
127
  * A round is fieldwork, not a file, so several artefacts promote into the same
65
128
  * round and meet the same people. Re-promoting an identical round record, or a
@@ -238,4 +301,11 @@ function camelCase (value) {
238
301
  return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
239
302
  }
240
303
 
241
- main()
304
+ try {
305
+ main()
306
+ } catch (error) {
307
+ // Every failure here is something to read and act on - a missing draft, a
308
+ // duplicate id, a dangling reference - so it gets its message, not a stack.
309
+ console.error(error.message)
310
+ process.exit(1)
311
+ }
@@ -1,6 +1,6 @@
1
1
  const { spawn } = require('child_process')
2
2
  const { createContextOrExit } = require('../lib/context')
3
- const { listDocs } = require('../lib/docs')
3
+ const { listDocs, listDocImages } = require('../lib/docs')
4
4
  const { allTemplates } = require('../lib/templates')
5
5
  const ctx = createContextOrExit()
6
6
 
@@ -76,6 +76,13 @@ function buildRoutes (basePath, knowledge) {
76
76
  routes.add(`${basePath}/docs/${doc.slug}`)
77
77
  }
78
78
 
79
+ // A guide that embeds a diagram the viewer cannot serve still returns 200 -
80
+ // with a broken image in it. Checking the images themselves is the only way
81
+ // that shows up before somebody reads the page.
82
+ for (const image of listDocImages()) {
83
+ routes.add(`${basePath}/docs/images/${image}`)
84
+ }
85
+
79
86
  // Detail pages are generated per record, so check a sample rather than all
80
87
  // of them - 132 needs would make the smoke test a load test.
81
88
  for (const collection of [
@@ -1,4 +1,5 @@
1
1
  {% extends "hippocampus/_layout.html" %}
2
+ {% from "nhsuk/components/pagination/macro.njk" import pagination %}
2
3
 
3
4
  {% block pageTitle %}{{ doc.title }}{% endblock %}
4
5
 
@@ -6,5 +7,19 @@
6
7
  <article class="knowledge-doc">
7
8
  {{ doc.html | safe }}
8
9
  </article>
10
+
11
+ {#
12
+ Reading order runs across the whole guide, so the page after Start here is
13
+ the first recipe rather than a dead end. The section a page belongs to is
14
+ in the trail above it.
15
+ #}
16
+ {% if doc.previous or doc.next %}
17
+ {{ pagination({
18
+ previous: { href: basePath ~ "/docs/" ~ doc.previous.slug, labelText: doc.previous.title } if doc.previous else undefined,
19
+ next: { href: basePath ~ "/docs/" ~ doc.next.slug, labelText: doc.next.title } if doc.next else undefined,
20
+ ariaLabel: "Previous and next guide"
21
+ }) }}
22
+ {% endif %}
23
+
9
24
  <p class="knowledge-muted">@hippo-digital/hippocampus {{ packageVersion }}</p>
10
25
  {% endblock %}
@@ -4,20 +4,49 @@
4
4
 
5
5
  {% block content %}
6
6
  <h1>Documentation</h1>
7
- <p class="nhsuk-lede-text">These guides ship with the package, so they always describe the version you have installed.</p>
7
+ <p class="nhsuk-lede-text">This guide ships with the package, so it always describes the version you have installed.</p>
8
8
  <p class="knowledge-muted">@hippo-digital/hippocampus {{ packageVersion }}</p>
9
9
 
10
- <h2 class="nhsuk-heading-m">Guides</h2>
11
- <div class="knowledge-card-grid knowledge-card-grid--wide knowledge-card-grid--fill">
12
- {% for doc in docs %}
13
- <article class="knowledge-card knowledge-card--compact">
14
- <h3 class="nhsuk-heading-s nhsuk-u-margin-bottom-1">
15
- <a href="{{ basePath }}/docs/{{ doc.slug }}">{{ doc.title }}</a>
16
- </h3>
17
- {% if doc.summary %}<p class="nhsuk-body-s nhsuk-u-margin-bottom-0">{{ doc.summary }}</p>{% endif %}
18
- </article>
19
- {% endfor %}
20
- </div>
10
+ {#
11
+ Grouped by what the reader is trying to do, in reading order. Each guide
12
+ says where it belongs in front matter; one that does not lands in
13
+ Reference rather than disappearing.
14
+
15
+ The tags say who a page is written for - somebody looking at the viewer,
16
+ somebody running commands, or both. They label and never filter: a
17
+ reviewer who only uses the viewer still needs to be able to find the page
18
+ about where research data goes.
19
+ #}
20
+ {% if sections.length > 1 %}
21
+ <nav class="knowledge-doc-contents" aria-label="Parts of the guide">
22
+ <h2 class="nhsuk-heading-s nhsuk-u-margin-bottom-2">In this guide</h2>
23
+ <ul class="nhsuk-list">
24
+ {% for section in sections %}
25
+ <li class="nhsuk-u-margin-bottom-1"><a href="#section-{{ section.id }}">{{ section.title }}</a></li>
26
+ {% endfor %}
27
+ {% if templates.length %}<li class="nhsuk-u-margin-bottom-1"><a href="#templates">Templates to fill in</a></li>{% endif %}
28
+ </ul>
29
+ </nav>
30
+ {% endif %}
31
+
32
+ {% for section in sections %}
33
+ <h2 class="nhsuk-heading-m" id="section-{{ section.id }}">{{ section.title }}</h2>
34
+ <p class="knowledge-note">{{ section.description }}</p>
35
+ <div class="knowledge-card-grid knowledge-card-grid--wide knowledge-card-grid--fill nhsuk-u-margin-bottom-5">
36
+ {% for doc in section.docs %}
37
+ <article class="knowledge-card knowledge-card--compact">
38
+ <h3 class="nhsuk-heading-s nhsuk-u-margin-bottom-1">
39
+ <a href="{{ basePath }}/docs/{{ doc.slug }}">{{ doc.title }}</a>
40
+ </h3>
41
+ {% if doc.summary %}<p class="nhsuk-body-s nhsuk-u-margin-bottom-2">{{ doc.summary }}</p>{% endif %}
42
+ <p class="knowledge-doc-audience nhsuk-u-margin-bottom-0">
43
+ <span class="nhsuk-u-visually-hidden">Written for: </span>
44
+ {% for label in doc.audienceLabels %}<strong class="nhsuk-tag nhsuk-tag--white">{{ label }}</strong> {% endfor %}
45
+ </p>
46
+ </article>
47
+ {% endfor %}
48
+ </div>
49
+ {% endfor %}
21
50
 
22
51
  {#
23
52
  The blank workbooks, where somebody might find them.
@@ -29,7 +58,7 @@
29
58
  thing it would have prevented.
30
59
  #}
31
60
  {% if templates.length %}
32
- <h2 class="nhsuk-heading-m">Templates to fill in</h2>
61
+ <h2 class="nhsuk-heading-m" id="templates">Templates to fill in</h2>
33
62
  <p class="knowledge-note">
34
63
  Workbooks with the columns each importer expects. Fill one in, run the
35
64
  command underneath it, then check the draft before promoting it.
@@ -70,11 +70,16 @@
70
70
  </section>
71
71
  {% endfor %}
72
72
  {% else %}
73
+ {#
74
+ The first page a team sees after installing, so the commands here have to
75
+ be ones that exist in their prototype. This used to name `npm run`
76
+ scripts that only this repository and its demo ever had.
77
+ #}
73
78
  <section class="knowledge-section">
74
- <h2>No research rounds imported yet</h2>
75
- <p>Place PowerPoint or text-based PDF research artefacts in <code>hippocampus/inbox/research</code>, then run <code>npm run research:sync</code> to detect new files, create reviewable drafts and update the research manifest.</p>
76
- <p>The sync command reports fit warnings when the artefact does not expose participants, insights or design actions clearly, then asks before promoting imported drafts into source data.</p>
77
- <p>After review, check promotion with <code>npm run promote:research-draft -- --draft hippocampus/imports/research/round-id.json --dry-run</code>, then remove <code>--dry-run</code> to merge it into source data.</p>
79
+ <h2>No research rounds yet</h2>
80
+ <p>Put research files in <code>hippocampus/inbox/research/</code> - decks, PDFs, Word documents, spreadsheets or text notes - then run <code>npx hippocampus research sync</code>. Each file becomes a draft in <code>hippocampus/imports/research/</code>, and nothing appears on this page until a person has reviewed a draft and promoted it.</p>
81
+ <p>Check a reviewed draft with <code>npx hippocampus promote research --draft hippocampus/imports/research/&lt;draft&gt;.json --dry-run</code>, then run it again without <code>--dry-run</code>.</p>
82
+ <p><a href="{{ basePath }}/docs/import-a-research-round">How to import a research round</a></p>
78
83
  </section>
79
84
  {% endif %}
80
85
  {% endblock %}