@hippo-digital/hippocampus 1.0.0-rc.3 → 1.0.0-rc.5

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/CHANGELOG.md CHANGED
@@ -30,12 +30,50 @@ journeys and screens they justify, rendered as a viewer inside your prototype.
30
30
  - Commands that need a knowledge base refuse when none is found and say where
31
31
  they looked, rather than exiting 0 having done nothing.
32
32
 
33
+ ### A fresh install
34
+
35
+ - `init` writes the thirteen collection files as empty arrays. The loader
36
+ already treated a missing file as empty, so the viewer ran without them, but
37
+ every skill declares the files it reads and an absent file failed that check
38
+ in a project whose only fault was being new.
39
+ - The directories it scaffolds each carry a `.gitkeep`. Git does not track an
40
+ empty directory, so without one the scaffold vanished on the next clone and
41
+ the skills reading from it failed for reasons invisible in the working copy.
42
+ - Directories are scaffolded on every run, not only the first. A project
43
+ initialised before a directory existed never gained it otherwise.
44
+
45
+ ### The stock Prototype Kit
46
+
47
+ Tested against a real kit cloned from `nhsuk/nhsuk-prototype-kit`, which found
48
+ three things the release gate's hand-written stand-in could not.
49
+
50
+ - `doctor`'s route check follows the URL the app announces. A stock kit takes
51
+ its port from `app/config.js` and ignores `PORT`, so the check timed out and
52
+ `doctor` reported a problem on a brand new install where nothing was wrong.
53
+ - `eject` removes the `viewsPath` entry from `app.js` itself, restoring both
54
+ host files to exactly what they were before `init`. It used to remove the
55
+ `routes.js` block, ask for the `app.js` entry by hand and exit non-zero -
56
+ an automatic edit that could only be undone manually.
57
+ - The gate's scratch project is now a faithful copy of a stock kit: two plain
58
+ string arrays in `app.js` rather than one, the port in `app/config.js`, a
59
+ `.github` holding only workflows. `skills install` creates its three
60
+ directories beside them without disturbing them.
61
+
62
+ The viewer's landing page no longer captions itself "Prototype Kit add-on
63
+ spike", which was a development-era label every install would have seen.
64
+
33
65
  ### Validation
34
66
 
35
67
  - Three tiers: errors are broken references, warnings are gaps worth filling,
36
68
  info is coverage. `--strict` promotes warnings to failures.
37
69
  - `doctor` checks wiring, integrity and every route, and prints the resolved
38
70
  root first.
71
+ - `skills validate` resolves the project to check against the same way every
72
+ other command does. It previously defaulted to a path relative to its own
73
+ location that only existed in this monorepo, so in an installed package it
74
+ pointed at `<host>/node_modules/apps/demo` and failed every check. The
75
+ release gate now runs shipped commands against a real install rather than
76
+ only checking that they load, which is what let this through.
39
77
 
40
78
  ### Data contract
41
79
 
@@ -56,6 +94,11 @@ journeys and screens they justify, rendered as a viewer inside your prototype.
56
94
  into `.github/skills` and every skill names its `owners` by agent, so either
57
95
  half alone is a set of dangling references. `--no-agents` installs the skills
58
96
  only.
97
+ - A file that already exists in the host and was not written by this command is
98
+ left exactly as it is and named in the output. Only files it had written
99
+ before were protected previously, which is backwards for the first install
100
+ into a repo that already has its own agents - the repo most likely to have
101
+ some. `--force` still overwrites, and now says what that would cost.
59
102
  - Everything the agents and skills reference that is not a repo file is read
60
103
  from the installed package, so those references are version-matched too.
61
104
  - `skills validate` checks both directions between skills and agents: a skill
package/lib/host-edit.js CHANGED
@@ -128,6 +128,36 @@ function addToStringArray (source, { name, entry }) {
128
128
  return { action: 'updated', source: source.replace(full, replacement) }
129
129
  }
130
130
 
131
+ /**
132
+ * The inverse of addToStringArray, held to the same standard: act only on an
133
+ * unambiguous single match, otherwise say so and change nothing.
134
+ *
135
+ * Without this, `init` added the viewsPath entry automatically and `eject`
136
+ * asked for it back by hand and exited non-zero - so undoing an automatic edit
137
+ * was a manual step that looked like a failure. An edit this package made is an
138
+ * edit it should be able to take back.
139
+ */
140
+ function removeFromStringArray (source, { name, entry }) {
141
+ if (!source.includes(entry)) return { action: 'unchanged', source }
142
+
143
+ const pattern = new RegExp(`(const\\s+${name}\\s*=\\s*\\[)([^\\]]*)\\]`, 'g')
144
+ const matches = [...source.matchAll(pattern)]
145
+ if (matches.length !== 1) {
146
+ return { action: 'no-anchor', reason: `Expected exactly one \`const ${name} = [...]\`, found ${matches.length}.` }
147
+ }
148
+
149
+ const [full, open, inner] = matches[0]
150
+ if (!inner.includes(entry)) {
151
+ return { action: 'no-anchor', reason: `The entry is in app.js but not inside \`${name}\`.` }
152
+ }
153
+
154
+ const indent = (inner.match(/\n(\s+)/) || [, ' '])[1]
155
+ const kept = inner.split(',').map((item) => item.trim()).filter(Boolean).filter((item) => item !== entry)
156
+ const body = kept.length ? `\n${indent}${kept.join(`,\n${indent}`)}\n` : '\n'
157
+
158
+ return { action: 'updated', source: source.replace(full, `${open}${body}]`) }
159
+ }
160
+
131
161
  function backup (filePath) {
132
162
  const backupPath = `${filePath}.hippocampus-backup`
133
163
  if (!fs.existsSync(backupPath)) fs.copyFileSync(filePath, backupPath)
@@ -148,4 +178,4 @@ function diff (before, after, filePath) {
148
178
  return out.join('\n')
149
179
  }
150
180
 
151
- module.exports = { upsertBlock, removeBlock, addToStringArray, findBlock, hashBody, backup, diff }
181
+ module.exports = { upsertBlock, removeBlock, addToStringArray, removeFromStringArray, findBlock, hashBody, backup, diff }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "1.0.0-rc.3",
3
+ "version": "1.0.0-rc.5",
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",
package/scripts/eject.js CHANGED
@@ -2,12 +2,14 @@
2
2
  const fs = require('fs')
3
3
  const path = require('path')
4
4
  const { resolveRoot } = require('../lib/resolve-root')
5
- const { removeBlock } = require('../lib/host-edit')
5
+ const { removeBlock, removeFromStringArray, backup } = require('../lib/host-edit')
6
6
 
7
7
  // Removes the host edits and nothing else. All data stays: the knowledge base
8
8
  // is the team's work, not this package's, and a command that deletes it because
9
9
  // somebody wanted to stop using the viewer would be indefensible.
10
10
 
11
+ const APP_VIEWS_ENTRY = "require('@hippo-digital/hippocampus').createHippocampus().viewsPath"
12
+
11
13
  const argv = process.argv.slice(2)
12
14
  const dryRun = argv.includes('--dry-run')
13
15
 
@@ -31,9 +33,22 @@ function main () {
31
33
  const appPath = path.join(root, 'app.js')
32
34
  if (fs.existsSync(appPath)) {
33
35
  const source = fs.readFileSync(appPath, 'utf8')
34
- if (source.includes('@hippo-digital/hippocampus')) {
35
- console.log('\napp.js still references the package. Remove the viewsPath entry by hand:')
36
- console.log(" require('@hippo-digital/hippocampus').createHippocampus().viewsPath")
36
+ const result = removeFromStringArray(source, { name: 'viewsPath', entry: APP_VIEWS_ENTRY })
37
+
38
+ if (result.action === 'updated') {
39
+ changed++
40
+ console.log(`${dryRun ? 'would remove' : 'removed'} the viewsPath entry from app.js`)
41
+ if (!dryRun) {
42
+ backup(appPath)
43
+ fs.writeFileSync(appPath, result.source)
44
+ }
45
+ } else if (result.action === 'no-anchor') {
46
+ console.log(`\napp.js could not be edited automatically: ${result.reason}`)
47
+ console.log('Remove this entry by hand:')
48
+ console.log(` ${APP_VIEWS_ENTRY}`)
49
+ } else if (source.includes('@hippo-digital/hippocampus')) {
50
+ console.log('\napp.js still references the package somewhere other than viewsPath.')
51
+ console.log('Check it by hand before uninstalling.')
37
52
  }
38
53
  }
39
54
 
package/scripts/init.js CHANGED
@@ -37,6 +37,7 @@ function main () {
37
37
  console.log(`Resolved from: ${source}\n`)
38
38
 
39
39
  planConfig(root)
40
+ planKnowledgeDirs(root)
40
41
  planKnowledgeBase(root)
41
42
  planArtefacts(root, artefactsDir(root))
42
43
  planArtefactGovernance(root)
@@ -125,6 +126,41 @@ function listTemplateFiles (dir, prefix = '') {
125
126
  return found
126
127
  }
127
128
 
129
+ // The directories the skills read from, scaffolded on every run rather than
130
+ // only on a first install. A project initialised before a directory existed
131
+ // never got it otherwise - which is how a knowledge base ends up missing
132
+ // `inbox/personas` and the persona skill fails its own `reads:` check.
133
+ //
134
+ // Each carries a .gitkeep. Git does not track an empty directory, so without
135
+ // one the scaffold is gone the moment somebody clones the repo, and the skills
136
+ // that read from it fail for reasons nobody can see in the working copy they
137
+ // are looking at.
138
+ const EMPTY_COLLECTIONS = [
139
+ 'users', 'needs', 'scenarios', 'journeys', 'screens', 'evidence', 'decisions',
140
+ 'assumptions', 'research-rounds', 'participants', 'insights', 'design-actions',
141
+ 'relationships'
142
+ ]
143
+
144
+ const KNOWLEDGE_DIRS = [
145
+ 'source', 'inbox/personas', 'inbox/project', 'inbox/research',
146
+ 'imports/project', 'imports/research', 'manifests'
147
+ ]
148
+
149
+ function planKnowledgeDirs (root) {
150
+ const missing = KNOWLEDGE_DIRS.filter((dir) => !fs.existsSync(path.join(root, 'hippocampus', dir)))
151
+ if (!missing.length) return
152
+
153
+ plan(`hippocampus/: ${missing.length} ${missing.length === 1 ? 'directory' : 'directories'} (${missing.join(', ')})`, () => {
154
+ for (const dir of missing) {
155
+ const target = path.join(root, 'hippocampus', dir)
156
+ fs.mkdirSync(target, { recursive: true })
157
+ // `source` always receives project.json and _meta.json, so it is never
158
+ // the empty directory this guards against.
159
+ if (dir !== 'source') fs.writeFileSync(path.join(target, '.gitkeep'), '')
160
+ }
161
+ })
162
+ }
163
+
128
164
  function planKnowledgeBase (root) {
129
165
  const sourceDir = path.join(root, 'hippocampus/source')
130
166
  const projectPath = path.join(sourceDir, 'project.json')
@@ -137,9 +173,7 @@ function planKnowledgeBase (root) {
137
173
  const id = kebab(dirName) || 'prototype'
138
174
  const name = dirName
139
175
  plan('hippocampus/source/project.json and an empty knowledge base', () => {
140
- for (const dir of ['source', 'inbox/personas', 'inbox/project', 'inbox/research', 'imports/project', 'imports/research', 'manifests']) {
141
- fs.mkdirSync(path.join(root, 'hippocampus', dir), { recursive: true })
142
- }
176
+ fs.mkdirSync(sourceDir, { recursive: true })
143
177
  fs.writeFileSync(projectPath, JSON.stringify({
144
178
  id: `${id}-knowledge`,
145
179
  name,
@@ -153,6 +187,15 @@ function planKnowledgeBase (root) {
153
187
  generator: 'hippocampus init',
154
188
  updatedAt: new Date().toISOString()
155
189
  }, null, 2) + '\n')
190
+
191
+ // The loader treats a missing collection as empty, so the viewer runs
192
+ // without these. The skills do not: every one declares the files it reads,
193
+ // and a file that is absent rather than empty fails that check in a project
194
+ // that is simply new. Writing them also shows someone opening the directory
195
+ // what the knowledge base is made of, which an empty folder does not.
196
+ for (const collection of EMPTY_COLLECTIONS) {
197
+ fs.writeFileSync(path.join(sourceDir, `${collection}.json`), '[]\n')
198
+ }
156
199
  })
157
200
  }
158
201
 
@@ -61,6 +61,7 @@ function main () {
61
61
  const trees = TREES.filter((tree) => tree.key === 'files' || withAgents)
62
62
  let wroteAnything = false
63
63
  let anySkipped = false
64
+ let anyForeign = false
64
65
 
65
66
  for (const tree of trees) {
66
67
  manifest[tree.key] = manifest[tree.key] || {}
@@ -79,6 +80,11 @@ function main () {
79
80
  console.log(` left alone because they have been edited here (${result.skipped.length}):`)
80
81
  for (const name of result.skipped) console.log(` ${name}`)
81
82
  }
83
+ if (result.foreign.length) {
84
+ anyForeign = true
85
+ console.log(` already yours, not written (${result.foreign.length}):`)
86
+ for (const name of result.foreign) console.log(` ${name}`)
87
+ }
82
88
 
83
89
  if (tree.key === 'files') {
84
90
  const merged = mergeCatalog(skillsTarget, manifest)
@@ -99,6 +105,12 @@ function main () {
99
105
  console.log('Re-install edited files with --force once you have kept whatever you changed.\n')
100
106
  }
101
107
 
108
+ if (anyForeign) {
109
+ console.log('The files listed as already yours share a name with ours but were not')
110
+ console.log('written by this command, so they have been left exactly as they are.')
111
+ console.log('`--force` would overwrite them - copy anything you want to keep first.\n')
112
+ }
113
+
102
114
  if (!dryRun && wroteAnything) {
103
115
  manifest.version = require('../package.json').version
104
116
  manifest.updatedAt = new Date().toISOString()
@@ -118,6 +130,7 @@ function installTree (sourceDir, targetDir, manifestFiles) {
118
130
  const skipped = []
119
131
  const unchanged = []
120
132
  const kept = []
133
+ const foreign = []
121
134
 
122
135
  for (const name of fs.readdirSync(sourceDir)) {
123
136
  if (name === 'skills.json' || !/\.(skill\.md|md|json)$/.test(name)) continue
@@ -131,6 +144,14 @@ function installTree (sourceDir, targetDir, manifestFiles) {
131
144
  if (current === incoming) { unchanged.push(name); continue }
132
145
  if (NEVER_OVERWRITE.has(name)) { kept.push(name); continue }
133
146
  const installed = manifestFiles[name]
147
+
148
+ // A file we have no record of writing is the host's, not a stale copy of
149
+ // ours that happens to share a name. The hash check above only ever
150
+ // protected files we had written before, which is backwards for the case
151
+ // that matters: the FIRST install into a repo that already has its own
152
+ // agents. Getting this wrong overwrites work nobody had a copy of.
153
+ if (!installed && !force) { foreign.push(name); continue }
154
+
134
155
  if (installed && current !== installed && !force) { skipped.push(name); continue }
135
156
  }
136
157
 
@@ -142,7 +163,7 @@ function installTree (sourceDir, targetDir, manifestFiles) {
142
163
  manifestFiles[name] = incoming
143
164
  }
144
165
 
145
- return { written, skipped, unchanged, kept }
166
+ return { written, skipped, unchanged, kept, foreign }
146
167
  }
147
168
 
148
169
  /**
@@ -4,7 +4,13 @@ const { listDocs } = require('../lib/docs')
4
4
  const ctx = createContextOrExit()
5
5
 
6
6
  const port = process.env.SMOKE_PORT || 4587
7
- const baseUrl = `http://127.0.0.1:${port}`
7
+ // Mutable, because the port we ask for is not always the port the app uses.
8
+ // The stock NHS Prototype Kit reads its port from `app/config.js`, where it is
9
+ // hardcoded to 3000, and ignores PORT entirely - so on a brand new kit this
10
+ // check failed and `doctor` reported a problem on an install where nothing was
11
+ // wrong. The app announces the URL it is actually on; believe that over the
12
+ // environment we set.
13
+ let baseUrl = `http://127.0.0.1:${port}`
8
14
  // A cold Prototype Kit boot compiles sass before it listens, which on a fresh
9
15
  // install is a good deal slower than the 15s this used to allow - and the
10
16
  // failure looked like "your routes are broken" rather than "it had not finished
@@ -111,17 +117,39 @@ async function waitForServer (server, output) {
111
117
  // Keep polling until the Prototype Kit has finished booting.
112
118
  }
113
119
 
120
+ const announced = announcedPort(output())
121
+ if (announced && announced !== currentPort()) {
122
+ baseUrl = `http://127.0.0.1:${announced}`
123
+ }
124
+
114
125
  await wait(250)
115
126
  }
116
127
 
117
128
  throw new Error(
118
129
  `The prototype did not start listening on ${baseUrl} within ${timeoutMs}ms.\n` +
119
- 'This command starts your app with PORT set, so if app.js hardcodes a port\n' +
120
- 'it will be running somewhere else. Otherwise raise SMOKE_TIMEOUT_MS.\n' +
130
+ 'This command starts your app with PORT set and follows the URL the app\n' +
131
+ 'announces, so a port set somewhere it never prints will be missed.\n' +
132
+ 'Otherwise raise SMOKE_TIMEOUT_MS.\n' +
121
133
  indent(output())
122
134
  )
123
135
  }
124
136
 
137
+ function currentPort () {
138
+ return baseUrl.slice(baseUrl.lastIndexOf(':') + 1)
139
+ }
140
+
141
+ // The kit prints its URLs through Browsersync once it is listening. Take the
142
+ // last one it mentions: an app that has moved port says so more than once, and
143
+ // the most recent is the one to trust.
144
+ function announcedPort (output) {
145
+ const matches = [...String(output).matchAll(/https?:\/\/(?:localhost|127\.0\.0\.1)(?::(\d{2,5}))?/gi)]
146
+ for (let i = matches.length - 1; i >= 0; i--) {
147
+ const found = matches[i][1]
148
+ if (found && found !== String(port)) return found
149
+ }
150
+ return null
151
+ }
152
+
125
153
  async function smokeRoutes (routes) {
126
154
  const failures = []
127
155
 
@@ -3,6 +3,7 @@ const path = require('path')
3
3
  const { z } = require('zod')
4
4
 
5
5
  const packagePaths = require('../lib/package-paths')
6
+ const { resolveRoot } = require('../lib/resolve-root')
6
7
 
7
8
  // Skills live in the package; the paths inside them (reads:, and the
8
9
  // `.github/skills/<id>.skill.md` references in guidance) describe a HOST
@@ -13,9 +14,25 @@ const rootDir = packagePaths.packageRoot
13
14
  const skillsDir = packagePaths.skillsDir
14
15
  const catalogPath = path.join(skillsDir, 'skills.json')
15
16
 
17
+ // Two very different situations share this command.
18
+ //
19
+ // In this monorepo the package is not installed anywhere, so the consumer to
20
+ // validate against is the demo app. In a host, the package sits in
21
+ // node_modules and the consumer is the project around it - resolved the same
22
+ // way every other command resolves it.
23
+ //
24
+ // The old default was `<packageRoot>/../../apps/demo` unconditionally. From
25
+ // node_modules that is `<host>/node_modules/apps/demo`, a path that cannot
26
+ // exist, so every `reads:` check failed and the command was unusable in the
27
+ // place it matters most. It went unnoticed because nothing ran a shipped
28
+ // command against a real install - only checked that it loaded.
16
29
  function readHostRoot () {
17
30
  const flag = process.argv.indexOf('--host')
18
31
  if (flag !== -1 && process.argv[flag + 1]) return path.resolve(process.argv[flag + 1])
32
+
33
+ const installed = rootDir.split(path.sep).includes('node_modules')
34
+ if (installed) return resolveRoot({ argv: process.argv.slice(2) }).root
35
+
19
36
  return path.resolve(rootDir, '../../apps/demo')
20
37
  }
21
38
 
@@ -10,7 +10,6 @@ composes:
10
10
  - audit-knowledge-source
11
11
  reads:
12
12
  - hippocampus/source/project.json
13
- - hippocampus/source/project-context.json
14
13
  - hippocampus/source/users.json
15
14
  - hippocampus/source/needs.json
16
15
  - hippocampus/source/insights.json
@@ -53,7 +52,7 @@ Works in two modes. **Live** - answer their questions in conversation, grounded
53
52
 
54
53
  ### Read these first
55
54
 
56
- 1. `project.json` and `project-context.json` for what the project is. **`project-context.json` is the narrative half.** If its `purpose`, `problemStatement` and `constraints` are empty, the project has never recorded why it exists - say that plainly and suggest `ingest-project-context`. Do not reconstruct a purpose from the graph.
55
+ 1. `project.json` and, if it exists, `project-context.json` for what the project is. **`project-context.json` is the narrative half, and it is optional** - a project has one only once somebody has run `ingest-project-context`. If it is missing, or its `purpose`, `problemStatement` and `constraints` are empty, the project has never recorded why it exists - say that plainly and suggest `ingest-project-context`. Do not reconstruct a purpose from the graph.
57
56
  2. The graph for the state. Everything below is counted, not remembered.
58
57
  3. `npx hippocampus validate` for the coverage notes.
59
58
 
@@ -8,7 +8,7 @@
8
8
  {% block content %}
9
9
  <div class="nhsuk-grid-row">
10
10
  <div class="nhsuk-grid-column-two-thirds">
11
- <span class="nhsuk-caption-l">Prototype Kit add-on spike</span>
11
+ <span class="nhsuk-caption-l">Design knowledge base</span>
12
12
  <h1>{{ knowledge.project.name }}</h1>
13
13
  <p class="nhsuk-lede-text">{{ knowledge.project.description }}</p>
14
14