@hippo-digital/hippocampus 2.5.0 → 2.7.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.
@@ -0,0 +1,206 @@
1
+ ---
2
+ section: recipes
3
+ order: 50
4
+ audience: [viewer, cli]
5
+ summary: Turn persona documents into the users and needs everything else hangs off. There is no draft for this, so git is where you review it.
6
+ ---
7
+ # Turn personas into users and needs
8
+
9
+ Users and their needs are what the rest of the knowledge base points at.
10
+ Scenarios, journeys, screens and research insights all name the user and the
11
+ needs they are about, so users usually come first. They come from your persona
12
+ documents.
13
+
14
+ This works differently from importing research. There is no import command
15
+ and no draft. Either an AI agent reads the persona documents and writes users,
16
+ needs and the evidence behind them straight into `hippocampus/source/`, or you
17
+ add them by hand. Either way, **you review the change with git before you
18
+ commit it**.
19
+
20
+ ## Who this is for
21
+
22
+ Researchers and designers who own the personas. You need to be able to run
23
+ commands in the prototype, and either have an AI agent set up or be happy
24
+ editing JSON files.
25
+
26
+ ## Before you start
27
+
28
+ ### Agree whether an agent may read the personas
29
+
30
+ Personas are research. If your team uses the agent route, what the agent reads
31
+ is sent to its service. Agree this first; see
32
+ [Data and governance](data-and-governance.md#agree-these-before-your-first-import).
33
+ If an agent may not read them, add the records by hand, described in
34
+ [By hand](#by-hand).
35
+
36
+ ### Start from a clean record
37
+
38
+ Commit or set aside any other changes in `hippocampus/source/` first, so that
39
+ `git diff` shows only what this step adds, and throwing it away throws away
40
+ nothing else.
41
+
42
+ ### Check the documents say enough
43
+
44
+ Each persona becomes one user. The more the document states in its own words,
45
+ the more the record holds:
46
+
47
+ - who the group is
48
+ - what they are responsible for
49
+ - what they need, and why
50
+ - their access needs, if the research covered them
51
+
52
+ Nothing is filled in from judgement. A persona that states two needs gives a
53
+ user with two needs, which is the honest result.
54
+
55
+ ## At the command line
56
+
57
+ 1. Copy the persona documents into `hippocampus/inbox/personas/`. The
58
+ `.gitignore` lines `init` writes keep them out of the repository; see
59
+ [Keep research files and drafts out of git](data-and-governance.md#keep-research-files-and-drafts-out-of-git).
60
+
61
+ 2. Ask your agent to use the `ingest-user-personas` skill on them, for
62
+ example: "Use the ingest-user-personas skill on the documents in
63
+ hippocampus/inbox/personas."
64
+
65
+ For each document, the agent adds:
66
+
67
+ - one **evidence** record for the document, with its file name as
68
+ `sourcePath`, so anyone can find the original
69
+ - one **user**, with the description and responsibilities from the document
70
+ - the **needs** the document states, in its own words, each citing that
71
+ evidence
72
+ - an **assumption** for every field it had to fill that the document did
73
+ not state
74
+
75
+ Two fields cannot be left empty, so they are where a guess could hide. When
76
+ the document does not rank needs, each need's priority is `medium` and an
77
+ assumption says so. When it does not cover access needs, the user's access
78
+ needs are exactly `Not yet researched`, and an assumption says that too.
79
+
80
+ 3. Check it:
81
+
82
+ ```bash
83
+ npx hippocampus validate
84
+ ```
85
+
86
+ 4. Review the change:
87
+
88
+ ```bash
89
+ git diff hippocampus/source
90
+ ```
91
+
92
+ Check that:
93
+
94
+ - there is one user per persona, and none merges two personas
95
+ - every need is one the document states, in its words, and belongs to the
96
+ right user
97
+ - every need cites the persona's evidence record
98
+ - nothing is invented: no responsibility, need or access need that is not in
99
+ the document
100
+ - the assumptions name what the documents left out
101
+ - nothing identifies a real person
102
+
103
+ 5. Commit `hippocampus/source/` if it is right. To throw the whole change away
104
+ instead, run `git checkout -- hippocampus/source`. That puts back every file
105
+ in it as last committed, which is why you started from a clean record.
106
+
107
+ ### By hand
108
+
109
+ [Source model](source-model.md#users) describes each field. For each persona,
110
+ add to these files in `hippocampus/source/`:
111
+
112
+ - `evidence.json`: one record with `sourceType: "user persona"` and the
113
+ document's file name as `sourcePath`
114
+ - `users.json`: the user
115
+ - `needs.json`: each need, with the user's id as `userId` and the evidence
116
+ record's id in `evidenceIds`
117
+ - `relationships.json`: a `has-need` link from the user to each need
118
+ - `assumptions.json`: anything you had to fill in that the document did not
119
+ say
120
+
121
+ Then run `npx hippocampus validate`, and review with `git diff` as above.
122
+
123
+ ## What it looks like
124
+
125
+ This example is made up. A user and one of their needs, as they appear in the
126
+ diff:
127
+
128
+ ```json
129
+ {
130
+ "id": "carer",
131
+ "label": "Carer",
132
+ "description": "Someone booking blood tests for a person they look after.",
133
+ "responsibilities": ["Book and keep track of tests for someone else"],
134
+ "accessNeeds": ["Not yet researched"]
135
+ }
136
+ ```
137
+
138
+ ```json
139
+ {
140
+ "id": "need-see-booked-appointments",
141
+ "userId": "carer",
142
+ "statement": "I need to see the appointments I have booked for my parent, so that I do not book the same test twice.",
143
+ "priority": "medium",
144
+ "evidenceIds": ["evidence-carer-persona"]
145
+ }
146
+ ```
147
+
148
+ `validate` then reports the gaps the import left on purpose:
149
+
150
+ ```text
151
+ $ npx hippocampus validate
152
+ hippocampus: knowledge data is valid
153
+ info 3 of 3 users have access needs not yet researched
154
+ info 4 of 6 needs (67%) sit at priority "medium" - likely the import default rather than a decision, so priority cannot sequence design work yet
155
+ ```
156
+
157
+ Those two lines are not errors. They are the gaps the personas left, kept
158
+ visible until research or a team decision fills them.
159
+
160
+ ## In the viewer
161
+
162
+ - **Users** (`/hippocampus/users`) lists every user with how many needs and
163
+ scenarios they have.
164
+ - A user's page shows their responsibilities and access needs, then each need
165
+ with the evidence behind it. `Not yet researched` shows there as it is.
166
+ - **User needs** (`/hippocampus/user-needs`) lists every need. Filter it by
167
+ user or by priority.
168
+ - The front page's **Needs with no screen** count goes up: every new need is
169
+ design work nobody has started.
170
+
171
+ ## How to check it worked
172
+
173
+ - `npx hippocampus validate` says `knowledge data is valid`.
174
+ - Each persona is on the Users page, with the number of needs its document
175
+ states.
176
+ - Each need's page lists the persona's evidence under it.
177
+
178
+ ## If it goes wrong
179
+
180
+ - **"users.0.accessNeeds: Too small: expected array to have >=1 items"**: a
181
+ user has no access needs at all. If nobody has researched them, write
182
+ `Not yet researched`.
183
+ - **"needs.5.evidenceIds: Too small: expected array to have >=1 items"**: a
184
+ need cites no evidence. Every need from a persona cites the persona's
185
+ evidence record. The number is the need's position in the file, counting
186
+ from 0.
187
+ - **"need need-reminder-text: userId references missing id patients"**: the
188
+ need names a user that does not exist, here because of a typing mistake.
189
+ Use the id from `users.json`.
190
+ - **A need you did not expect**: if it is not in the document, take it out. A
191
+ need that came from somewhere else needs its own evidence.
192
+ - **The diff shows changes you did not make**: something else in
193
+ `hippocampus/source/` had changed before you started. Sort those out
194
+ separately before committing.
195
+
196
+ ## Related skills
197
+
198
+ - `ingest-user-personas`: the agent route described above.
199
+ - `add-user-needs`: adds needs to a user who already exists, or sharpens vague
200
+ ones, each linked to the evidence behind it.
201
+ - `find-unintended-consequences`: when a new kind of user arrives, checks what
202
+ their journeys could break for the users already here. See
203
+ [Check for unintended consequences](check-for-unintended-consequences.md).
204
+
205
+ Whatever an agent reads is sent to the agent's service. See
206
+ [When anything leaves your machine](data-and-governance.md#when-anything-leaves-your-machine).
@@ -0,0 +1,69 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const { spawnSync } = require('child_process')
4
+
5
+ // Research files (hippocampus/inbox) and import drafts (hippocampus/imports)
6
+ // hold participants' words: transcripts, quotes, notes. The guide's advice is
7
+ // to keep both on the machine that imported them, because anything committed
8
+ // stays in the repository's history. `init` writes the .gitignore lines that do
9
+ // that, and `doctor` says when files there are committed anyway.
10
+ //
11
+ // A team can decide otherwise. A .gitignore line that names the folder - a rule
12
+ // or just a comment - is taken as that decision, so neither command overrides
13
+ // or nags about a choice somebody has written down.
14
+ const RESEARCH_DIRS = ['inbox', 'imports']
15
+
16
+ function ignoreLines (relDir) {
17
+ return [`${relDir}/**`, `!${relDir}/**/`, `!${relDir}/**/.gitkeep`]
18
+ }
19
+
20
+ function ignoreBlock (relDirs) {
21
+ return [
22
+ '# Research files and import drafts: copies of research with participants\'',
23
+ '# words in them, which stay on the machine that imported them. Written by',
24
+ '# `hippocampus init`. To commit a folder instead, replace its lines with a',
25
+ '# comment that names it, and init and doctor will leave it alone.',
26
+ ...relDirs.flatMap(ignoreLines)
27
+ ].join('\n') + '\n'
28
+ }
29
+
30
+ function readGitignore (root) {
31
+ const file = path.join(root, '.gitignore')
32
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''
33
+ }
34
+
35
+ // Read at write time, not plan time: init plans more than one change to this
36
+ // file, and a write built from a stale copy would drop the others.
37
+ function appendToGitignore (root, text) {
38
+ const file = path.join(root, '.gitignore')
39
+ const current = readGitignore(root)
40
+ const prefix = current.trim() ? `${current.replace(/\n*$/, '\n')}\n` : ''
41
+ fs.writeFileSync(file, prefix + text)
42
+ }
43
+
44
+ function mentions (gitignoreText, relDir) {
45
+ return gitignoreText.split('\n').some((line) => line.includes(relDir))
46
+ }
47
+
48
+ /**
49
+ * Files git tracks under relDir, apart from the .gitkeep files that keep the
50
+ * empty folders in the repository. `ignoredOnly` narrows that to files a
51
+ * .gitignore rule now matches - committed before the rule was written, and
52
+ * still tracked, because ignoring a file never untracks it.
53
+ *
54
+ * Returns null when there is nothing to ask: not a git repository, or no git.
55
+ */
56
+ function trackedFiles (root, relDir, { ignoredOnly = false } = {}) {
57
+ const args = ['ls-files', '-z', ...(ignoredOnly ? ['-c', '-i', '--exclude-standard'] : []), '--', relDir]
58
+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' })
59
+ if (result.error || result.status !== 0) return null
60
+ return result.stdout.split('\0').filter(Boolean).filter((file) => path.basename(file) !== '.gitkeep')
61
+ }
62
+
63
+ function relativeDir (root, dir) {
64
+ return path.relative(root, dir).split(path.sep).join('/')
65
+ }
66
+
67
+ module.exports = {
68
+ RESEARCH_DIRS, ignoreLines, ignoreBlock, readGitignore, appendToGitignore, mentions, trackedFiles, relativeDir
69
+ }
package/lib/templates.js CHANGED
@@ -24,7 +24,7 @@ const DESCRIBED = {
24
24
  'Purpose, vision, policy context, channels, constraints, risks, milestones ' +
25
25
  'and source facts. One sheet per kind, one row per record.',
26
26
  command: 'hippocampus import project-context <file>',
27
- then: 'hippocampus promote project-context'
27
+ then: 'hippocampus promote project-context --draft <the draft it names>'
28
28
  },
29
29
  'service-blueprint.xlsx': {
30
30
  title: 'Service blueprint',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "2.5.0",
3
+ "version": "2.7.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",
@@ -54,6 +54,8 @@ if (flags.json) {
54
54
 
55
55
  const LIMIT = flags.all ? Infinity : 25
56
56
  const clip = (text, n = 108) => (text && text.length > n ? `${text.slice(0, n - 1)}…` : text || '')
57
+ // "1 roles" and "2 participant(s)" read as a draft nobody finished.
58
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
57
59
  const roundLabel = (round) => (round ? `${round.title}, ${round.date}` : 'no research round')
58
60
  let clipped = false
59
61
 
@@ -71,11 +73,11 @@ const { scenario, persona } = result
71
73
  console.log('Checking a journey against the users we already know')
72
74
  console.log(` ${scenario.title}`)
73
75
  console.log(` ${scenario.id} · ${scenario.userLabel} (${scenario.userId})`)
74
- console.log(` (${ctx.root}, ${result.researchRounds} research rounds)`)
76
+ console.log(` (${ctx.root}, ${count(result.researchRounds, 'research round')})`)
75
77
 
76
78
  console.log('\nThis user in the research')
77
79
  if (persona.participants.length) {
78
- console.log(` ${persona.participants.length} participant(s) whose role matches "${persona.matchedOn.join('", "')}", in ${persona.rounds.length} round(s): ` +
80
+ console.log(` ${count(persona.participants.length, 'participant')} whose role matches "${persona.matchedOn.join('", "')}", in ${count(persona.rounds.length, 'round')}: ` +
79
81
  persona.rounds.map((r) => `${r.title} (${r.date})`).join('; '))
80
82
  } else {
81
83
  console.log(` No participant's role matches "${persona.matchedOn.join('", "')}". No round has included this kind of user,`)
@@ -95,7 +97,7 @@ section('What this journey stands on', standsOn, (g) => g.kind === 'insight'
95
97
 
96
98
  const needCount = result.reaches.reduce((n, u) => n + u.needs.length, 0)
97
99
  if (result.reaches.length) {
98
- console.log(`\nUsers we already know who stand on the same ground (${result.reaches.length} roles, ${needCount} needs)`)
100
+ console.log(`\nUsers we already know who stand on the same ground (${count(result.reaches.length, 'role')}, ${count(needCount, 'need')})`)
99
101
  for (const user of result.reaches) {
100
102
  console.log(` ${user.label} (${user.userId})`)
101
103
  for (const need of user.needs.slice(0, LIMIT)) {
@@ -134,9 +136,9 @@ console.log('\nQuestions every new kind of user raises')
134
136
  for (const c of result.concerns) {
135
137
  console.log(` ${c.id.padEnd(12)} ${c.question}`)
136
138
  if (c.nobodyAsked) {
137
- console.log(` Nobody has asked. No record in ${result.researchRounds} rounds names it. That is the finding.`)
139
+ console.log(` Nobody has asked. No record in ${count(result.researchRounds, 'round')} names it. That is the finding.`)
138
140
  } else {
139
- if (c.findings) console.log(` ${c.findings} finding(s), in ${c.roundsWithFindings} round(s)`)
141
+ if (c.findings) console.log(` ${count(c.findings, 'finding')}, in ${count(c.roundsWithFindings, 'round')}`)
140
142
  for (const n of c.namedBy.slice(0, 6)) console.log(` named by ${n.id}${n.status ? ` [${n.status}]` : ''}`)
141
143
  if (c.namedBy.length > 6) console.log(` ... and ${c.namedBy.length - 6} more`)
142
144
  }
package/scripts/doctor.js CHANGED
@@ -8,6 +8,7 @@ const { createContext } = require('../lib/context')
8
8
  const { lintKnowledge } = require('../lib/lint-knowledge')
9
9
  const { findBlock } = require('../lib/host-edit')
10
10
  const packagePaths = require('../lib/package-paths')
11
+ const researchInGit = require('../lib/research-in-git')
11
12
 
12
13
  // What doctor is for: answering "why is it not working?" without guessing.
13
14
  // The resolved root is the first line of output, because it is the answer to
@@ -15,6 +16,7 @@ const packagePaths = require('../lib/package-paths')
15
16
 
16
17
  const argv = process.argv.slice(2)
17
18
  const problems = []
19
+ const warnings = []
18
20
  const notes = []
19
21
 
20
22
  function main () {
@@ -55,6 +57,8 @@ function main () {
55
57
  }
56
58
  }
57
59
 
60
+ checkResearchInGit(root, projects)
61
+
58
62
  if (!argv.includes('--no-smoke') && projects.length && !problems.length) {
59
63
  const smoke = spawnSync(process.execPath, [path.join(packagePaths.scriptsDir, 'smoke-routes.js'), '--root', root],
60
64
  { encoding: 'utf8' })
@@ -79,7 +83,57 @@ function main () {
79
83
  process.exit(1)
80
84
  }
81
85
 
82
- console.log('\nAll good.')
86
+ // A warning is not a failure: the prototype works. It is something a person
87
+ // should decide about, so it is said every time until they have.
88
+ console.log(warnings.length
89
+ ? `\nWorking, with ${warnings.length} warning${warnings.length === 1 ? '' : 's'} to look at.`
90
+ : '\nAll good.')
91
+ }
92
+
93
+ function warn (label, message) {
94
+ console.log(` warn ${label}: ${message}`)
95
+ warnings.push(`${label}: ${message}`)
96
+ }
97
+
98
+ // Research files and import drafts committed to git. Three cases, because the
99
+ // fix differs:
100
+ // - matched by a .gitignore rule but still tracked: committed before the rule
101
+ // existed, and ignoring a file never untracks it
102
+ // - not ignored, and .gitignore never names the folder: nobody has decided
103
+ // - not ignored, and .gitignore names the folder: a team decision, written
104
+ // down. Said once as a note, not as a warning on every run.
105
+ function checkResearchInGit (root, projects) {
106
+ const gitignore = researchInGit.readGitignore(root)
107
+ let checked = false
108
+ let clean = true
109
+
110
+ for (const project of projects) {
111
+ for (const dir of researchInGit.RESEARCH_DIRS) {
112
+ const relDir = researchInGit.relativeDir(root, path.join(project.dir, dir))
113
+ const tracked = researchInGit.trackedFiles(root, relDir)
114
+ if (tracked === null) return // not a git repository: nothing can have been committed
115
+ checked = true
116
+ if (!tracked.length) continue
117
+ clean = false
118
+
119
+ const files = `${tracked.length} ${tracked.length === 1 ? 'file' : 'files'} in ${relDir}`
120
+ const ignored = researchInGit.trackedFiles(root, relDir, { ignoredOnly: true }) || []
121
+ if (ignored.length) {
122
+ const [it, is] = ignored.length === 1 ? ['it', 'is'] : ['them', 'are']
123
+ const ignoredFiles = `${ignored.length} ${ignored.length === 1 ? 'file' : 'files'} in ${relDir}`
124
+ warn('research files', `${ignoredFiles} ${is} still committed, though .gitignore now excludes ${it}. ` +
125
+ `\`git rm -r --cached ${relDir}\` then \`git add ${relDir}\` stops tracking ${it} and keeps ${it} on disk.`)
126
+ } else if (researchInGit.mentions(gitignore, relDir)) {
127
+ notes.push(`${files} ${tracked.length === 1 ? 'is' : 'are'} committed to git, which .gitignore says is deliberate. ` +
128
+ 'They hold participants\' words - see Data and governance in the guide.')
129
+ } else {
130
+ warn('research files', `${files} ${tracked.length === 1 ? 'is' : 'are'} committed to git. They hold participants\' ` +
131
+ 'words. `npx hippocampus init` explains how to keep them out, or says how to record that your team decided to commit them.')
132
+ }
133
+ }
134
+ }
135
+
136
+ if (checked && clean) console.log(' ok research files: none committed to git')
83
137
  }
84
138
 
85
139
  function report (label, ok, okMessage, problemMessage) {
@@ -1,7 +1,6 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
3
  const AdmZip = require('adm-zip')
4
- const { PDFParse } = require('pdf-parse')
5
4
  const { XMLParser } = require('fast-xml-parser')
6
5
  const { ProjectContextImportDraftSchema } = require('../lib/schema')
7
6
  const { createContextOrExit } = require('../lib/context')
@@ -18,8 +17,10 @@ function ctx () {
18
17
  async function main () {
19
18
  const args = parseArgs(process.argv.slice(2))
20
19
  if (!args.document || !args.contextId || !args.title) {
21
- throw new Error('Usage: npx hippocampus import project-context -- --document path/to/overview.pdf --context-id context-id --title "Project overview"\n' +
22
- 'A filled-in copy of templates/project-context.xlsx works too, and needs no guessing.')
20
+ // `hippocampus import project-context` runs sync-project-context.js, which
21
+ // calls this with all three. Reaching here means it was run by hand.
22
+ throw new Error('Usage: npx hippocampus import project-context path/to/file.xlsx\n' +
23
+ 'A filled-in copy of templates/project-context.xlsx needs no guessing; a .pptx or .pdf works too.')
23
24
  }
24
25
 
25
26
  // A spreadsheet is a different kind of input from a deck or a PDF. Those are
@@ -45,8 +46,8 @@ async function main () {
45
46
  ? `Read ${sections.length} tabs`
46
47
  : `Imported ${sections.length} ${sectionLabel(args.document).toLowerCase()}`)
47
48
  reportFit(draft)
48
- console.log(`Draft written to ${outputPath}`)
49
- console.log(`Review written to ${reviewPath}`)
49
+ console.log(`Draft written to ${shown(outputPath)}`)
50
+ console.log(`Review written to ${shown(reviewPath)}`)
50
51
  }
51
52
 
52
53
  function parseArgs (args) {
@@ -98,6 +99,10 @@ function extractPowerPointSlides (deckPath) {
98
99
  }
99
100
 
100
101
  async function extractPdfPages (pdfPath) {
102
+ // Loaded here, not at the top: the PDF parser is the one dependency that has
103
+ // refused to load on some Node versions, and a spreadsheet or a deck should
104
+ // not fail to import because of a parser it never uses.
105
+ const { PDFParse } = require('pdf-parse')
101
106
  const parser = new PDFParse({ data: fs.readFileSync(pdfPath) })
102
107
 
103
108
  try {
@@ -488,6 +493,13 @@ function kebab (value) {
488
493
  .replace(/^-+|-+$/g, '')
489
494
  }
490
495
 
496
+ // Paths as the person would type them from the project root, not the
497
+ // absolute path of wherever the project happens to live.
498
+ function shown (file) {
499
+ const relative = path.relative(ctx().root, file)
500
+ return relative && !relative.startsWith('..') ? relative : file
501
+ }
502
+
491
503
  function camelCase (value) {
492
504
  return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
493
505
  }
package/scripts/init.js CHANGED
@@ -5,6 +5,7 @@ const { resolveRoot, CONFIG_FILENAME } = require('../lib/resolve-root')
5
5
  const { CURRENT_SCHEMA_VERSION } = require('../lib/schema-version')
6
6
  const hostEdit = require('../lib/host-edit')
7
7
  const packagePaths = require('../lib/package-paths')
8
+ const researchInGit = require('../lib/research-in-git')
8
9
 
9
10
  // Set a host project up to use Hippocampus: write the config and an empty
10
11
  // knowledge base, then make the two host edits - both inside marked blocks, both
@@ -13,6 +14,9 @@ const packagePaths = require('../lib/package-paths')
13
14
  // --dry-run print what would change and write nothing
14
15
  // --no-wire write the data, print the host edits to paste by hand
15
16
  // --private-artefacts gitignore the copied research material
17
+ //
18
+ // It also gitignores the inbox and the import drafts, unless .gitignore already
19
+ // names them or files in them are already committed. See planResearchIgnore.
16
20
 
17
21
  const argv = process.argv.slice(2)
18
22
  const dryRun = argv.includes('--dry-run')
@@ -41,6 +45,7 @@ function main () {
41
45
  planKnowledgeBase(root)
42
46
  planArtefacts(root, artefactsDir(root))
43
47
  planArtefactGovernance(root)
48
+ planResearchIgnore(root)
44
49
  if (!noWire) {
45
50
  planHostEdit(path.join(root, 'app/routes.js'), wireRoutes)
46
51
  planHostEdit(path.join(root, 'app.js'), wireApp)
@@ -216,8 +221,7 @@ function planArtefactGovernance (root) {
216
221
  if (privateArtefacts) {
217
222
  if (alreadyIgnored) return
218
223
  plan(`.gitignore (${ARTEFACTS_IGNORE_LINE})`, () => {
219
- const prefix = current.trim() ? `${current.replace(/\n*$/, '\n')}\n` : ''
220
- fs.writeFileSync(gitignorePath, prefix +
224
+ researchInGit.appendToGitignore(root,
221
225
  '# Research material copied into the knowledge base: transcripts and\n' +
222
226
  '# participant quotes. Kept out of this repo by `hippocampus init --private-artefacts`.\n' +
223
227
  `${ARTEFACTS_IGNORE_LINE}\n`)
@@ -245,6 +249,56 @@ function planArtefactGovernance (root) {
245
249
  ].join('\n'))
246
250
  }
247
251
 
252
+ // The inbox and the import drafts are working copies of research, with
253
+ // participants' words in them. Unlike source-artefacts - material a team may
254
+ // well decide to keep - the guide's advice for these is settled: keep them on
255
+ // the machine that imported them. So they are ignored by default, rather than
256
+ // left to a paragraph somebody may not read before their first commit.
257
+ //
258
+ // Two things stop it. A .gitignore line naming the folder means the team has
259
+ // already decided, either way. And files there that are already committed
260
+ // mean a rule now would ignore new drafts while the old ones stayed tracked -
261
+ // half a decision, made silently - so init says what it found instead.
262
+ function planResearchIgnore (root) {
263
+ const current = researchInGit.readGitignore(root)
264
+ const toIgnore = []
265
+ const committed = []
266
+
267
+ for (const dir of researchInGit.RESEARCH_DIRS) {
268
+ const relDir = `hippocampus/${dir}`
269
+ if (researchInGit.mentions(current, relDir)) continue
270
+ const tracked = researchInGit.trackedFiles(root, relDir) || []
271
+ if (tracked.length) committed.push({ relDir, count: tracked.length })
272
+ else toIgnore.push(relDir)
273
+ }
274
+
275
+ if (toIgnore.length) {
276
+ plan(`.gitignore (${toIgnore.join(', ')})`, () => {
277
+ researchInGit.appendToGitignore(root, researchInGit.ignoreBlock(toIgnore))
278
+ })
279
+ }
280
+
281
+ for (const { relDir, count } of committed) {
282
+ manual.push([
283
+ `${count} ${count === 1 ? 'file' : 'files'} in ${relDir} ${count === 1 ? 'is' : 'are'} committed to git, so .gitignore was left alone.`,
284
+ '',
285
+ 'Research files and import drafts hold participants\' words. The guide\'s',
286
+ 'Data and governance page explains what to agree with your information',
287
+ 'governance lead.',
288
+ '',
289
+ 'To keep them out of git from now on, add to .gitignore:',
290
+ ...researchInGit.ignoreLines(relDir).map((line) => ` ${line}`),
291
+ 'then stop tracking them (the files stay on your machine):',
292
+ ` git rm -r --cached ${relDir}`,
293
+ ` git add ${relDir}`,
294
+ 'Earlier commits still hold them.',
295
+ '',
296
+ `If your team has decided they belong in the repo, add a .gitignore comment`,
297
+ `that names ${relDir}, and init and doctor will leave it alone.`
298
+ ].join('\n'))
299
+ }
300
+ }
301
+
248
302
  function countFiles (dir) {
249
303
  if (!fs.existsSync(dir)) return 0
250
304
  let total = 0
@@ -44,15 +44,20 @@ const { knowledgeSourceDir } = ctx.paths
44
44
  // data is wrong" rather than "this is not configured".
45
45
  const LINK_CONFIG = ctx.config.linkInsights || {}
46
46
 
47
- const GROUP_TO_USERS = (LINK_CONFIG.userGroups || []).map((entry, i) => {
48
- if (!entry || !entry.match || !Array.isArray(entry.users)) {
49
- throw new Error(
50
- `linkInsights.userGroups[${i}] in ${ctx.configPath} needs a "match" pattern ` +
51
- 'and a "users" array of user ids.'
52
- )
53
- }
54
- return [new RegExp(entry.match, 'i'), entry.users]
55
- })
47
+ // Read inside main, so a malformed entry is reported as a message rather than
48
+ // a stack trace from loading the module.
49
+ let GROUP_TO_USERS = []
50
+ function readUserGroups () {
51
+ return (LINK_CONFIG.userGroups || []).map((entry, i) => {
52
+ if (!entry || !entry.match || !Array.isArray(entry.users)) {
53
+ throw new Error(
54
+ `linkInsights.userGroups[${i}] in ${ctx.configPath} needs a "match" pattern ` +
55
+ 'and a "users" array of user ids.'
56
+ )
57
+ }
58
+ return [new RegExp(entry.match, 'i'), entry.users]
59
+ })
60
+ }
56
61
 
57
62
  // The affected groups are read out of the insight summary. The sentence shape
58
63
  // comes from whichever importer wrote it, so it is configurable too.
@@ -78,13 +83,17 @@ function tokens (text) {
78
83
 
79
84
  function main () {
80
85
  const args = parseArgs(process.argv.slice(2))
86
+ GROUP_TO_USERS = readUserGroups()
81
87
  const read = (f) => JSON.parse(fs.readFileSync(path.join(knowledgeSourceDir, f), 'utf8'))
82
88
 
83
89
  const needs = read('needs.json')
84
90
  const participants = read('participants.json')
85
91
  const insights = read('insights.json').filter((i) => !args.round || i.roundId === args.round)
86
92
  const relationships = read('relationships.json')
87
- const insightIds = new Set(read('insights.json').map((i) => i.id))
93
+ // The links this run owns are the ones from the insights it is matching.
94
+ // This was every insight in the knowledge base, so `--round round-2` deleted
95
+ // every other round's insight-to-need links and wrote back only round 2's.
96
+ const insightIds = new Set(insights.map((i) => i.id))
88
97
 
89
98
  // Rare words are informative; words in every need are not.
90
99
  const df = new Map()
@@ -95,6 +104,13 @@ function main () {
95
104
  for (const t of set) df.set(t, (df.get(t) || 0) + 1)
96
105
  }
97
106
  const weight = (t) => Math.log(needs.length / ((df.get(t) || 0) + 1)) + 1
107
+ // A term is distinctive when it is in at most 1/e of the needs - about a
108
+ // third. This used to be `weight(t) >= 2`, which is the same rule with the
109
+ // +1 smoothing left in, and the smoothing decides it on a small knowledge
110
+ // base: with fewer than six needs no term could ever qualify, even one found
111
+ // in a single need, so a new project's first run linked nothing at all. On
112
+ // NCRS's 132 needs the two rules differ by one need's worth of frequency.
113
+ const distinctiveTerm = (t) => (df.get(t) || 0) / needs.length <= 1 / Math.E
98
114
 
99
115
  const links = []
100
116
  const report = []
@@ -147,7 +163,7 @@ function main () {
147
163
  if (!have.has(t)) continue
148
164
  const w = weight(t)
149
165
  score += w
150
- if (w >= 2) distinctive++
166
+ if (distinctiveTerm(t)) distinctive++
151
167
  }
152
168
  // Normalise by the need's own length so a long statement does not win by
153
169
  // sheer surface area.
@@ -215,7 +231,7 @@ function main () {
215
231
  const lines = [
216
232
  `# Insight to need links${args.round ? `: ${args.round}` : ''}`,
217
233
  '',
218
- `Generated by \`scripts/link-insights-to-needs.js\`. ${links.length} links across ${report.filter((r) => r.matched.length).length} insights.`,
234
+ `Generated by \`npx hippocampus link insight-needs\`. ${count(links.length, 'link')} across ${count(report.filter((r) => r.matched.length).length, 'insight')}.`,
219
235
  '',
220
236
  'Scores are relative within an insight, not across insights. The lowest-scoring link',
221
237
  'under each insight is the one most worth checking. Delete a link from',
@@ -238,6 +254,10 @@ function main () {
238
254
  console.log(`review pack: ${path.relative(ctx.root, reviewPath)}`)
239
255
  }
240
256
 
257
+ function count (n, word) {
258
+ return `${n} ${word}${n === 1 ? '' : 's'}`
259
+ }
260
+
241
261
  function parseArgs (argv) {
242
262
  const parsed = {}
243
263
  for (let i = 0; i < argv.length; i++) {
@@ -249,4 +269,9 @@ function parseArgs (argv) {
249
269
  return parsed
250
270
  }
251
271
 
252
- main()
272
+ try {
273
+ main()
274
+ } catch (error) {
275
+ console.error(error.message)
276
+ process.exit(1)
277
+ }