@hippo-digital/hippocampus 2.4.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +19 -0
  3. package/assets/dist/hippocampus.css +1 -1
  4. package/assets/hippocampus.scss +34 -1
  5. package/bin/hippocampus.js +1 -1
  6. package/docs/add-project-context.md +225 -0
  7. package/docs/agent-roadmap.md +6 -1
  8. package/docs/agent-workflow.md +6 -1
  9. package/docs/ask-whats-already-known.md +159 -0
  10. package/docs/check-for-unintended-consequences.md +191 -0
  11. package/docs/colour-pairings.md +6 -0
  12. package/docs/components.md +7 -1
  13. package/docs/custom-agents-usage.md +6 -1
  14. package/docs/data-and-governance.md +188 -0
  15. package/docs/design-actions-and-decisions.md +5 -0
  16. package/docs/diagrams/README.md +44 -0
  17. package/docs/diagrams/evidence-flow.mmd +56 -0
  18. package/docs/diagrams/mermaid.config.json +20 -0
  19. package/docs/hippocampus-for-designers-and-researchers.md +9 -3
  20. package/docs/hippocampus-technical.md +7 -1
  21. package/docs/images/evidence-flow.svg +1 -0
  22. package/docs/import-a-research-round.md +233 -0
  23. package/docs/link-insights-to-needs.md +225 -0
  24. package/docs/prompt-architecture-guardrails.md +6 -1
  25. package/docs/repeatable-research-round-ingestion.md +9 -3
  26. package/docs/research-knowledge-graph.md +12 -4
  27. package/docs/research-source-file-conventions.md +7 -2
  28. package/docs/review-and-promote-a-draft.md +212 -0
  29. package/docs/source-model.md +7 -1
  30. package/docs/start-here.md +223 -0
  31. package/docs/turn-personas-into-users-and-needs.md +207 -0
  32. package/lib/create-router.js +26 -3
  33. package/lib/docs.js +288 -30
  34. package/lib/templates.js +1 -1
  35. package/package.json +1 -1
  36. package/scripts/consequences.js +7 -5
  37. package/scripts/import-project-context.js +17 -5
  38. package/scripts/import-research-deck.js +31 -6
  39. package/scripts/known.js +2 -2
  40. package/scripts/link-insights-to-needs.js +38 -13
  41. package/scripts/promote-project-context-draft.js +66 -15
  42. package/scripts/promote-research-draft.js +99 -12
  43. package/scripts/smoke-routes.js +8 -1
  44. package/scripts/sync-project-context.js +90 -12
  45. package/skills/ingest-project-context/SKILL.md +1 -1
  46. package/skills/skills.json +2 -2
  47. package/skills/structure-project-context-draft/SKILL.md +1 -1
  48. package/templates/project-context.xlsx +0 -0
  49. package/views/hippocampus/doc.html +15 -0
  50. package/views/hippocampus/docs.html +42 -13
  51. package/views/hippocampus/research.html +9 -4
@@ -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
+ }
@@ -4,17 +4,18 @@ const { spawnSync } = require('child_process')
4
4
  const { ProjectContextImportDraftSchema } = require('../lib/schema')
5
5
  const { createContextOrExit } = require('../lib/context')
6
6
  const ctx = createContextOrExit()
7
- const { knowledgeSourceDir, projectImportsDir } = ctx.paths
7
+ const { knowledgeSourceDir, projectImportsDir, projectManifestPath } = ctx.paths
8
8
 
9
9
  const projectContextPath = path.join(knowledgeSourceDir, 'project-context.json')
10
10
 
11
11
  function main () {
12
12
  const args = parseArgs(process.argv.slice(2))
13
- if (!args.draft) {
14
- throw new Error(`Usage: npx hippocampus promote project-context -- --draft ${path.relative(ctx.root, path.join(projectImportsDir, 'context-id.json'))} [--dry-run]`)
13
+ if (!args.draft || args.draft === true) {
14
+ throw new Error(`Usage: npx hippocampus promote project-context --draft ${path.relative(ctx.root, path.join(projectImportsDir, '<draft>.json'))} [--dry-run]${listDrafts()}`)
15
15
  }
16
16
 
17
- const draft = validateDraft(readJson(path.resolve(args.draft)))
17
+ const draftPath = resolveDraft(args.draft)
18
+ const draft = validateDraft(readJson(draftPath))
18
19
  // A project that has never recorded context has no project-context.json at
19
20
  // all: `init` cannot write one, because the schema requires a non-empty id,
20
21
  // title and summary and inventing those is worse than leaving the file out.
@@ -32,16 +33,15 @@ function main () {
32
33
  }
33
34
  const proposed = mergeProjectContext(current, draft.projectContext)
34
35
 
35
- console.log([
36
- `users: +${newCount(current.users, draft.projectContext.users)}`,
37
- `channels: +${newCount(current.channels, draft.projectContext.channels)}`,
38
- `policies: +${newCount(current.policies, draft.projectContext.policies)}`,
39
- `constraints: +${newCount(current.constraints, draft.projectContext.constraints)}`,
40
- `risks: +${newCount(current.risks, draft.projectContext.risks)}`,
41
- `milestones: +${newCount(current.milestones, draft.projectContext.milestones)}`,
42
- `facts: +${newCount(current.facts, draft.projectContext.facts)}`,
43
- `sourceArtefacts: +${newCount(current.sourceArtefacts, draft.projectContext.sourceArtefacts)}`
44
- ].join(', '))
36
+ // Promotion merges by id: a record the draft shares with source replaces it.
37
+ // So the summary says what changes as well as what is new - "+0" alone read
38
+ // as "nothing happened" when a corrected template had rewritten five rows.
39
+ const keys = ['users', 'channels', 'policies', 'constraints', 'risks', 'milestones', 'facts', 'sourceArtefacts']
40
+ console.log(keys.map((key) => {
41
+ const added = newCount(current[key], draft.projectContext[key])
42
+ const changed = changedCount(current[key], draft.projectContext[key])
43
+ return `${key}: +${added}${changed ? ` (${changed} updated)` : ''}`
44
+ }).join(', '))
45
45
 
46
46
  if (args.dryRun) {
47
47
  console.log('Dry run only. Source files were not changed.')
@@ -64,9 +64,48 @@ function main () {
64
64
  throw new Error('Promotion wrote project context, but knowledge validation failed. Review the promoted data.')
65
65
  }
66
66
 
67
+ markPromoted(draftPath)
67
68
  console.log('Project context draft promoted and knowledge validation passed.')
68
69
  }
69
70
 
71
+ /**
72
+ * The draft path a person types is relative to wherever they are; the one the
73
+ * import prints is relative to the project root. Accept both, and when neither
74
+ * exists, list the drafts there are rather than failing with a stack trace.
75
+ */
76
+ function resolveDraft (value) {
77
+ const found = [path.resolve(value), path.resolve(ctx.root, value)].find((candidate) => fs.existsSync(candidate))
78
+ if (found) return found
79
+ throw new Error(`No draft at ${value}.${listDrafts()}`)
80
+ }
81
+
82
+ function listDrafts () {
83
+ const drafts = fs.existsSync(projectImportsDir)
84
+ ? fs.readdirSync(projectImportsDir).filter((name) => name.endsWith('.json')).sort()
85
+ : []
86
+ const where = path.relative(ctx.root, projectImportsDir)
87
+ return drafts.length
88
+ ? `\nDrafts in ${where}:\n${drafts.map((name) => ` ${path.join(where, name)}`).join('\n')}`
89
+ : `\nThere are no drafts in ${where}. Run \`npx hippocampus import project-context\` to import the files in the inbox.`
90
+ }
91
+
92
+ /**
93
+ * `import project-context` keeps the list of what it has imported and
94
+ * promoted. Promoting with this command used to leave that list saying
95
+ * "imported", so the next import offered the draft for promotion again.
96
+ */
97
+ function markPromoted (draftPath) {
98
+ if (!fs.existsSync(projectManifestPath)) return
99
+ const manifest = readJson(projectManifestPath)
100
+ const item = (manifest.artefacts || []).find((artefact) =>
101
+ artefact.draftPath && path.resolve(ctx.root, artefact.draftPath) === draftPath)
102
+ if (!item || item.status === 'promoted') return
103
+ item.status = 'promoted'
104
+ item.promotedAt = new Date().toISOString()
105
+ manifest.updatedAt = item.promotedAt
106
+ writeJson(projectManifestPath, manifest)
107
+ }
108
+
70
109
  function validateDraft (draft) {
71
110
  const result = ProjectContextImportDraftSchema.safeParse(draft)
72
111
  if (result.success) return result.data
@@ -105,6 +144,11 @@ function mergeById (current, incoming) {
105
144
  ]))
106
145
  }
107
146
 
147
+ function changedCount (current, incoming) {
148
+ const existing = new Map(current.map((item) => [item.id, JSON.stringify(item)]))
149
+ return incoming.filter((item) => existing.has(item.id) && existing.get(item.id) !== JSON.stringify(item)).length
150
+ }
151
+
108
152
  function newCount (current, incoming) {
109
153
  const existingIds = new Set(current.map((item) => item.id))
110
154
  return incoming.filter((item) => !existingIds.has(item.id)).length
@@ -119,6 +163,8 @@ function parseArgs (args) {
119
163
  const key = camelCase(rawKey)
120
164
  if (value !== undefined) {
121
165
  parsed[key] = value
166
+ } else if (key === 'dryRun' || key === 'help') {
167
+ parsed[key] = true
122
168
  } else if (args[index + 1] && !args[index + 1].startsWith('--')) {
123
169
  parsed[key] = args[index + 1]
124
170
  index++
@@ -141,4 +187,9 @@ function camelCase (value) {
141
187
  return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
142
188
  }
143
189
 
144
- main()
190
+ try {
191
+ main()
192
+ } catch (error) {
193
+ console.error(error.message)
194
+ process.exit(1)
195
+ }
@@ -4,7 +4,7 @@ const { spawnSync } = require('child_process')
4
4
  const { ResearchImportDraftSchema } = require('../lib/schema')
5
5
  const { createContextOrExit } = require('../lib/context')
6
6
  const ctx = createContextOrExit()
7
- const { knowledgeSourceDir, researchImportsDir } = ctx.paths
7
+ const { knowledgeSourceDir, researchImportsDir, researchManifestPath } = ctx.paths
8
8
 
9
9
  const dataDir = knowledgeSourceDir
10
10
 
@@ -18,18 +18,27 @@ const collections = {
18
18
 
19
19
  function main () {
20
20
  const args = parseArgs(process.argv.slice(2))
21
- if (!args.draft) {
22
- throw new Error(`Usage: npx hippocampus promote research -- --draft ${path.relative(ctx.root, path.join(researchImportsDir, 'round-id.json'))} [--dry-run]`)
21
+ if (!args.draft || args.draft === true) {
22
+ throw new Error(`Usage: npx hippocampus promote research --draft ${path.relative(ctx.root, path.join(researchImportsDir, '<draft>.json'))} [--dry-run]`)
23
23
  }
24
24
 
25
- const draft = validateDraft(readJson(path.resolve(args.draft)))
25
+ const draftPath = resolveDraft(args.draft)
26
+ const draft = validateDraft(readJson(draftPath))
26
27
  const current = readCurrentCollections()
27
- const reused = reconcileSharedRecords(current, draft)
28
+
29
+ if (alreadyPromoted(current, draft)) {
30
+ console.log(`Already promoted: every insight and design action in ${path.relative(ctx.root, draftPath)} is already in hippocampus/source. Nothing was written.`)
31
+ if (!args.dryRun) markPromoted(draftPath)
32
+ return
33
+ }
34
+
35
+ const { reused, notes } = reconcileSharedRecords(current, draft)
28
36
  const proposed = mergeCollections(current, draft)
29
37
  validateNoDuplicateIds(current, draft)
30
38
  validateDraftReferences(proposed)
31
39
 
32
40
  if (reused.length) console.log(`Reusing existing records from earlier artefacts in this round: ${reused.join(', ')}`)
41
+ for (const note of notes) console.log(note)
33
42
 
34
43
  const counts = Object.keys(collections).map((key) => `${key}: +${(draft[key] || []).length}`)
35
44
  console.log(`Promotion checked: ${counts.join(', ')}`)
@@ -54,29 +63,100 @@ function main () {
54
63
  })
55
64
 
56
65
  if (validation.status !== 0) {
57
- throw new Error('Promotion wrote source files, but knowledge validation failed. Review the promoted data.')
66
+ throw new Error('Promotion wrote source files, but knowledge validation failed. Review the promoted data: `git diff hippocampus/source` shows what changed.')
58
67
  }
59
68
 
69
+ markPromoted(draftPath)
60
70
  console.log('Research draft promoted and knowledge validation passed.')
61
71
  }
62
72
 
73
+ /**
74
+ * Every place a draft path is printed - sync's report, the review file, this
75
+ * command's usage - writes it from the project root. So that is where it is
76
+ * looked for when it is not where the command was run, rather than failing
77
+ * from a subfolder with a stack trace about a file that is plainly there.
78
+ */
79
+ function resolveDraft (value) {
80
+ const found = [path.resolve(value), path.resolve(ctx.root, value)].find((candidate) => fs.existsSync(candidate))
81
+ if (found) return found
82
+
83
+ const drafts = fs.existsSync(researchImportsDir)
84
+ ? fs.readdirSync(researchImportsDir).filter((name) => name.endsWith('.json')).sort()
85
+ : []
86
+ const where = path.relative(ctx.root, researchImportsDir)
87
+ throw new Error([
88
+ `No draft at ${value}.`,
89
+ drafts.length
90
+ ? `Drafts in ${where}:\n${drafts.map((name) => ` ${path.join(where, name)}`).join('\n')}`
91
+ : `There are no drafts in ${where}. Run \`npx hippocampus research sync\` to import the files in the inbox.`
92
+ ].join('\n'))
93
+ }
94
+
95
+ /**
96
+ * A draft whose findings are all in source already has been promoted: by
97
+ * hand before promotion recorded itself in the manifest, or twice. Saying so
98
+ * is more use than failing on the first duplicate id.
99
+ */
100
+ function alreadyPromoted (current, draft) {
101
+ const records = [
102
+ ...(draft.insights || []).map((item) => ['insights', item.id]),
103
+ ...(draft.designActions || []).map((item) => ['designActions', item.id])
104
+ ]
105
+ if (!records.length) return false
106
+ const existing = { insights: idSet(current.insights), designActions: idSet(current.designActions) }
107
+ return records.every(([key, id]) => existing[key].has(id))
108
+ }
109
+
110
+ /**
111
+ * `research sync` keeps the list of what it has imported and promoted.
112
+ * Promoting with this command used to leave that list saying "imported", so
113
+ * the next sync offered the draft again and a yes failed on duplicate ids.
114
+ */
115
+ function markPromoted (draftPath) {
116
+ if (!fs.existsSync(researchManifestPath)) return
117
+ const manifest = readJson(researchManifestPath)
118
+ const item = (manifest.artefacts || []).find((artefact) =>
119
+ artefact.draftPath && path.resolve(ctx.root, artefact.draftPath) === draftPath)
120
+ if (!item || item.status === 'promoted') return
121
+ item.status = 'promoted'
122
+ item.promotedAt = new Date().toISOString()
123
+ manifest.updatedAt = item.promotedAt
124
+ writeJson(researchManifestPath, manifest)
125
+ }
126
+
63
127
  /**
64
128
  * A round is fieldwork, not a file, so several artefacts promote into the same
65
- * round and meet the same people. Re-promoting an identical round record, or a
129
+ * round and meet the same people. Re-promoting a round record, or a
66
130
  * participant already seen in a sibling artefact, is expected rather than a
67
131
  * collision - the duplicate check should only fire on genuinely conflicting data.
68
132
  *
69
- * Returns the ids that were absorbed rather than added, so the run says so out loud.
133
+ * A different title does mean a clash: the title comes from the round's
134
+ * folder, so two titles under one id are two rounds given the same number. A
135
+ * different date does not. Each file is dated from its own name when the
136
+ * folder has no date, and fieldwork runs over days, so the interview notes
137
+ * and the playback of one round routinely disagree. That used to refuse the
138
+ * second file outright; now the round keeps the date it was first promoted
139
+ * with, and the run says so.
140
+ *
141
+ * Returns the ids that were absorbed rather than added, and notes to print.
70
142
  */
71
143
  function reconcileSharedRecords (current, draft) {
72
144
  const reused = []
145
+ const notes = []
73
146
 
74
147
  const existingRounds = new Map(current.researchRounds.map((round) => [round.id, round]))
75
148
  draft.researchRounds = (draft.researchRounds || []).filter((round) => {
76
149
  const existing = existingRounds.get(round.id)
77
150
  if (!existing) return true
78
- if (existing.title !== round.title || existing.date !== round.date) {
79
- throw new Error(`research round ${round.id} already exists with a different title or date. Reconcile the draft against hippocampus/source/research-rounds.json before promoting.`)
151
+ if (existing.title !== round.title) {
152
+ throw new Error(
153
+ `Research round ${round.id} already exists with a different title: "${existing.title}", where this draft says "${round.title}".\n` +
154
+ 'Two rounds have been given the same number. If this is a different round, give it a new id in the draft; ' +
155
+ 'if it is the same round, make the title match hippocampus/source/research-rounds.json.')
156
+ }
157
+ if (existing.date !== round.date) {
158
+ notes.push(`Round ${round.id} keeps its date, ${existing.date}. This draft says ${round.date}. ` +
159
+ 'To change the round\'s date, edit it in hippocampus/source/research-rounds.json.')
80
160
  }
81
161
  reused.push(`round ${round.id}`)
82
162
  return false
@@ -109,7 +189,7 @@ function reconcileSharedRecords (current, draft) {
109
189
  })
110
190
  void draftIds
111
191
 
112
- return reused
192
+ return { reused, notes }
113
193
  }
114
194
 
115
195
  function validateDraft (draft) {
@@ -238,4 +318,11 @@ function camelCase (value) {
238
318
  return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
239
319
  }
240
320
 
241
- main()
321
+ try {
322
+ main()
323
+ } catch (error) {
324
+ // Every failure here is something to read and act on - a missing draft, a
325
+ // duplicate id, a dangling reference - so it gets its message, not a stack.
326
+ console.error(error.message)
327
+ process.exit(1)
328
+ }
@@ -1,6 +1,6 @@
1
1
  const { spawn } = require('child_process')
2
2
  const { createContextOrExit } = require('../lib/context')
3
- const { listDocs } = require('../lib/docs')
3
+ const { listDocs, listDocImages } = require('../lib/docs')
4
4
  const { allTemplates } = require('../lib/templates')
5
5
  const ctx = createContextOrExit()
6
6
 
@@ -76,6 +76,13 @@ function buildRoutes (basePath, knowledge) {
76
76
  routes.add(`${basePath}/docs/${doc.slug}`)
77
77
  }
78
78
 
79
+ // A guide that embeds a diagram the viewer cannot serve still returns 200 -
80
+ // with a broken image in it. Checking the images themselves is the only way
81
+ // that shows up before somebody reads the page.
82
+ for (const image of listDocImages()) {
83
+ routes.add(`${basePath}/docs/images/${image}`)
84
+ }
85
+
79
86
  // Detail pages are generated per record, so check a sample rather than all
80
87
  // of them - 132 needs would make the smoke test a load test.
81
88
  for (const collection of [
@@ -7,20 +7,56 @@ const { createContextOrExit } = require('../lib/context')
7
7
  const ctx = createContextOrExit()
8
8
  const { projectInboxDir, projectImportsDir, manifestsDir, projectManifestPath } = ctx.paths
9
9
 
10
- const supportedExtensions = new Set(['.pptx', '.pdf'])
10
+ // `hippocampus import project-context` - with no file, imports every new file
11
+ // in hippocampus/inbox/project; given a file, imports that one. Either way each
12
+ // file becomes a draft in hippocampus/imports/project and is recorded in the
13
+ // project manifest, so promotion and later runs know what is already done.
14
+ //
15
+ // The command used to point straight at the single-file importer, which needs
16
+ // --document, --context-id and --title. The skills, the guides and the
17
+ // template card on the docs page all said `import project-context` on its own,
18
+ // or with a file, so every documented way of running it stopped at a usage
19
+ // message, and this inbox sync was never reachable at all.
20
+ //
21
+ // A filled-in copy of templates/project-context.xlsx is the input that needs
22
+ // no guessing, and this sync skipped it: only decks and PDFs were read.
23
+ const supportedExtensions = new Set(['.pptx', '.pdf', '.xlsx'])
24
+
25
+ const USAGE = `Usage: npx hippocampus import project-context [file ...] [--dry-run] [--no-promote] [--yes]
26
+
27
+ With no file, imports every new file in ${path.relative(ctx.root, projectInboxDir) || '.'}.
28
+ A file can be a filled-in copy of templates/project-context.xlsx (the reliable
29
+ route), a PowerPoint deck (.pptx) or a PDF. Each becomes a draft in
30
+ ${path.relative(ctx.root, projectImportsDir)} to review before it is promoted.
31
+
32
+ --dry-run list what would be imported; write nothing
33
+ --no-promote import only; do not offer to promote
34
+ --yes promote the new drafts without asking
35
+ --context-id name for the draft (one file only; default: from the file name)
36
+ --title title for a deck or PDF (one file only; default: the file name).
37
+ A filled-in template takes its id and title from its Overview tab.`
11
38
 
12
39
  async function main () {
13
40
  const args = parseArgs(process.argv.slice(2))
41
+ if (args.help) {
42
+ console.log(USAGE)
43
+ return
44
+ }
14
45
  const sourceDir = path.resolve(args.source || projectInboxDir)
15
46
 
16
47
  fs.mkdirSync(sourceDir, { recursive: true })
17
48
  fs.mkdirSync(projectImportsDir, { recursive: true })
18
49
  fs.mkdirSync(manifestsDir, { recursive: true })
19
50
 
51
+ const named = [...args._, ...(typeof args.document === 'string' ? [args.document] : [])].map(resolveFile)
20
52
  const manifest = readManifest()
21
- const files = listFiles(sourceDir)
53
+ const files = named.length ? named : listFiles(sourceDir)
22
54
  const supported = files.filter((file) => supportedExtensions.has(path.extname(file).toLowerCase()))
23
55
  const unsupported = files.filter((file) => !supportedExtensions.has(path.extname(file).toLowerCase()))
56
+ // A file whose import failed (so it has no draft) is tried again rather than
57
+ // reported as known: the failure is usually something fixed since. A failed
58
+ // promotion keeps its entry - its draft may hold corrections.
59
+ manifest.artefacts = manifest.artefacts.filter((item) => !(item.status === 'failed' && !item.draftPath))
24
60
  const knownHashes = new Map(manifest.artefacts.map((item) => [item.sha256, item]))
25
61
  const existingIds = new Set(manifest.artefacts.map((item) => item.id))
26
62
  const imported = []
@@ -35,8 +71,13 @@ async function main () {
35
71
  continue
36
72
  }
37
73
 
38
- const id = uniqueId(kebab(path.basename(file, path.extname(file))), existingIds)
74
+ const id = uniqueId(kebab(named.length === 1 && typeof args.contextId === 'string'
75
+ ? args.contextId
76
+ : path.basename(file, path.extname(file))), existingIds)
39
77
  existingIds.add(id)
78
+ const title = named.length === 1 && typeof args.title === 'string'
79
+ ? args.title
80
+ : path.basename(file, path.extname(file))
40
81
  const draftPath = path.join(projectImportsDir, `${id}.json`)
41
82
  const reviewPath = path.join(projectImportsDir, `${id}.review.md`)
42
83
 
@@ -45,7 +86,7 @@ async function main () {
45
86
  path.join(ctx.package.scriptsDir, 'import-project-context.js'),
46
87
  `--document=${file}`,
47
88
  `--context-id=${id}`,
48
- `--title=${path.basename(file, path.extname(file))}`,
89
+ `--title=${title}`,
49
90
  `--output-dir=${projectImportsDir}`
50
91
  ], {
51
92
  cwd: ctx.root,
@@ -90,12 +131,16 @@ async function main () {
90
131
  manifest.updatedAt = new Date().toISOString()
91
132
  if (!args.dryRun) writeManifest(manifest)
92
133
 
93
- report({ sourceDir, files, supported, unsupported, imported, alreadyKnown, promotable, dryRun: args.dryRun })
134
+ report({ sourceDir, named, files, supported, unsupported, imported, alreadyKnown, promotable, dryRun: args.dryRun })
94
135
 
95
- if (args.dryRun || args.noPromote || !promotable.length) return
136
+ if (args.dryRun || !promotable.length) return
96
137
 
97
- const shouldPromote = args.yes || await confirm('Promote imported, unpromoted project context drafts now?')
98
- if (!shouldPromote) return
138
+ const shouldPromote = !args.noPromote && (args.yes || await confirm('Promote imported, unpromoted project context drafts now?'))
139
+ if (!shouldPromote) {
140
+ console.log('\nNext: read each review file, correct the draft if it needs it, then promote it:')
141
+ for (const item of promotable) console.log(` npx hippocampus promote project-context --draft ${item.draftPath}`)
142
+ return
143
+ }
99
144
 
100
145
  for (const item of promotable) {
101
146
  // Run the sibling script directly rather than `npm run <script>`. Those npm
@@ -128,15 +173,23 @@ async function main () {
128
173
  console.log(`Promotion manifest updated at ${relative(projectManifestPath)}`)
129
174
  }
130
175
 
176
+ // Flags that never take a value. Without this, `--no-promote overview.pptx`
177
+ // read the file as the value of --no-promote and imported the whole inbox.
178
+ const BOOLEAN_FLAGS = new Set(['dryRun', 'noPromote', 'yes', 'help'])
179
+
131
180
  function parseArgs (args) {
132
- const parsed = {}
181
+ const parsed = { _: [] }
133
182
  for (let index = 0; index < args.length; index++) {
134
183
  const arg = args[index]
135
- if (!arg.startsWith('--')) continue
184
+ if (arg === '--root') { index++; continue }
185
+ if (arg === '--') continue
186
+ if (!arg.startsWith('--')) { parsed._.push(arg); continue }
136
187
  const [rawKey, value] = arg.slice(2).split('=', 2)
137
188
  const key = camelCase(rawKey)
138
189
  if (value !== undefined) {
139
190
  parsed[key] = value
191
+ } else if (BOOLEAN_FLAGS.has(key)) {
192
+ parsed[key] = true
140
193
  } else if (args[index + 1] && !args[index + 1].startsWith('--')) {
141
194
  parsed[key] = args[index + 1]
142
195
  index++
@@ -147,6 +200,17 @@ function parseArgs (args) {
147
200
  return parsed
148
201
  }
149
202
 
203
+ // A file named on the command line, from where it was run or from the
204
+ // project root - the same two places a draft path is looked for.
205
+ function resolveFile (value) {
206
+ const found = [path.resolve(value), path.resolve(ctx.root, value)].find((candidate) => fs.existsSync(candidate))
207
+ if (!found) throw new Error(`No file at ${value}.`)
208
+ if (!supportedExtensions.has(path.extname(found).toLowerCase())) {
209
+ throw new Error(`${value} is not a file project context can be imported from. Use a filled-in copy of templates/project-context.xlsx, a PowerPoint deck (.pptx) or a PDF.`)
210
+ }
211
+ return found
212
+ }
213
+
150
214
  function readManifest () {
151
215
  if (!fs.existsSync(projectManifestPath)) {
152
216
  return {
@@ -176,8 +240,22 @@ function hashFile (file) {
176
240
  return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
177
241
  }
178
242
 
179
- function report ({ sourceDir, files, supported, unsupported, imported, alreadyKnown, promotable, dryRun }) {
180
- console.log(`Project context inbox: ${relative(sourceDir)}`)
243
+ function report ({ sourceDir, named, files, supported, unsupported, imported, alreadyKnown, promotable, dryRun }) {
244
+ if (named.length) {
245
+ for (const item of alreadyKnown) {
246
+ console.log(`${item.sourcePath} was imported before, as ${item.id}.${item.status === 'promoted' ? ' It has been promoted. Nothing to do.' : ''}`)
247
+ }
248
+ if (imported.length) {
249
+ console.log(`${dryRun ? 'Would import' : 'Imported'}:`)
250
+ for (const item of imported) console.log(`- ${item.id}: ${item.reviewPath}`)
251
+ }
252
+ if (promotable.length) {
253
+ console.log('Drafts not yet promoted:')
254
+ for (const item of promotable) console.log(`- ${item.id}: ${item.draftPath}`)
255
+ }
256
+ return
257
+ }
258
+ console.log(`Project context inbox: ${relative(sourceDir) || '.'}`)
181
259
  console.log(`Files found: ${files.length}`)
182
260
  console.log(`Supported files: ${supported.length}`)
183
261
  console.log(`New imports${dryRun ? ' found' : ' created'}: ${imported.length}`)
@@ -33,7 +33,7 @@ guardrails:
33
33
  acceptance:
34
34
  - Sync and structuring steps complete without canonical source edits.
35
35
  - Unsupported overview claims are omitted or flagged as gaps.
36
- - npx hippocampus promote project-context -- --dry-run passes.
36
+ - npx hippocampus promote project-context -- --draft hippocampus/imports/project/[draft-id].json --dry-run passes.
37
37
  ---
38
38
 
39
39
  # Ingest project context
@@ -274,7 +274,7 @@
274
274
  "acceptance": [
275
275
  "Sync and structuring steps complete without canonical source edits.",
276
276
  "Unsupported overview claims are omitted or flagged as gaps.",
277
- "npx hippocampus promote project-context -- --dry-run passes."
277
+ "npx hippocampus promote project-context -- --draft hippocampus/imports/project/[draft-id].json --dry-run passes."
278
278
  ]
279
279
  },
280
280
  {
@@ -442,7 +442,7 @@
442
442
  "acceptance": [
443
443
  "The draft keeps source metadata and extracted text intact.",
444
444
  "Unsupported policy, risk, or milestone claims are left out or called out as gaps.",
445
- "npx hippocampus promote project-context -- --dry-run passes."
445
+ "npx hippocampus promote project-context -- --draft hippocampus/imports/project/[draft-id].json --dry-run passes."
446
446
  ]
447
447
  },
448
448
  {
@@ -27,7 +27,7 @@ guardrails:
27
27
  acceptance:
28
28
  - The draft keeps source metadata and extracted text intact.
29
29
  - Unsupported policy, risk, or milestone claims are left out or called out as gaps.
30
- - npx hippocampus promote project-context -- --dry-run passes.
30
+ - npx hippocampus promote project-context -- --draft hippocampus/imports/project/[draft-id].json --dry-run passes.
31
31
  ---
32
32
 
33
33
  # Structure project context draft
Binary file
@@ -1,4 +1,5 @@
1
1
  {% extends "hippocampus/_layout.html" %}
2
+ {% from "nhsuk/components/pagination/macro.njk" import pagination %}
2
3
 
3
4
  {% block pageTitle %}{{ doc.title }}{% endblock %}
4
5
 
@@ -6,5 +7,19 @@
6
7
  <article class="knowledge-doc">
7
8
  {{ doc.html | safe }}
8
9
  </article>
10
+
11
+ {#
12
+ Reading order runs across the whole guide, so the page after Start here is
13
+ the first recipe rather than a dead end. The section a page belongs to is
14
+ in the trail above it.
15
+ #}
16
+ {% if doc.previous or doc.next %}
17
+ {{ pagination({
18
+ previous: { href: basePath ~ "/docs/" ~ doc.previous.slug, labelText: doc.previous.title } if doc.previous else undefined,
19
+ next: { href: basePath ~ "/docs/" ~ doc.next.slug, labelText: doc.next.title } if doc.next else undefined,
20
+ ariaLabel: "Previous and next guide"
21
+ }) }}
22
+ {% endif %}
23
+
9
24
  <p class="knowledge-muted">@hippo-digital/hippocampus {{ packageVersion }}</p>
10
25
  {% endblock %}