@hippo-digital/hippocampus 1.0.0-rc.5 → 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
@@ -62,6 +62,87 @@ three things the release gate's hand-written stand-in could not.
62
62
  The viewer's landing page no longer captions itself "Prototype Kit add-on
63
63
  spike", which was a development-era label every install would have seen.
64
64
 
65
+ ### The blueprint importer
66
+
67
+ Run against a real service blueprint it produced **88 unmapped rows and one
68
+ mapped**. Four faults, all silent:
69
+
70
+ - **It did not speak the schema's vocabulary.** A blueprint authored against the
71
+ data model uses `Frontstage`, `Backstage`, `Support processes`,
72
+ `Data dependencies`, `Security and governance`, `Exception handling` and
73
+ `Future state`. The triage table matched `Back office`, `Data`, `Processes`,
74
+ `Exception journeys` and `Future steps` - a different dialect. Both are now
75
+ covered, along with `Screen` and `User action`.
76
+ - **Two lanes were unreachable at any label.** `frontstage` and
77
+ `securityAndGovernance` appeared nowhere as a destination, so no spelling
78
+ could have imported them.
79
+ - **Step names came from the wrong row, and the first two lanes were dropped.**
80
+ The header was guessed as whichever of the first six rows had the most
81
+ populated cells, read the names from the row *after* it, and started lanes two
82
+ rows further down. Steps were named after the contents of the User action row,
83
+ and `Screen` and `User action` never appeared at all. The header is now the row
84
+ above the first labelled row, which is structural rather than a guess.
85
+ - **Ordinary tables were forced into blueprint shape.** An Evidence tab became 74
86
+ lanes named after repeated step names. A blueprint's step-header row has an
87
+ empty column 0 and its lane labels are distinct; a table has neither. A sheet
88
+ failing either test is read flat, which keeps every cell for review.
89
+
90
+ The same file now maps every lane, names its steps correctly and classifies all
91
+ four sheets, with nothing unmapped.
92
+
93
+ The grid logic is exported and covered by unit tests - `npm run test:unit`, also
94
+ run by the release gate. They are the package's first.
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
+
65
146
  ### Validation
66
147
 
67
148
  - Three tiers: errors are broken references, warnings are gaps worth filling,
@@ -74,6 +155,14 @@ spike", which was a development-era label every install would have seen.
74
155
  pointed at `<host>/node_modules/apps/demo` and failed every check. The
75
156
  release gate now runs shipped commands against a real install rather than
76
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.
77
166
 
78
167
  ### Data contract
79
168
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hippo-digital/hippocampus",
3
- "version": "1.0.0-rc.5",
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,9 +11,11 @@
11
11
  "index.js",
12
12
  "bin",
13
13
  "lib",
14
+ "!lib/__tests__",
14
15
  "views",
15
16
  "assets",
16
17
  "scripts",
18
+ "!scripts/__tests__",
17
19
  "skills",
18
20
  "agents",
19
21
  "instructions",
@@ -2,7 +2,6 @@ const fs = require('fs')
2
2
  const path = require('path')
3
3
  const { openWorkbook, readSheetGrid } = require('./lib/xlsx-grid')
4
4
  const { createContextOrExit } = require('../lib/context')
5
- const ctx = createContextOrExit()
6
5
 
7
6
  // Generic triage mapping from common service-blueprint swimlane vocabulary to
8
7
  // where it belongs in Hippocampus's knowledge model (see
@@ -10,6 +9,19 @@ const ctx = createContextOrExit()
10
9
  // "unmapped" and is flagged for a manual decision - this list intentionally
11
10
  // holds only generic blueprint/service-design terms, not any one project's
12
11
  // specific persona or team names, so the same rules apply to any spreadsheet.
12
+ // Generic triage mapping from service-blueprint swimlane vocabulary to where it
13
+ // belongs in Hippocampus's knowledge model (see docs/source-model.md). Anything
14
+ // that doesn't match falls through as "unmapped" and is flagged for a manual
15
+ // decision. This list intentionally holds only generic blueprint/service-design
16
+ // terms, not any one project's persona or team names.
17
+ //
18
+ // It covers BOTH dialects, because the first version covered only one and not
19
+ // the important one. Every JourneyStep field name is a lane label somebody will
20
+ // write - a blueprint authored against the schema used `Frontstage`,
21
+ // `Backstage`, `Support processes`, `Data dependencies`,
22
+ // `Security and governance`, `Exception handling` and `Future state`, and the
23
+ // table matched none of them. `frontstage` and `securityAndGovernance` had no
24
+ // destination at all, so those lanes were unreachable under any label.
13
25
  const SWIMLANE_TRIAGE = [
14
26
  // Open questions and WIP markers are checked first so they take priority
15
27
  // over the more generic keyword matches below (e.g. "Do we need a row for
@@ -17,18 +29,21 @@ const SWIMLANE_TRIAGE = [
17
29
  { match: /^do we need/i, destination: 'assumption', note: 'An open question row, not step content.' },
18
30
  { match: /unhappy path/i, destination: 'assumption', note: 'Likely deserves its own scenario/journey once detailed, rather than a lane on this one.' },
19
31
 
20
- { match: /^user groups$/i, destination: 'users', note: 'One User record per distinct persona named in this row.' },
21
- { match: /^(external )?user steps/i, destination: 'journeyStep.userAction', note: 'What the user actually does at this step.' },
22
- { match: /exception journeys/i, destination: 'journeyStep.exceptionHandling', note: '' },
23
- { match: /^back ?office/i, destination: 'journeyStep.backstage', note: '' },
24
- { match: /future steps?$/i, destination: 'journeyStep.futureState', note: 'Proposed/target-state, not current fact.' },
32
+ { match: /^user groups?$/i, destination: 'users', note: 'One User record per distinct persona named in this row.' },
33
+ { match: /^screens?$/i, destination: 'journeyStep.screenIds', note: 'Match each route to an existing Screen record, or add one.' },
34
+ { match: /^((external )?user steps|user actions?|what the user does)/i, destination: 'journeyStep.userAction', note: 'What the user actually does at this step.' },
35
+ { match: /^front ?stage|^front.of.house/i, destination: 'journeyStep.frontstage', note: 'What the user can see at this step.' },
36
+ { match: /^back ?stage|^back ?office/i, destination: 'journeyStep.backstage', note: '' },
37
+ { match: /^(support )?processes/i, destination: 'journeyStep.supportProcesses', note: '' },
38
+ { match: /^data( dependenc(y|ies))?$/i, destination: 'journeyStep.dataDependencies', note: '' },
39
+ { match: /^(security|governance|security and governance|information governance)/i, destination: 'journeyStep.securityAndGovernance', note: '' },
25
40
  { match: /^pain points/i, destination: 'journeyStep.painPoints', note: '' },
26
- { match: /^data$/i, destination: 'journeyStep.dataDependencies', note: '' },
27
- { match: /^processes/i, destination: 'journeyStep.supportProcesses', note: '' },
28
- { match: /needs? linked to (jira|a ticket)/i, destination: 'needs', note: 'Need.statement + Need.reference (ticket ID).' },
29
- { match: /^backlog status/i, destination: 'projectContext.facts', note: '' },
41
+ { match: /^exception (handling|journeys)|^edge cases/i, destination: 'journeyStep.exceptionHandling', note: '' },
42
+ { match: /^future (state|steps?)$/i, destination: 'journeyStep.futureState', note: 'Proposed/target-state, not current fact.' },
43
+ { match: /needs? linked to (jira|a ticket)/i, destination: 'needs', note: 'Ticket references, not needs - link to the existing Need records instead.' },
44
+ { match: /^backlog status/i, destination: 'unmapped', note: 'Delivery tracking, not design knowledge. Usually left out.' },
30
45
  { match: /^notes$/i, destination: 'projectContext.facts', note: '' },
31
- { match: /^opportunities/i, destination: 'assumption', note: 'One Assumption per opportunity.' },
46
+ { match: /^opportunities/i, destination: 'assumption', note: 'Proposed, not observed - record as an assumption until evidenced.' },
32
47
  { match: /^systems/i, destination: 'projectContext.channels', note: '' },
33
48
  { match: /^sources$/i, destination: 'evidence', note: '' }
34
49
  ]
@@ -43,7 +58,7 @@ async function main () {
43
58
  const workbook = openWorkbook(documentPath)
44
59
 
45
60
  const draft = {
46
- sourceDocument: path.relative(ctx.root, documentPath),
61
+ sourceDocument: path.relative(createContextOrExit().root, documentPath),
47
62
  importedAt: new Date().toISOString(),
48
63
  note: 'Review artefact only - nothing here has been written to the project source yet. Decide, sheet by sheet and row by row, whether any identifying details should be genericized before promoting content into <project>/source/*.json.',
49
64
  sheets: Object.fromEntries(
@@ -74,45 +89,86 @@ async function main () {
74
89
  * silently dropping its content.
75
90
  */
76
91
  function extractSheet (workbook, sheetName) {
77
- const grid = readSheetGrid(workbook, sheetName)
78
- const { steps, headerRowIndex } = buildSteps(grid)
79
- const swimlanes = groupIntoSwimlanes(grid, steps, headerRowIndex + 2)
92
+ return extractFromGrid(readSheetGrid(workbook, sheetName))
93
+ }
94
+
95
+ function extractFromGrid (grid) {
96
+ const { steps, laneStartRow, stepHeaderIsAboveLabels } = buildSteps(grid)
97
+ const swimlanes = groupIntoSwimlanes(grid, steps, laneStartRow)
80
98
 
81
99
  // A handful of stray column-0 values isn't enough evidence that a sheet
82
100
  // follows the swimlane convention - most of its actual content needs to
83
101
  // have landed inside a swimlane, or this isn't really a step x lane
84
102
  // blueprint and forcing that shape on it would silently drop everything
85
103
  // that came before the first (possibly late, possibly sparse) label.
86
- const contentCells = flattenCells(grid.slice(headerRowIndex + 2)).length
104
+ const contentCells = flattenCells(grid.slice(laneStartRow)).length
87
105
  const capturedCells = swimlanes.reduce(
88
106
  (sum, swimlane) => sum + Object.values(swimlane.cellsByStep).reduce((n, v) => n + asList(v).length, 0),
89
107
  0
90
108
  )
91
109
 
92
- if (swimlanes.length && contentCells > 0 && capturedCells / contentCells >= 0.5) {
110
+ // Two structural tests separate a blueprint from an ordinary table, because
111
+ // both have a populated column 0 and both passed the coverage test on their
112
+ // own - an Evidence tab came out as 74 lanes named after repeated step names,
113
+ // and a Sources tab as 8 lanes named after its ID column.
114
+ //
115
+ // 1. A blueprint's step-header row has an EMPTY column 0 - the corner above
116
+ // the lane labels. A table's header row names that column ("Source ID").
117
+ // 2. Each lane appears once. Duplicate labels mean column 0 holds data.
118
+ //
119
+ // A blueprint that does label its corner cell is read as flat, which keeps
120
+ // every cell for manual review. Wrongly flat loses nothing; wrongly blueprint
121
+ // invents a structure and buries the content.
122
+ const labels = swimlanes.map((swimlane) => swimlane.label)
123
+ const labelsAreUnique = new Set(labels).size === labels.length
124
+
125
+ if (stepHeaderIsAboveLabels && swimlanes.length && labelsAreUnique &&
126
+ contentCells > 0 && capturedCells / contentCells >= 0.5) {
93
127
  return { shape: 'blueprint', steps: steps.map((step) => step.label), swimlanes }
94
128
  }
95
129
 
96
130
  return { shape: 'flat', cells: flattenCells(grid) }
97
131
  }
98
132
 
133
+ /**
134
+ * Finds the row of step names and the row the lanes start on.
135
+ *
136
+ * A blueprint's shape is: some number of title/phase rows, then a row of step
137
+ * names with an empty column 0, then one labelled row per lane. So the step
138
+ * header is the row immediately above the first labelled row - structural, and
139
+ * true whether there are zero title rows or three.
140
+ *
141
+ * The previous version guessed the header as whichever of the first six rows
142
+ * had the most populated cells, then read the step names from the row AFTER it
143
+ * and started lanes two rows later. On a real blueprint that named the steps
144
+ * after the contents of the User action row and silently dropped the first two
145
+ * lanes entirely.
146
+ */
99
147
  function buildSteps (grid) {
100
- // The step-header row is whichever of the first few rows has the most
101
- // populated columns - generic enough to not assume a fixed row number.
102
- const candidateRows = grid.slice(0, 6).map((row, index) => ({ row: row || [], index }))
103
- const headerRowIndex = candidateRows.reduce((best, candidate) =>
104
- (candidate.row.filter(Boolean).length > (candidateRows[best]?.row.filter(Boolean).length || 0) ? candidate.index : best), 0)
148
+ // A lane row has a label AND content beside it. A title row ("Patient search
149
+ // blueprint" in A1) has the label and nothing else, and taking it as the
150
+ // first lane puts the header above the top of the sheet and finds no steps
151
+ // at all. Requiring content beside the label tells them apart.
152
+ const firstLabelRow = grid.findIndex((row) => row && row[0] && row.slice(1).filter(Boolean).length > 0)
153
+
154
+ if (firstLabelRow === -1) return { steps: [], headerRowIndex: 0, laneStartRow: grid.length, stepHeaderIsAboveLabels: false }
155
+
156
+ // Usually the header sits above the first label. A sheet that puts a corner
157
+ // label in column 0 of its header row ("Step", "Stage") has no row above to
158
+ // take, so the header is that row itself and the lanes start below it.
159
+ const above = firstLabelRow > 0 ? (grid[firstLabelRow - 1] || []) : []
160
+ const aboveHasSteps = above.slice(1).filter(Boolean).length > 0
161
+
162
+ const headerRowIndex = aboveHasSteps ? firstLabelRow - 1 : firstLabelRow
163
+ const laneStartRow = aboveHasSteps ? firstLabelRow : firstLabelRow + 1
105
164
 
106
165
  const headerRow = grid[headerRowIndex] || []
107
- const nextRow = grid[headerRowIndex + 1] || []
108
166
  const steps = []
109
-
110
- for (let col = 1; col < Math.max(headerRow.length, nextRow.length); col++) {
111
- const label = nextRow[col] || headerRow[col]
112
- if (label) steps.push({ column: col, label: String(label).trim() })
167
+ for (let col = 1; col < headerRow.length; col++) {
168
+ if (headerRow[col]) steps.push({ column: col, label: String(headerRow[col]).trim() })
113
169
  }
114
170
 
115
- return { steps, headerRowIndex }
171
+ return { steps, headerRowIndex, laneStartRow, stepHeaderIsAboveLabels: aboveHasSteps }
116
172
  }
117
173
 
118
174
  function groupIntoSwimlanes (grid, steps, startRow) {
@@ -236,7 +292,14 @@ function parseArgs (args) {
236
292
  return parsed
237
293
  }
238
294
 
239
- main().catch((error) => {
240
- console.error(error.message)
241
- process.exit(1)
242
- })
295
+ // Exported so the grid logic can be tested without a workbook or a project:
296
+ // these are the parts that were silently wrong, and they are pure functions of
297
+ // a grid.
298
+ module.exports = { buildSteps, groupIntoSwimlanes, extractFromGrid, triageFor }
299
+
300
+ if (require.main === module) {
301
+ main().catch((error) => {
302
+ console.error(error.message)
303
+ process.exit(1)
304
+ })
305
+ }
@@ -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