@hippo-digital/hippocampus 1.0.0-rc.6 → 1.0.0-rc.7

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
@@ -93,6 +93,56 @@ four sheets, with nothing unmapped.
93
93
  The grid logic is exported and covered by unit tests - `npm run test:unit`, also
94
94
  run by the release gate. They are the package's first.
95
95
 
96
+ ### Unit tests where end-to-end cannot reach
97
+
98
+ 35 tests covering the two places where being wrong damages something the team
99
+ owns, and where the install test structurally cannot help: it wires one
100
+ well-formed Prototype Kit, and every branch below needs a differently-malformed
101
+ file or directory tree.
102
+
103
+ - **`host-edit.js`** - the seven paths where it refuses to edit `app.js`. A block
104
+ with no end marker, a block the team has edited since it was written, two
105
+ `viewsPath` arrays, an array holding something other than string literals, no
106
+ safe insertion point. The install test reached none of them, and those
107
+ refusals are the whole safety design: half-editing a file leaves its owner
108
+ worse off than not editing it. Also that add-then-remove and
109
+ insert-then-remove restore the file byte for byte.
110
+ - **`resolve-root.js`** - the precedence chain and its two hard errors. A wrong
111
+ root does not fail; it produces an empty knowledge base and no explanation.
112
+
113
+ Not added elsewhere on purpose: `schema.js` and `lint-knowledge.js` are covered
114
+ by `validate` against both a real and an empty knowledge base, the router and
115
+ docs by `doctor` hitting every route, and `skills install` end-to-end. Tests
116
+ there would restate what already runs.
117
+
118
+ ### Project context from a filled-in template
119
+
120
+ `templates/project-context.xlsx` ships with the package: a tab per collection,
121
+ one row per record, and the column headers are the schema's field names.
122
+ `import project-context` accepts it alongside the decks and PDFs it already took.
123
+
124
+ The difference is what the importer has to do. A deck is prose written for
125
+ another purpose, so the importer guesses at structure and reports how well it
126
+ fitted. A filled-in template already is the structure, so nothing is inferred
127
+ and nothing can be inferred wrongly. Both produce the same draft, reviewed and
128
+ promoted the same way - nothing reaches the knowledge base without a dry run.
129
+
130
+ Three rules keep a half-filled template harmless: a row with no id is skipped,
131
+ the shipped guidance row is skipped, and the worked example is skipped. The
132
+ Overview tab keeps its examples in a column of their own rather than in the
133
+ value cells, because an example sitting in a value cell imports as though
134
+ somebody had written it - which is how invented content gets into a knowledge
135
+ base, and it did on the first cut of this.
136
+
137
+ A test asserts every tab's columns against the schema, so a field added to the
138
+ model and not to the workbook fails the build rather than quietly becoming
139
+ unfillable.
140
+
141
+ The workbook reading lives in `scripts/lib/project-context-workbook.js` rather
142
+ than inside the importer, which loads a PDF parser, a zip reader and an XML
143
+ parser for the deck path. Reading a spreadsheet needs none of them, and a test
144
+ that loaded them inherited every way they can fail on a given Node version.
145
+
96
146
  ### Validation
97
147
 
98
148
  - Three tiers: errors are broken references, warnings are gaps worth filling,
@@ -105,6 +155,14 @@ run by the release gate. They are the package's first.
105
155
  pointed at `<host>/node_modules/apps/demo` and failed every check. The
106
156
  release gate now runs shipped commands against a real install rather than
107
157
  only checking that they load, which is what let this through.
158
+ - The gate runs the unit tests by spawning node rather than shelling out to
159
+ `npm run`. It executes as `prepublishOnly`, so `npm publish --workspace=<pkg>`
160
+ has already set `npm_config_workspace`; an inner `npm run` inherited it,
161
+ looked for the script in the workspace rather than the root, and failed with
162
+ "Missing script" while the tests were green.
163
+ - It no longer claims a failure it cannot name. The fallback printed the first
164
+ lines of output, which on a green run are passing tests - so it reported
165
+ "unit tests fail" and offered three ticks as the evidence.
108
166
 
109
167
  ### Data contract
110
168
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "1.0.0-rc.6",
3
+ "version": "1.0.0-rc.7",
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",
@@ -11,6 +11,7 @@
11
11
  "index.js",
12
12
  "bin",
13
13
  "lib",
14
+ "!lib/__tests__",
14
15
  "views",
15
16
  "assets",
16
17
  "scripts",
@@ -5,20 +5,35 @@ const { PDFParse } = require('pdf-parse')
5
5
  const { XMLParser } = require('fast-xml-parser')
6
6
  const { ProjectContextImportDraftSchema } = require('../lib/schema')
7
7
  const { createContextOrExit } = require('../lib/context')
8
- const ctx = createContextOrExit()
9
- const { projectImportsDir } = ctx.paths
8
+ const { openWorkbook, readSheetGrid } = require('./lib/xlsx-grid')
9
+ const {
10
+ WORKBOOK_TABS, OVERVIEW_FIELDS, readWorkbookSections, readOverview, readRecordTab
11
+ } = require('./lib/project-context-workbook')
12
+ let cachedContext = null
13
+ function ctx () {
14
+ if (!cachedContext) cachedContext = createContextOrExit()
15
+ return cachedContext
16
+ }
10
17
 
11
18
  async function main () {
12
19
  const args = parseArgs(process.argv.slice(2))
13
20
  if (!args.document || !args.contextId || !args.title) {
14
- throw new Error('Usage: npm run import:project-context -- --document path/to/overview.pdf --context-id context-id --title "Project overview"')
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.')
15
23
  }
16
24
 
17
- const sections = await extractSections(args.document)
18
- const draft = buildDraft(args, sections)
25
+ // A spreadsheet is a different kind of input from a deck or a PDF. Those are
26
+ // prose somebody wrote for another purpose, so the importer guesses at
27
+ // structure and flags how well it fitted. A filled-in template already IS the
28
+ // structure - the columns are the schema - so nothing is inferred and nothing
29
+ // can be inferred wrongly. It still produces the same draft, reviewed and
30
+ // promoted the same way.
31
+ const isWorkbook = path.extname(args.document).toLowerCase() === '.xlsx'
32
+ const sections = isWorkbook ? readWorkbookSections(args.document) : await extractSections(args.document)
33
+ const draft = isWorkbook ? buildDraftFromWorkbook(args, sections) : buildDraft(args, sections)
19
34
  validateDraft(draft)
20
35
 
21
- const outputDir = args.outputDir ? path.resolve(args.outputDir) : projectImportsDir
36
+ const outputDir = args.outputDir ? path.resolve(args.outputDir) : ctx().paths.projectImportsDir
22
37
  fs.mkdirSync(outputDir, { recursive: true })
23
38
 
24
39
  const outputPath = path.join(outputDir, `${args.contextId}.json`)
@@ -26,7 +41,9 @@ async function main () {
26
41
  fs.writeFileSync(outputPath, `${JSON.stringify(draft, null, 2)}\n`)
27
42
  fs.writeFileSync(reviewPath, buildReviewMarkdown(draft))
28
43
 
29
- console.log(`Imported ${sections.length} ${sectionLabel(args.document).toLowerCase()}`)
44
+ console.log(isWorkbook
45
+ ? `Read ${sections.length} tabs`
46
+ : `Imported ${sections.length} ${sectionLabel(args.document).toLowerCase()}`)
30
47
  reportFit(draft)
31
48
  console.log(`Draft written to ${outputPath}`)
32
49
  console.log(`Review written to ${reviewPath}`)
@@ -99,7 +116,7 @@ async function extractPdfPages (pdfPath) {
99
116
  }
100
117
 
101
118
  function buildDraft (args, sections) {
102
- const sourceDocument = path.relative(ctx.root, path.resolve(args.document))
119
+ const sourceDocument = path.relative(ctx().root, path.resolve(args.document))
103
120
  const lines = sections.flatMap((section) => section.text)
104
121
  const context = {
105
122
  id: args.contextId,
@@ -136,6 +153,60 @@ function buildDraft (args, sections) {
136
153
  }
137
154
  }
138
155
 
156
+ function buildDraftFromWorkbook (args, sections) {
157
+ const documentPath = path.resolve(args.document)
158
+ const workbook = openWorkbook(documentPath)
159
+ const present = new Set([...workbook.sheetFiles.keys()])
160
+ const sourceDocument = path.relative(ctx().root, documentPath)
161
+
162
+ const overview = present.has('Overview') ? readOverview(readSheetGrid(workbook, 'Overview')) : {}
163
+ const warnings = []
164
+
165
+ const context = {
166
+ id: overview.id || args.contextId,
167
+ title: overview.title || args.title,
168
+ summary: overview.summary || args.summary || `Project context from ${path.basename(args.document)}.`
169
+ }
170
+
171
+ if (!overview.summary && !args.summary) {
172
+ warnings.push('The Overview tab has no summary. Add one - it is the first thing anybody reads.')
173
+ }
174
+
175
+ for (const field of ['purpose', 'vision', 'problemStatement', 'serviceProposition']) {
176
+ if (overview[field]) context[field] = overview[field]
177
+ }
178
+
179
+ const narrativeGaps = ['purpose', 'vision', 'problemStatement', 'serviceProposition'].filter((f) => !context[f])
180
+ if (narrativeGaps.length) {
181
+ warnings.push(`Overview left blank: ${narrativeGaps.join(', ')}. Blank is fine if nobody has written it down - say so rather than inventing it.`)
182
+ }
183
+
184
+ for (const [tab, collection] of Object.entries(WORKBOOK_TABS)) {
185
+ const rows = present.has(tab) ? readRecordTab(readSheetGrid(workbook, tab), tab) : []
186
+ context[collection] = rows
187
+ if (!rows.length) warnings.push(`${tab} is empty.`)
188
+ }
189
+
190
+ const selfId = kebab(`${context.id} workbook`)
191
+ if (!context.sourceArtefacts.some((artefact) => artefact.id === selfId)) {
192
+ context.sourceArtefacts.push({
193
+ id: selfId,
194
+ title: context.title,
195
+ sourcePath: sourceDocument,
196
+ sourceType: 'filled-in template',
197
+ importedAt: new Date().toISOString()
198
+ })
199
+ }
200
+
201
+ return {
202
+ sourceDocument,
203
+ importedAt: new Date().toISOString(),
204
+ warnings,
205
+ projectContext: context,
206
+ sections
207
+ }
208
+ }
209
+
139
210
  function extractPurpose (lines) {
140
211
  const purposeLines = lines.filter((line) => {
141
212
  const lower = line.toLowerCase()
@@ -421,7 +492,11 @@ function camelCase (value) {
421
492
  return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
422
493
  }
423
494
 
424
- main().catch((error) => {
425
- console.error(error.message)
426
- process.exit(1)
427
- })
495
+ module.exports = { buildDraftFromWorkbook }
496
+
497
+ if (require.main === module) {
498
+ main().catch((error) => {
499
+ console.error(error.message)
500
+ process.exit(1)
501
+ })
502
+ }
@@ -0,0 +1,111 @@
1
+ const path = require('path')
2
+ const { openWorkbook, readSheetGrid } = require('./xlsx-grid')
3
+
4
+ // Reading a filled-in project-context template. Kept apart from the importer
5
+ // because that module loads a PDF parser, a zip reader and an XML parser to
6
+ // handle decks - none of which a spreadsheet needs, and all of which a test of
7
+ // this logic would otherwise have to load too.
8
+
9
+ const WORKBOOK_TABS = {
10
+ Users: 'users',
11
+ Channels: 'channels',
12
+ Policies: 'policies',
13
+ Constraints: 'constraints',
14
+ Risks: 'risks',
15
+ Milestones: 'milestones',
16
+ Facts: 'facts',
17
+ Sources: 'sourceArtefacts'
18
+ }
19
+
20
+
21
+ const OVERVIEW_FIELDS = ['id', 'title', 'summary', 'purpose', 'vision', 'problemStatement', 'serviceProposition']
22
+
23
+
24
+ function readWorkbookSections (documentPath) {
25
+ const workbook = openWorkbook(path.resolve(documentPath))
26
+ const present = new Set([...workbook.sheetFiles.keys()])
27
+
28
+ const sections = []
29
+ let number = 1
30
+
31
+ for (const tab of ['Overview', ...Object.keys(WORKBOOK_TABS)]) {
32
+ if (!present.has(tab)) continue
33
+ const grid = readSheetGrid(workbook, tab)
34
+ const text = []
35
+ for (const row of grid) {
36
+ if (!row) continue
37
+ const line = row.map((cell) => String(cell == null ? '' : cell).trim()).filter(Boolean).join(' | ')
38
+ if (line) text.push(line)
39
+ }
40
+ // The draft schema wants at least one line per section, and an empty tab is
41
+ // worth recording as empty rather than omitting - the review note is how
42
+ // somebody notices they left a tab blank.
43
+ sections.push({ number: number++, title: tab, text: text.length ? text : ['(no rows)'] })
44
+ }
45
+
46
+ if (!sections.length) {
47
+ throw new Error(
48
+ `${path.basename(documentPath)} has none of the expected tabs.\n` +
49
+ `Expected: Overview, ${Object.keys(WORKBOOK_TABS).join(', ')}.\n` +
50
+ 'Start from templates/project-context.xlsx in the installed package.'
51
+ )
52
+ }
53
+
54
+ return sections
55
+ }
56
+
57
+ function readOverview (grid) {
58
+ const values = {}
59
+ for (const row of grid) {
60
+ if (!row) continue
61
+ const field = String(row[0] == null ? '' : row[0]).trim()
62
+ const value = String(row[1] == null ? '' : row[1]).trim()
63
+ if (OVERVIEW_FIELDS.includes(field) && value) values[field] = value
64
+ }
65
+ return values
66
+ }
67
+
68
+
69
+ function readRecordTab (grid, tab) {
70
+ const headerIndex = grid.findIndex((row) => row && String(row[0] || '').trim() === 'id')
71
+ if (headerIndex === -1) {
72
+ throw new Error(`The ${tab} tab has no "id" column header. Start from templates/project-context.xlsx.`)
73
+ }
74
+
75
+ const headers = (grid[headerIndex] || []).map((cell) => String(cell == null ? '' : cell).trim())
76
+ const records = []
77
+ const seen = new Set()
78
+
79
+ for (let rowIndex = headerIndex + 1; rowIndex < grid.length; rowIndex++) {
80
+ const row = grid[rowIndex]
81
+ if (!row) continue
82
+
83
+ const id = String(row[0] == null ? '' : row[0]).trim()
84
+
85
+ // Three kinds of row are not records: an empty one, the guidance row the
86
+ // template ships (every cell parenthesised), and the worked example. All
87
+ // three are skipped so a template used exactly as shipped imports cleanly
88
+ // and an id that is genuinely malformed still reaches the validator, where
89
+ // it is reported rather than quietly dropped.
90
+ if (!id || id.startsWith('(') || id.startsWith('example-')) continue
91
+
92
+ const record = {}
93
+ for (let col = 0; col < headers.length; col++) {
94
+ const field = headers[col]
95
+ if (!field) continue
96
+ const value = String(row[col] == null ? '' : row[col]).trim()
97
+ if (value) record[field] = value
98
+ }
99
+
100
+ if (seen.has(id)) {
101
+ throw new Error(`The ${tab} tab uses the id "${id}" more than once (row ${rowIndex + 1}). Ids must be unique within a tab.`)
102
+ }
103
+ seen.add(id)
104
+ records.push(record)
105
+ }
106
+
107
+ return records
108
+ }
109
+
110
+
111
+ module.exports = { WORKBOOK_TABS, OVERVIEW_FIELDS, readWorkbookSections, readOverview, readRecordTab }
@@ -11,6 +11,7 @@ reads:
11
11
  - node_modules/@hippo-digital/hippocampus/docs/repeatable-research-round-ingestion.md
12
12
  - node_modules/@hippo-digital/hippocampus/docs/hippocampus-technical.md
13
13
  - node_modules/@hippo-digital/hippocampus/docs/source-model.md
14
+ - node_modules/@hippo-digital/hippocampus/templates/project-context.xlsx
14
15
  - hippocampus/inbox/project/
15
16
  - hippocampus/imports/project/[draft-id].review.md
16
17
  - hippocampus/imports/project/[draft-id].json
@@ -37,6 +38,10 @@ acceptance:
37
38
 
38
39
  ## Use when
39
40
  - A project overview deck or PDF needs to become a review-ready project-context draft.
41
+ - A filled-in copy of `templates/project-context.xlsx` needs importing. Prefer this
42
+ when the team is gathering context rather than working from one existing document:
43
+ the columns are the schema, so nothing has to be inferred from prose and the
44
+ structuring step below is already done.
40
45
  - You want one entrypoint for the no-promote import, draft structuring, and dry-run validation flow.
41
46
 
42
47
  ## Workflow
Binary file