@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
@@ -0,0 +1,206 @@
1
+ ---
2
+ section: start
3
+ order: 10
4
+ audience: [viewer, cli]
5
+ summary: What Hippocampus is and is not, how research moves through it, and how to get it running in a prototype.
6
+ ---
7
+ # Start here
8
+
9
+ Hippocampus keeps a design team's knowledge in one connected place: the
10
+ research a team has done, what it learned, the needs that came out of it, and
11
+ the journeys and screens built to meet them. Every record is linked to the
12
+ records it relies on, so you can follow a screen back to the research that
13
+ shaped it.
14
+
15
+ This page covers what Hippocampus is, how research moves through it, and how
16
+ to set it up. If you only ever look at the pages in a prototype and never run
17
+ commands, read the first three sections and skip to
18
+ [If you only use the viewer](#if-you-only-use-the-viewer).
19
+
20
+ ## What Hippocampus is
21
+
22
+ - **A structured record.** Users, needs, research rounds, insights, evidence,
23
+ scenarios, journeys, screens and decisions, each stored as data in the same
24
+ repository as your NHS Prototype Kit prototype.
25
+ - **A set of links between them.** A need says which evidence supports it. A
26
+ screen says which needs it meets. A decision says what it changed. That is
27
+ what lets you ask "why is this screen like this?" and get an answer.
28
+ - **A viewer.** Pages inside your prototype, at `/hippocampus`, that show the
29
+ records and the links between them. Nobody has to read the data files.
30
+ - **A set of commands and skills.** Commands bring research in and check the
31
+ record holds together. Skills are written instructions an AI agent follows
32
+ to do the longer jobs, such as tidying a research draft or turning a
33
+ scenario into a journey.
34
+
35
+ ## What it is not
36
+
37
+ - **Not where your research files live.** Your shared drive, or wherever your
38
+ team keeps research, stays the home of the original files. Hippocampus holds
39
+ what was learned from them and where it came from.
40
+ - **Not an analysis tool.** It does not decide which findings matter. People
41
+ do, and the record shows who decided and on what evidence.
42
+ - **Not automatic.** Nothing becomes part of the record until a person
43
+ approves it.
44
+ - **Not a hosted service.** It runs inside your prototype, on your machine,
45
+ like the rest of the prototype does.
46
+
47
+ ## How research moves through it
48
+
49
+ ![How evidence moves through Hippocampus: seven steps from inbox to viewer, with a person approving each draft before it becomes part of the record](images/evidence-flow.svg)
50
+
51
+ The list below describes the same steps.
52
+ [Open the diagram on its own](images/evidence-flow.svg) to see it full size.
53
+
54
+ 1. **Inbox.** You put research files in `hippocampus/inbox/research/`. Decks,
55
+ PDFs, Word documents, spreadsheets and plain text notes all work.
56
+ 2. **Import.** `npx hippocampus research sync` reads each new file on your
57
+ machine and writes a draft. Nothing is sent anywhere.
58
+ 3. **Draft.** The draft goes into `hippocampus/imports/research/`. It is a
59
+ machine's reading of a messy file, so nothing treats it as true yet.
60
+
61
+ *Optional:* an AI agent can tidy the draft using the
62
+ `structure-research-draft` skill. Whatever the agent reads is sent to that
63
+ agent's service. See [When anything leaves your machine](#when-anything-leaves-your-machine).
64
+ 4. **Review.** A person reads the draft. If it is not right, it goes back to be
65
+ fixed. The `review-research-import-draft` skill can help someone check it,
66
+ but it does not decide.
67
+ 5. **Promote.** A person runs `npx hippocampus promote research` for the draft
68
+ they reviewed. This is the only step that writes to the record, and nothing
69
+ runs it on its own.
70
+
71
+ `research sync` asks whether to promote straight after importing. The
72
+ answer defaults to no. Say no until someone has read the draft, and do not
73
+ use `--yes`, which promotes without asking.
74
+ 6. **Source.** Promoted records live in `hippocampus/source/`. This is the
75
+ record everything else is built from.
76
+ 7. **Viewer.** The pages at `/hippocampus` are built from `source/` each time
77
+ you load one, so a promoted change shows up when you refresh.
78
+
79
+ Alongside the viewer, skills that review or hand over work write their output
80
+ to `artefacts/`: route review packs, accessibility reviews and delivery
81
+ summaries. Nothing reads them back, so `artefacts/` is safe to delete.
82
+
83
+ ## If you only use the viewer
84
+
85
+ You can follow the evidence behind a prototype without running anything. The
86
+ pages below are under `/hippocampus` by default; your team may have mounted
87
+ the viewer somewhere else.
88
+
89
+ | To find out | Open |
90
+ | --- | --- |
91
+ | Where the work stands: rounds not yet mined, insights with no need, needs with no screen | `/hippocampus` |
92
+ | Why a screen is designed the way it is | `/hippocampus/trace`, then choose the screen |
93
+ | What depends on a piece of research | any evidence link on a need or user page, which opens its impact page |
94
+ | Every need, and what supports it | `/hippocampus/user-needs` |
95
+ | The journey being prototyped, and what it is built on | `/hippocampus/handover` |
96
+ | How the records connect | `/hippocampus/graph` |
97
+ | This guide | `/hippocampus/docs` |
98
+
99
+ A link that is missing in the viewer is a link missing in the record. Ask the
100
+ team to add it rather than drawing it in by hand somewhere else.
101
+
102
+ ## Set it up
103
+
104
+ ### Before you start
105
+
106
+ You need:
107
+
108
+ - an NHS Prototype Kit project, using `nhsuk-prototype-kit` 8.3.0 or later
109
+ - Node.js 22.16.0 or later
110
+
111
+ ### Install it
112
+
113
+ In your prototype's folder:
114
+
115
+ ```bash
116
+ npm install @hippo-digital/hippocampus
117
+ ```
118
+
119
+ ### Set up the knowledge base
120
+
121
+ See what would change first:
122
+
123
+ ```bash
124
+ npx hippocampus init --dry-run
125
+ ```
126
+
127
+ Then run it for real:
128
+
129
+ ```bash
130
+ npx hippocampus init
131
+ ```
132
+
133
+ This writes:
134
+
135
+ - `hippocampus.config.json`, which tells every command where your knowledge
136
+ base is
137
+ - `hippocampus/`, with an empty knowledge base and its `inbox/`, `imports/`
138
+ and `source/` folders
139
+ - `artefacts/`, with a short README in each folder
140
+
141
+ It also adds two short blocks to your prototype, one in `app/routes.js` and
142
+ one in `app.js`, so the viewer appears inside it. Both are marked, and
143
+ `npx hippocampus eject` takes them back out without touching your knowledge
144
+ base.
145
+
146
+ ### Check it worked
147
+
148
+ ```bash
149
+ npx hippocampus doctor
150
+ ```
151
+
152
+ The first line is the project folder it found. If that is wrong, nothing
153
+ after it will be right: run the command from inside your prototype, or pass
154
+ `--root <folder>`.
155
+
156
+ After that, `doctor` checks the config, the knowledge base, the two blocks in
157
+ your prototype and whether the records link up. Then it starts the prototype
158
+ and opens every page to make sure each one loads. A failed check says what went
159
+ wrong, and usually what to run next.
160
+
161
+ Start your prototype as you normally would and go to `/hippocampus`. An empty
162
+ knowledge base still shows every page, and tells you what to add next.
163
+
164
+ ### If your team uses an AI agent
165
+
166
+ ```bash
167
+ npx hippocampus skills install
168
+ ```
169
+
170
+ This copies the skills, agent roles and instructions into `.github/` in your
171
+ prototype, where agents such as GitHub Copilot read them. Run it again after
172
+ upgrading Hippocampus; it leaves alone any file your team has edited and tells
173
+ you which.
174
+
175
+ ## When anything leaves your machine
176
+
177
+ - **The `hippocampus` commands send nothing anywhere.** Importing reads PDFs,
178
+ Word, PowerPoint and Excel files on your machine. Apart from the optional
179
+ Gemini tool below, the only network request any command makes is `doctor`
180
+ opening your own prototype's pages.
181
+ - **Skills are carried out by an AI agent, and what the agent reads goes to
182
+ its service.** If you point a skill at a research transcript, that
183
+ transcript is sent to whichever service runs the agent. Agree with your
184
+ information governance lead which agents may read which material before the
185
+ first research file goes into the inbox. The same applies to any agent
186
+ connected to `hippocampus mcp`, which hands it the knowledge base.
187
+ - **One optional tool calls Google Gemini.** `hippocampus mcp` serves the
188
+ knowledge base to agents. One of its tools, `design_brain_ask`, sends the
189
+ question and the parts of the knowledge base it looks up to Gemini. It is
190
+ off unless someone sets `GEMINI_API_KEY` and `DESIGN_BRAIN_MODEL` and
191
+ installs `@google/genai`. The rest of `hippocampus mcp` uses no model.
192
+
193
+ ## What to read next
194
+
195
+ - [Ask what's already known](ask-whats-already-known.md): check what the team
196
+ already knows before you research or design something
197
+ - [Import a research round](import-a-research-round.md) and
198
+ [Review a draft and promote it](review-and-promote-a-draft.md): bring a
199
+ round of research in, steps 1 to 6 above
200
+ - [Hippocampus for designers and researchers](hippocampus-for-designers-and-researchers.md):
201
+ the record types and viewer pages in more detail
202
+ - [Research source file conventions](research-source-file-conventions.md):
203
+ how to write research files so they import cleanly
204
+ - [Repeatable research round ingestion](repeatable-research-round-ingestion.md):
205
+ the full import and promotion procedure
206
+ - [Source model](source-model.md): every record type and its fields
@@ -1,7 +1,7 @@
1
1
  const express = require('express')
2
2
  const path = require('path')
3
3
  const packagePaths = require('./package-paths')
4
- const { listDocs, readDoc, packageVersion } = require('./docs')
4
+ const { listDocSections, readDoc, docImagePath, packageVersion } = require('./docs')
5
5
  const { listTemplates, allTemplates } = require('./templates')
6
6
  const { hrefFor, listHrefFor } = require('./record-links')
7
7
  const { matchesText, facet, matchesFacet, queryWithout } = require('./filter')
@@ -377,7 +377,7 @@ function createHippocampusRouter ({ basePath, knowledgeStore, paths }) {
377
377
  // so what a team reads always matches the version they are running.
378
378
  router.get('/docs', (req, res) => {
379
379
  res.render('hippocampus/docs', {
380
- docs: listDocs(),
380
+ sections: listDocSections(),
381
381
  templates: listTemplates(paths),
382
382
  packageVersion: packageVersion()
383
383
  })
@@ -393,10 +393,33 @@ function createHippocampusRouter ({ basePath, knowledgeStore, paths }) {
393
393
  res.download(template.path, template.file)
394
394
  })
395
395
 
396
+ // Diagrams the guides embed, from the package like the guides themselves.
397
+ // docImagePath only answers for a plain name already in docs/images. The CSP
398
+ // is because an SVG opened on its own is a document that can run script:
399
+ // these are the package's own files, but the header costs nothing and means a
400
+ // diagram can only ever be a picture.
401
+ router.get('/docs/images/:file', (req, res) => {
402
+ const file = docImagePath(req.params.file)
403
+ if (!file) return res.status(404).render('hippocampus/not-found')
404
+ res.set('X-Content-Type-Options', 'nosniff')
405
+ res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'")
406
+ res.sendFile(file)
407
+ })
408
+
409
+ // A guide sits under its section in the trail, so a reader who arrived from a
410
+ // link elsewhere can see which part of the guide they are in and get back to
411
+ // the rest of it. Not when the two share a name: "Start here > Start here"
412
+ // reads as a mistake, and the section adds nothing the page title does not.
396
413
  router.get('/docs/:slug', (req, res) => {
397
414
  const doc = readDoc(req.params.slug)
398
415
  if (!doc) return res.status(404).render('hippocampus/not-found')
399
- withLeaf(res, req, doc.title)
416
+ const section = { text: doc.sectionTitle, href: `${basePath}/docs#section-${doc.section}` }
417
+ res.locals.breadcrumbItems = buildTrail({
418
+ basePath,
419
+ path: req.path,
420
+ leaf: doc.title,
421
+ crumbs: doc.sectionTitle === doc.title ? [] : [section]
422
+ })
400
423
  res.render('hippocampus/doc', { doc, packageVersion: packageVersion() })
401
424
  })
402
425
 
package/lib/docs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
- const { marked } = require('marked')
3
+ const { Marked } = require('marked')
4
4
  const packagePaths = require('./package-paths')
5
5
 
6
6
  // Docs are served, not copied.
@@ -14,58 +14,316 @@ const packagePaths = require('./package-paths')
14
14
  // `hippocampus skills install` copies them, with hashes so an upgrade can tell
15
15
  // a stale copy from an edited one.
16
16
 
17
- const TITLE_OVERRIDES = {
18
- 'hippocampus-for-designers-and-researchers': 'Hippocampus for designers and researchers'
19
- }
17
+ // The guide is grouped for the people reading it, not by filename. Each doc
18
+ // says where it belongs in front matter at its top:
19
+ //
20
+ // ---
21
+ // title: Ingest a research round
22
+ // section: recipes
23
+ // order: 20
24
+ // audience: [viewer, cli]
25
+ // summary: Take a deck or a transcript from the inbox to a reviewed draft.
26
+ // ---
27
+ //
28
+ // Every key is optional, and every default is what the list did before front
29
+ // matter existed. A doc nobody has migrated still appears - in Reference,
30
+ // titled by its first heading - rather than vanishing because it did not say
31
+ // where it goes.
32
+ const SECTIONS = [
33
+ {
34
+ id: 'start',
35
+ title: 'Start here',
36
+ description: 'What Hippocampus is, how evidence moves through it, and how to get it running.'
37
+ },
38
+ {
39
+ id: 'recipes',
40
+ title: 'Task recipes',
41
+ description: 'One page per job. Each says what you will see in the viewer and what someone runs to get there.'
42
+ },
43
+ {
44
+ id: 'governance',
45
+ title: 'Data and governance',
46
+ description: 'Where research data goes, who approves it, and when anything leaves the machine.'
47
+ },
48
+ {
49
+ id: 'reference',
50
+ title: 'Reference',
51
+ description: 'Record shapes, file conventions and the detail the recipes link to.'
52
+ },
53
+ {
54
+ id: 'contributors',
55
+ title: 'For contributors',
56
+ description: 'How the package works inside, and how agents are set up to work on it.'
57
+ }
58
+ ]
59
+
60
+ const DEFAULT_SECTION = 'reference'
61
+ const DEFAULT_ORDER = 999
62
+
63
+ // Who a page is written for. A label, never a filter: hiding a page from
64
+ // somebody because of who we guessed they were is how a reviewer ends up
65
+ // unable to find the governance page.
66
+ const AUDIENCES = { viewer: 'Viewer', cli: 'Command line' }
67
+
68
+ const IMAGE_PATTERN = /^[a-z0-9-]+\.(svg|png)$/
20
69
 
21
70
  function slugOf (filename) {
22
71
  return filename.replace(/\.md$/, '')
23
72
  }
24
73
 
25
- function titleOf (filename, contents) {
26
- const slug = slugOf(filename)
27
- if (TITLE_OVERRIDES[slug]) return TITLE_OVERRIDES[slug]
28
- const heading = contents.match(/^#\s+(.+)$/m)
29
- if (heading) return heading[1].trim()
30
- return slug.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase())
74
+ // Deliberately small. Front matter here is five flat keys, and a YAML parser
75
+ // would be a seventh dependency to read them.
76
+ //
77
+ // It is also strict about what counts as front matter at all: a block whose
78
+ // lines are not all `key: value`, `key: [a, b]`, a `- item` under a bare key,
79
+ // a comment or blank is left in the body untouched. A doc that happens to open
80
+ // with a horizontal rule must not lose its first paragraph to a parser that
81
+ // guessed - and a malformed block that renders on the page is a mistake its
82
+ // author will see, where one silently dropped is not.
83
+ function parseFrontMatter (contents) {
84
+ const match = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/.exec(contents)
85
+ if (!match) return { data: {}, body: contents }
86
+
87
+ const data = {}
88
+ let listKey = null
89
+
90
+ for (const line of (match[1] || '').split(/\r?\n/)) {
91
+ if (!line.trim() || /^\s*#/.test(line)) continue
92
+
93
+ const item = /^\s+-\s+(.*)$/.exec(line)
94
+ if (item && listKey) {
95
+ data[listKey].push(unquote(withoutComment(item[1])))
96
+ continue
97
+ }
98
+
99
+ const pair = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line)
100
+ if (!pair) return { data: {}, body: contents }
101
+
102
+ const key = pair[1]
103
+ const raw = withoutComment(pair[2])
104
+ const list = /^\[(.*)\]$/.exec(raw)
105
+ if (list) {
106
+ data[key] = list[1].split(',').map(unquote).filter(Boolean)
107
+ listKey = null
108
+ } else if (!raw.trim()) {
109
+ data[key] = []
110
+ listKey = key
111
+ } else {
112
+ data[key] = unquote(raw)
113
+ listKey = null
114
+ }
115
+ }
116
+
117
+ return { data, body: contents.slice(match[0].length) }
31
118
  }
32
119
 
33
- function summaryOf (contents) {
34
- const body = contents.replace(/^#\s+.+$/m, '').trim()
35
- const paragraph = body.split(/\n\s*\n/).find((block) => block.trim() && !block.trim().startsWith('#'))
120
+ // YAML's rule: a # after whitespace starts a comment, unless it is inside
121
+ // quotes. Without this, `section: recipes # where it goes` is an unknown
122
+ // section, and the guide quietly moves to Reference.
123
+ function withoutComment (raw) {
124
+ const value = raw.trim()
125
+ const quoted = /^(['"])(.*?)\1\s*(?:#.*)?$/.exec(value)
126
+ if (quoted) return `${quoted[1]}${quoted[2]}${quoted[1]}`
127
+ return value.replace(/\s+#.*$/, '')
128
+ }
129
+
130
+ function unquote (value) {
131
+ const trimmed = String(value).trim()
132
+ const quoted = /^(['"])(.*)\1$/.exec(trimmed)
133
+ return quoted ? quoted[2] : trimmed
134
+ }
135
+
136
+ function text (value) {
137
+ return typeof value === 'string' && value.trim() ? value.trim() : ''
138
+ }
139
+
140
+ function headingOf (body) {
141
+ const heading = body.match(/^#\s+(.+)$/m)
142
+ return heading ? heading[1].trim() : ''
143
+ }
144
+
145
+ function summaryOf (body) {
146
+ const rest = body.replace(/^#\s+.+$/m, '').trim()
147
+ const paragraph = rest.split(/\n\s*\n/).find((block) => block.trim() && !block.trim().startsWith('#'))
36
148
  if (!paragraph) return ''
37
- const text = paragraph.replace(/\s+/g, ' ').replace(/[*_`[\]]/g, '').trim()
38
- return text.length > 200 ? `${text.slice(0, 197)}...` : text
149
+ const plain = paragraph.replace(/\s+/g, ' ').replace(/[*_`[\]]/g, '').trim()
150
+ return plain.length > 200 ? `${plain.slice(0, 197)}...` : plain
151
+ }
152
+
153
+ function orderOf (value) {
154
+ return /^-?\d+$/.test(text(value)) ? Number(value) : DEFAULT_ORDER
155
+ }
156
+
157
+ // Everything the list and the page need from one file, with front matter
158
+ // already taken off. The body is the only thing that reaches marked, the title
159
+ // finder and the summary finder - front matter that got as far as any of them
160
+ // would render as a stray paragraph at the top of every guide, and become the
161
+ // summary on every card.
162
+ function describe (filename, contents) {
163
+ const slug = slugOf(filename)
164
+ const { data, body } = parseFrontMatter(contents)
165
+
166
+ const section = SECTIONS.some((candidate) => candidate.id === text(data.section))
167
+ ? text(data.section)
168
+ : DEFAULT_SECTION
169
+
170
+ const declared = [].concat(data.audience || []).filter((value) => AUDIENCES[value])
171
+ const audience = declared.length ? [...new Set(declared)] : Object.keys(AUDIENCES)
172
+
173
+ return {
174
+ slug,
175
+ title: text(data.title) || headingOf(body) || slug.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase()),
176
+ summary: text(data.summary) || summaryOf(body),
177
+ section,
178
+ order: orderOf(data.order),
179
+ audience,
180
+ audienceLabels: audience.map((value) => AUDIENCES[value]),
181
+ body
182
+ }
183
+ }
184
+
185
+ function sectionIndex (id) {
186
+ return SECTIONS.findIndex((section) => section.id === id)
187
+ }
188
+
189
+ function byPlace (a, b) {
190
+ return sectionIndex(a.section) - sectionIndex(b.section) ||
191
+ a.order - b.order ||
192
+ a.title.localeCompare(b.title)
39
193
  }
40
194
 
41
- function listDocs () {
42
- if (!fs.existsSync(packagePaths.docsDir)) return []
43
- return fs.readdirSync(packagePaths.docsDir)
195
+ function summaryFields ({ body, ...rest }) {
196
+ return rest
197
+ }
198
+
199
+ // Flat, in reading order: Start here first, contributors last. The smoke test
200
+ // only wants slugs from this, so it stays flat rather than learning sections.
201
+ function listDocs (docsDir = packagePaths.docsDir) {
202
+ if (!fs.existsSync(docsDir)) return []
203
+ return fs.readdirSync(docsDir)
44
204
  .filter((name) => name.endsWith('.md'))
45
- .sort()
46
- .map((name) => {
47
- const contents = fs.readFileSync(path.join(packagePaths.docsDir, name), 'utf8')
48
- return { slug: slugOf(name), title: titleOf(name, contents), summary: summaryOf(contents) }
49
- })
205
+ .map((name) => summaryFields(describe(name, fs.readFileSync(path.join(docsDir, name), 'utf8'))))
206
+ .sort(byPlace)
207
+ }
208
+
209
+ // Sections with nothing in them are left out. An empty heading on the list
210
+ // reads as "this part of the guide is missing", which until it is written it
211
+ // is - but the list is not the place to say so.
212
+ function listDocSections (docsDir = packagePaths.docsDir) {
213
+ const docs = listDocs(docsDir)
214
+ return SECTIONS
215
+ .map((section) => ({ ...section, docs: docs.filter((doc) => doc.section === section.id) }))
216
+ .filter((section) => section.docs.length)
50
217
  }
51
218
 
52
- function readDoc (slug) {
219
+ function readDoc (slug, docsDir = packagePaths.docsDir) {
53
220
  // The slug comes off a URL, so it is checked against the directory listing
54
221
  // rather than joined onto a path and hoped for.
55
222
  if (!/^[a-z0-9-]+$/.test(slug)) return null
56
- const filePath = path.join(packagePaths.docsDir, `${slug}.md`)
223
+ const filePath = path.join(docsDir, `${slug}.md`)
57
224
  if (!fs.existsSync(filePath)) return null
58
225
 
59
- const contents = fs.readFileSync(filePath, 'utf8')
226
+ const doc = describe(`${slug}.md`, fs.readFileSync(filePath, 'utf8'))
227
+ const all = listDocs(docsDir)
228
+ const at = all.findIndex((candidate) => candidate.slug === slug)
229
+ const section = SECTIONS.find((candidate) => candidate.id === doc.section)
230
+
60
231
  return {
61
- slug,
62
- title: titleOf(`${slug}.md`, contents),
63
- html: marked(contents, { mangle: false, headerIds: true })
232
+ ...summaryFields(doc),
233
+ sectionTitle: section.title,
234
+ html: renderMarkdown(doc.body),
235
+ // Reading order runs across sections on purpose: the page after Start here
236
+ // is the first recipe, not nothing.
237
+ previous: at > 0 ? pageLink(all[at - 1]) : null,
238
+ next: at >= 0 && at < all.length - 1 ? pageLink(all[at + 1]) : null
64
239
  }
65
240
  }
66
241
 
242
+ function pageLink (doc) {
243
+ return { slug: doc.slug, title: doc.title }
244
+ }
245
+
246
+ // Diagrams the guides embed. Only files that are in docs/images, only by a
247
+ // name that is just a slug and an image extension: a URL segment is never
248
+ // joined onto a path until it has matched an entry in the directory listing.
249
+ function docImagePath (file, docsDir = packagePaths.docsDir) {
250
+ if (!IMAGE_PATTERN.test(file || '')) return null
251
+ const imagesDir = path.join(docsDir, 'images')
252
+ if (!fs.existsSync(imagesDir)) return null
253
+ if (!fs.readdirSync(imagesDir).includes(file)) return null
254
+ return path.join(imagesDir, file)
255
+ }
256
+
257
+ function listDocImages (docsDir = packagePaths.docsDir) {
258
+ const imagesDir = path.join(docsDir, 'images')
259
+ if (!fs.existsSync(imagesDir)) return []
260
+ return fs.readdirSync(imagesDir).filter((name) => IMAGE_PATTERN.test(name)).sort()
261
+ }
262
+
263
+ // Markdown to HTML, with two things marked no longer does on its own.
264
+ //
265
+ // Heading ids. `headerIds: true` was passed here for as long as this file has
266
+ // existed, but marked dropped that option in v8 and ignores it, so no heading
267
+ // in any guide had an id and no link to part of a guide could work. The ids
268
+ // follow GitHub's rule - lower case, punctuation dropped, spaces to hyphens,
269
+ // repeats numbered - so one link works in the viewer and on GitHub alike.
270
+ //
271
+ // Links between guides. They are written `source-model.md`, which is right on
272
+ // GitHub and in an editor, and a 404 in the viewer, where the page is
273
+ // `docs/source-model`. Only a bare sibling `.md` is rewritten; anything with a
274
+ // scheme, a leading slash or a directory is left as it was written.
275
+ function renderMarkdown (body) {
276
+ const seen = new Map()
277
+ const md = new Marked({
278
+ walkTokens (token) {
279
+ if (token.type === 'link') token.href = docHref(token.href)
280
+ },
281
+ renderer: {
282
+ heading ({ tokens, depth }) {
283
+ const inner = this.parser.parseInline(tokens)
284
+ const id = uniqueId(seen, headingId(inner))
285
+ return `<h${depth} id="${id}">${inner}</h${depth}>\n`
286
+ }
287
+ }
288
+ })
289
+ return md.parse(body)
290
+ }
291
+
292
+ function docHref (href) {
293
+ const match = /^(?:\.\/)?([a-z0-9-]+)\.md(#[^\s]*)?$/.exec(href || '')
294
+ return match ? `${match[1]}${match[2] || ''}` : href
295
+ }
296
+
297
+ function headingId (html) {
298
+ return html
299
+ .replace(/<[^>]*>/g, '')
300
+ .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
301
+ .replace(/&quot;/g, '"').replace(/&#39;/g, "'")
302
+ .toLowerCase()
303
+ .trim()
304
+ .replace(/[^\p{L}\p{N}\s_-]/gu, '')
305
+ .replace(/\s/g, '-')
306
+ }
307
+
308
+ function uniqueId (seen, base) {
309
+ const id = base || 'section'
310
+ const count = seen.get(id) || 0
311
+ seen.set(id, count + 1)
312
+ return count ? `${id}-${count}` : id
313
+ }
314
+
67
315
  function packageVersion () {
68
316
  return require('../package.json').version
69
317
  }
70
318
 
71
- module.exports = { listDocs, readDoc, packageVersion }
319
+ module.exports = {
320
+ SECTIONS,
321
+ listDocs,
322
+ listDocSections,
323
+ readDoc,
324
+ docImagePath,
325
+ listDocImages,
326
+ parseFrontMatter,
327
+ renderMarkdown,
328
+ packageVersion
329
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "2.4.0",
3
+ "version": "2.5.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",