@hippo-digital/hippocampus 2.1.0 → 2.3.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.
- package/CHANGELOG.md +106 -0
- package/README.md +26 -0
- package/agents/knowledge-builder.md +1 -0
- package/agents/workflow-orchestrator.md +1 -0
- package/bin/hippocampus.js +2 -0
- package/lib/brief.js +115 -0
- package/lib/consequences.js +348 -0
- package/lib/mcp-server.js +193 -0
- package/package.json +10 -2
- package/scripts/consequences.js +147 -0
- package/scripts/mcp.js +86 -0
- package/skills/find-unintended-consequences/SKILL.md +124 -0
- package/skills/skills.json +33 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,111 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.3.0
|
|
4
|
+
|
|
5
|
+
`hippocampus mcp` serves the knowledge base to agents over MCP, read-only, so an
|
|
6
|
+
agent building or reviewing a journey can ask what is already known instead of
|
|
7
|
+
being handed a copy of it. Ported from Ed Hiley's Design Brain server in the NAER
|
|
8
|
+
prototype, with the tool names kept so agents already written against it work
|
|
9
|
+
unchanged.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx hippocampus mcp # HTTP on http://127.0.0.1:3100/mcp
|
|
13
|
+
npx hippocampus mcp --stdio # for a client that starts the server itself
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Six tools, all `design_brain_*`:
|
|
17
|
+
|
|
18
|
+
- **`design_brain_brief`** - start here. Give it a role, scenario, journey or
|
|
19
|
+
build spec and it returns one brief: the needs, scenarios with their edge
|
|
20
|
+
cases, journey steps, build-spec acceptance criteria, screens, decisions,
|
|
21
|
+
insights and design actions, each with its record id. Assumptions are kept in
|
|
22
|
+
their own section as beliefs, not research. A subject that matches nothing
|
|
23
|
+
says so rather than returning everything.
|
|
24
|
+
- **`design_brain_known`** - `hippocampus known` on a topic.
|
|
25
|
+
- **`design_brain_consequences`** - `hippocampus consequences` on a scenario id.
|
|
26
|
+
New; the NAER server did not have it.
|
|
27
|
+
- **`design_brain_overview`** - record counts, scenario ids, build specs and the
|
|
28
|
+
skills this package ships.
|
|
29
|
+
- **`design_brain_read`** - a file or folder in the project.
|
|
30
|
+
- **`design_brain_ask`** - a free question, answered by a Gemini model that
|
|
31
|
+
calls the tools above. Optional: it needs `GEMINI_API_KEY`,
|
|
32
|
+
`DESIGN_BRAIN_MODEL` and `@google/genai` installed in the host (an optional
|
|
33
|
+
peer), and says it is off when any of them is missing. Every other tool runs
|
|
34
|
+
without a model.
|
|
35
|
+
|
|
36
|
+
`known` and `consequences` answer through the package's own commands, so the
|
|
37
|
+
MCP answer and the terminal answer are the same answer.
|
|
38
|
+
|
|
39
|
+
It binds to 127.0.0.1 only. `DESIGN_BRAIN_MCP_PORT` changes the port and
|
|
40
|
+
`DESIGN_BRAIN_MCP_LOG=<file>` appends each call and its answer to a file.
|
|
41
|
+
|
|
42
|
+
`design_brain_read` is confined to the project root, and refuses `.env*`,
|
|
43
|
+
`.git`, `.npmrc` and `node_modules` anywhere in the path. The NAER version would
|
|
44
|
+
serve `.env`, which is where `GEMINI_API_KEY` lives.
|
|
45
|
+
|
|
46
|
+
`@modelcontextprotocol/sdk` is a new dependency. The install gate now checks
|
|
47
|
+
that `hippocampus mcp` loads in a real install.
|
|
48
|
+
|
|
49
|
+
## 2.2.0
|
|
50
|
+
|
|
51
|
+
`hippocampus consequences <scenario-id>` runs a new or changed journey against the
|
|
52
|
+
users the knowledge base already knows, before the journey is designed. A
|
|
53
|
+
`find-unintended-consequences` skill ships with it, and `knowledge-builder` and
|
|
54
|
+
`workflow-orchestrator` list it.
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npx hippocampus consequences scenario-fire-safety-officer-visit-list-check
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The case it was built for is a new persona arriving - optometrists on NCRS - and the
|
|
61
|
+
question of whether their journeys will hurt the people already using the service.
|
|
62
|
+
The input is a scenario; the output is:
|
|
63
|
+
|
|
64
|
+
- **This user in the research.** Whether any participant's role matches the new
|
|
65
|
+
persona. Matched on the words that tell this role apart from the other users, so
|
|
66
|
+
"safety" in *fire safety officer* does not match an *MRI safety officer*.
|
|
67
|
+
- **What the journey stands on.** The evidence under its own needs (their
|
|
68
|
+
`evidenceIds` and `supported-by` rows) and the insights that test them, with
|
|
69
|
+
assertion-type evidence called out.
|
|
70
|
+
- **Users who stand on the same ground.** Every other user whose needs cite the
|
|
71
|
+
same evidence or are tested by the same insights, and which they share.
|
|
72
|
+
- **Design actions and decisions already on that ground.** A decision can be
|
|
73
|
+
taken in a journey built on the same evidence, or it can resolve a design
|
|
74
|
+
action that responds to one of the journey's insights. It is reported either
|
|
75
|
+
way, with its status and which route it came by.
|
|
76
|
+
- **Weak ground.** Assumptions attached to the journey's needs or ground,
|
|
77
|
+
assertion-type or low-confidence evidence, and insights on the ground that are
|
|
78
|
+
not held at high confidence.
|
|
79
|
+
- **Screens already built on that ground** - where the journey is likely to land.
|
|
80
|
+
- **Questions every new kind of user raises:** what they may see, whether they
|
|
81
|
+
write, and whether they look at one record or many. A concern no record names is
|
|
82
|
+
reported as nobody having asked.
|
|
83
|
+
|
|
84
|
+
It walks the shared ground and never the screen. A screen's own needs belong to its
|
|
85
|
+
intended users by construction, so starting from the screens a journey touches
|
|
86
|
+
always reports that nothing is wrong. On NAER, walking out from the address screen
|
|
87
|
+
found one role; walking the evidence the same change rests on found five roles and
|
|
88
|
+
ten needs. Screens are listed but not walked for the same reason: a shared page
|
|
89
|
+
reaches every user and buries the few whose needs actually stand on the ground.
|
|
90
|
+
|
|
91
|
+
Insights count as ground because evidence alone is not enough. On NCRS each
|
|
92
|
+
persona has its own evidence record, so evidence is almost never shared between
|
|
93
|
+
users. Read that way, the safeguarding household scenario reached nobody and
|
|
94
|
+
found no decisions, which is the "nothing is wrong" answer this command exists to
|
|
95
|
+
prevent. Read through the insights, it reaches 13 needs across 6 roles, and all
|
|
96
|
+
five Round 16 decisions on location search through `da-r16-01`.
|
|
97
|
+
|
|
98
|
+
Matching participants to the new persona ignores generic job words such as
|
|
99
|
+
*practitioner*, *clinical*, *administrator* and *lead*. Without that, on NCRS
|
|
100
|
+
"Safeguarding practitioner (clinical)" was matched on *practitioner* alone, and
|
|
101
|
+
three *Clinical - Practitioner* participants from other rounds were counted as
|
|
102
|
+
research on safeguarding.
|
|
103
|
+
|
|
104
|
+
It lists candidates, not verdicts. Whether a decision is a collision or already
|
|
105
|
+
answers the question, and whether a gap needs research, are judgements, and the
|
|
106
|
+
skill is where they get made. It exits 0 whenever the scenario exists, and supports
|
|
107
|
+
`--json` and `--all`.
|
|
108
|
+
|
|
3
109
|
## 2.1.0
|
|
4
110
|
|
|
5
111
|
`hippocampus known <topic>` answers "what do we already know about this?" before
|
package/README.md
CHANGED
|
@@ -139,6 +139,8 @@ npx hippocampus doctor # wiring, integrity and routes - start here
|
|
|
139
139
|
npx hippocampus validate # parse, check integrity, report coverage gaps
|
|
140
140
|
npx hippocampus validate --strict # and fail on warnings
|
|
141
141
|
npx hippocampus known "topic" # what is already known, what was built on it, what nobody asked
|
|
142
|
+
npx hippocampus consequences <id> # run a new journey against the users we already know
|
|
143
|
+
npx hippocampus mcp # serve the knowledge base to agents over MCP
|
|
142
144
|
npx hippocampus research triage # rank a research folder before importing anything
|
|
143
145
|
npx hippocampus research sync # inbox artefacts to reviewable drafts
|
|
144
146
|
npx hippocampus source index # record what was ingested, before the copies go
|
|
@@ -156,6 +158,30 @@ hippocampus: knowledge data is valid
|
|
|
156
158
|
info 108 of 132 needs (82%) sit at priority "medium"
|
|
157
159
|
```
|
|
158
160
|
|
|
161
|
+
## Serving it to agents over MCP
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
npx hippocampus mcp # HTTP on http://127.0.0.1:3100/mcp
|
|
165
|
+
npx hippocampus mcp --stdio # for a client that starts the server itself
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Read-only, localhost only. The tools are `design_brain_brief` (start here: one
|
|
169
|
+
brief for a role, scenario, journey or build spec, with record ids),
|
|
170
|
+
`design_brain_known`, `design_brain_consequences`, `design_brain_overview`,
|
|
171
|
+
`design_brain_read` and `design_brain_ask`. Only `ask` uses a model; it needs
|
|
172
|
+
`GEMINI_API_KEY`, `DESIGN_BRAIN_MODEL` and `npm install @google/genai`, and
|
|
173
|
+
reports that it is off otherwise.
|
|
174
|
+
|
|
175
|
+
To add it to Claude Code:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
claude mcp add --transport http design_brain http://127.0.0.1:3100/mcp
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`DESIGN_BRAIN_MCP_PORT` changes the port. `DESIGN_BRAIN_MCP_LOG=<file>` logs
|
|
182
|
+
each call. `design_brain_read` never serves `.env`, `.git`, `.npmrc` or
|
|
183
|
+
`node_modules`.
|
|
184
|
+
|
|
159
185
|
## Documentation
|
|
160
186
|
|
|
161
187
|
The guides are served by the viewer at `{basePath}/docs`, so they always
|
|
@@ -19,6 +19,7 @@ Maintains the Hippocampus source model.
|
|
|
19
19
|
- `.github/skills/create-journey-from-scenario/SKILL.md`
|
|
20
20
|
- `.github/skills/audit-knowledge-source/SKILL.md`
|
|
21
21
|
- `.github/skills/whats-known-about/SKILL.md`
|
|
22
|
+
- `.github/skills/find-unintended-consequences/SKILL.md`
|
|
22
23
|
- `.github/skills/ingest-user-personas/SKILL.md`
|
|
23
24
|
- `.github/skills/record-design-decision/SKILL.md`
|
|
24
25
|
- `.github/skills/onboard-team-member/SKILL.md`
|
|
@@ -27,6 +27,7 @@ Coordinates larger Hippocampus delivery work.
|
|
|
27
27
|
- `.github/skills/map-research-to-graph/SKILL.md`
|
|
28
28
|
- `.github/skills/audit-knowledge-source/SKILL.md`
|
|
29
29
|
- `.github/skills/whats-known-about/SKILL.md`
|
|
30
|
+
- `.github/skills/find-unintended-consequences/SKILL.md`
|
|
30
31
|
- `.github/skills/triage-research-corpus/SKILL.md`
|
|
31
32
|
- `.github/skills/onboard-team-member/SKILL.md`
|
|
32
33
|
|
package/bin/hippocampus.js
CHANGED
|
@@ -18,6 +18,8 @@ const COMMANDS = {
|
|
|
18
18
|
eject: 'eject.js',
|
|
19
19
|
validate: 'validate-knowledge.js',
|
|
20
20
|
known: 'known.js',
|
|
21
|
+
consequences: 'consequences.js',
|
|
22
|
+
mcp: 'mcp.js',
|
|
21
23
|
migrate: 'migrate-knowledge.js',
|
|
22
24
|
'research sync': 'sync-research-artefacts.js',
|
|
23
25
|
'research triage': 'triage-research-corpus.js',
|
package/lib/brief.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
|
|
4
|
+
// "Tell me everything you know about the paramedic" answered in one read.
|
|
5
|
+
//
|
|
6
|
+
// An agent building a feature needs the user's needs, the scenarios and journey
|
|
7
|
+
// steps, the build spec, the screens, and the decisions, assumptions and
|
|
8
|
+
// insights that surround them - each with its record id, so what it writes can
|
|
9
|
+
// cite the knowledge base rather than paraphrase it. Keyword search alone finds
|
|
10
|
+
// the words and misses the structure: the first agents to use this knowledge
|
|
11
|
+
// base over MCP ran one `known` query and missed contested items, the build
|
|
12
|
+
// spec and every record id.
|
|
13
|
+
//
|
|
14
|
+
// So a brief starts from the user roles the subject names, because a role links
|
|
15
|
+
// most of the graph, takes the scenarios, journeys, needs and screens around
|
|
16
|
+
// it, then follows the relationships one step out for decisions, assumptions,
|
|
17
|
+
// insights and design actions. Assumptions stay labelled as beliefs.
|
|
18
|
+
//
|
|
19
|
+
// Ported from the Design Brain MCP server Ed Hiley wrote for NAER.
|
|
20
|
+
|
|
21
|
+
const MAX_CHARS = 40000
|
|
22
|
+
|
|
23
|
+
function readBuildSpecs (root) {
|
|
24
|
+
const dir = path.join(root, 'build-specs')
|
|
25
|
+
if (!fs.existsSync(dir)) return []
|
|
26
|
+
return fs.readdirSync(dir)
|
|
27
|
+
.filter((f) => f.endsWith('.json') && !f.startsWith('_'))
|
|
28
|
+
.map((f) => {
|
|
29
|
+
try {
|
|
30
|
+
return { file: `build-specs/${f}`, ...JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')) }
|
|
31
|
+
} catch (error) {
|
|
32
|
+
return { file: `build-specs/${f}`, error: error.message }
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function brief (knowledge, subject, { buildSpecs = [], maxChars = MAX_CHARS } = {}) {
|
|
38
|
+
const text = String(subject || '').trim()
|
|
39
|
+
const tokens = text.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2)
|
|
40
|
+
const slug = tokens.join('-')
|
|
41
|
+
const matches = (value) => tokens.some((t) => String(value ?? '').toLowerCase().includes(t))
|
|
42
|
+
const list = (key) => knowledge[key] || []
|
|
43
|
+
|
|
44
|
+
// Start from the user roles the subject names. A role links most of the knowledge base.
|
|
45
|
+
const users = list('users').filter((u) =>
|
|
46
|
+
tokens.includes(u.id) || tokens.some((t) => u.id.split('-').includes(t)) || matches(u.label))
|
|
47
|
+
const userIds = new Set(users.map((u) => u.id))
|
|
48
|
+
|
|
49
|
+
const scenarios = list('scenarios').filter((s) => userIds.has(s.userId) || (slug && s.id.includes(slug)))
|
|
50
|
+
const scenarioIds = new Set(scenarios.map((s) => s.id))
|
|
51
|
+
const journeys = list('journeys').filter((j) => scenarioIds.has(j.scenarioId) || (slug && j.id.includes(slug)))
|
|
52
|
+
const needs = list('needs').filter((n) => userIds.has(n.userId) || scenarios.some((s) => (s.needIds || []).includes(n.id)))
|
|
53
|
+
const needIds = new Set(needs.map((n) => n.id))
|
|
54
|
+
const stepScreens = new Set(journeys.flatMap((j) => (j.steps || []).flatMap((s) => s.screenIds || [])))
|
|
55
|
+
const screens = list('screens').filter((s) => stepScreens.has(s.id) || (s.needIds || []).some((id) => needIds.has(id)))
|
|
56
|
+
const specs = buildSpecs.filter((b) => userIds.has(b.role?.id) || (slug && (b.journeySlug || '').includes(slug)))
|
|
57
|
+
|
|
58
|
+
// Follow the relationships one step out from the core records.
|
|
59
|
+
const core = new Set([...userIds, ...scenarioIds, ...journeys.map((j) => j.id), ...needIds, ...screens.map((s) => s.id)])
|
|
60
|
+
const linked = new Set()
|
|
61
|
+
for (const r of list('relationships')) {
|
|
62
|
+
if (core.has(r.from)) linked.add(r.to)
|
|
63
|
+
if (core.has(r.to)) linked.add(r.from)
|
|
64
|
+
}
|
|
65
|
+
for (const n of needs) for (const id of n.evidenceIds || []) linked.add(id)
|
|
66
|
+
for (const j of journeys) {
|
|
67
|
+
for (const s of j.steps || []) for (const id of [...(s.decisionIds || []), ...(s.evidenceIds || [])]) linked.add(id)
|
|
68
|
+
}
|
|
69
|
+
const pick = (items) => items.filter((i) => linked.has(i.id))
|
|
70
|
+
const decisions = pick(list('decisions'))
|
|
71
|
+
// Assumptions are often not linked in the graph, so also take any that name the role or cite its needs.
|
|
72
|
+
const assumptions = list('assumptions').filter((a) => linked.has(a.id) ||
|
|
73
|
+
(a.needIds || []).some((id) => needIds.has(id)) ||
|
|
74
|
+
users.some((u) => String(a.statement || '').toLowerCase().includes(String(u.label || '').toLowerCase())))
|
|
75
|
+
const insights = pick(list('insights'))
|
|
76
|
+
const actions = pick(list('designActions'))
|
|
77
|
+
const rounds = new Map(list('researchRounds').map((r) => [r.id, r]))
|
|
78
|
+
|
|
79
|
+
if (!users.length && !journeys.length && !scenarios.length && !specs.length) {
|
|
80
|
+
return `No user, scenario, journey or build spec matches "${text}". Use a keyword search (known) for a topic, or the overview to see what exists.`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const out = [`# Brief: ${text}`, 'Every item has its record ID. Cite these IDs. Assumptions are beliefs, not research.']
|
|
84
|
+
const section = (title, items, line) => {
|
|
85
|
+
if (!items.length) return
|
|
86
|
+
out.push(`\n## ${title} (${items.length})`)
|
|
87
|
+
for (const i of items) out.push(line(i))
|
|
88
|
+
}
|
|
89
|
+
const edge = (e) => (typeof e === 'string' ? e : e.label || e.title || JSON.stringify(e))
|
|
90
|
+
section('Users', users, (u) => `- ${u.id}: ${u.label}. ${u.description || ''}`.trim())
|
|
91
|
+
section('Needs', needs, (n) => `- ${n.id} [${n.priority}]: ${n.statement}`)
|
|
92
|
+
section('Scenarios', scenarios, (s) => `- ${s.id} [risk ${s.riskLevel}]: ${s.title}. Trigger: ${s.trigger || ''}` +
|
|
93
|
+
((s.edgeCases || []).length ? `\n Edge cases: ${s.edgeCases.map(edge).join('; ')}` : ''))
|
|
94
|
+
section('Journeys', journeys, (j) => [`- ${j.id}: ${j.title}. ${j.description || ''}`.trim(),
|
|
95
|
+
...(j.steps || []).map((s) => ` - ${s.id}: ${s.label}. ${s.userAction || ''}` +
|
|
96
|
+
((s.frontstage || []).length ? `\n Shows: ${s.frontstage.join('; ')}` : '') +
|
|
97
|
+
((s.exceptionHandling || []).length ? `\n Exceptions: ${s.exceptionHandling.join('; ')}` : '') +
|
|
98
|
+
((s.needIds || []).length ? `\n Needs: ${s.needIds.join(', ')}` : ''))].join('\n'))
|
|
99
|
+
section('Build specs', specs, (b) => [`- ${b.file} (journey ${b.journeySlug}, role ${b.role?.id}: "${b.role?.need || ''}")`,
|
|
100
|
+
...(b.acceptanceCriteria || []).map((a) => ` - Acceptance: ${a}`),
|
|
101
|
+
...(b.a11yRequirements || []).map((a) => ` - Accessibility: ${a}`),
|
|
102
|
+
...(b.routes || []).map((r) => ` - Route: ${r.method} ${r.path}. ${r.notes || ''}`.trim())].join('\n'))
|
|
103
|
+
section('Screens', screens, (s) => `- ${s.id} ${s.route}: ${s.title}. ${s.purpose || ''}`.trim())
|
|
104
|
+
section('Decisions', decisions, (d) => `- ${d.id} [${d.status}]: ${d.title}. ${d.decision || ''}`.trim())
|
|
105
|
+
section('Assumptions (beliefs, not research)', assumptions, (a) => `- ${a.id} [risk ${a.risk}]: ${a.statement}`)
|
|
106
|
+
section('Insights', insights, (i) => {
|
|
107
|
+
const round = rounds.get(i.roundId)
|
|
108
|
+
return `- ${i.id} [${i.confidence}, ${round?.title || i.roundId}, ${round?.date || ''}]: ${i.title}`
|
|
109
|
+
})
|
|
110
|
+
section('Design actions', actions, (a) => `- ${a.id} [${a.status}]: ${a.title}`)
|
|
111
|
+
const result = out.join('\n')
|
|
112
|
+
return result.length > maxChars ? `${result.slice(0, maxChars)}\n\n[Cut at ${maxChars} of ${result.length} characters.]` : result
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { brief, readBuildSpecs, MAX_CHARS }
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
// "If we add this journey, who that we already know could it hurt?" answered
|
|
2
|
+
// from the knowledge base, before the journey is designed.
|
|
3
|
+
//
|
|
4
|
+
// The input is a scenario for a new or changed journey. The output is every
|
|
5
|
+
// existing user whose needs stand on the same ground, the decisions already
|
|
6
|
+
// taken on that ground, the weak parts of it, and the questions every new kind
|
|
7
|
+
// of user raises that nobody may have asked.
|
|
8
|
+
//
|
|
9
|
+
// Two rules make the answer worth having:
|
|
10
|
+
//
|
|
11
|
+
// - Walk the shared ground, never the screen. A screen's own needs belong, by
|
|
12
|
+
// construction, to its intended users, so starting from the screens a journey
|
|
13
|
+
// touches always reports that nothing is wrong. The users a journey can hurt
|
|
14
|
+
// are the ones whose needs rest on the same evidence, the same assumptions and
|
|
15
|
+
// the same decisions.
|
|
16
|
+
// - Report candidates, not verdicts. Whether a decision is a collision, whether
|
|
17
|
+
// a finding is already handled, whether a gap needs research - those are
|
|
18
|
+
// judgements. This lists what a person or an agent has to look at, with the
|
|
19
|
+
// record behind each item, and leaves the call to them.
|
|
20
|
+
|
|
21
|
+
const { whatsKnown, ASSERTION_TYPES } = require('./known')
|
|
22
|
+
|
|
23
|
+
// Questions every new kind of user raises, whatever the service. Checked by
|
|
24
|
+
// coverage: a concern that no record names is a question nobody has asked, and
|
|
25
|
+
// is reported as that, not as a pass.
|
|
26
|
+
const STANDING_CONCERNS = [
|
|
27
|
+
{
|
|
28
|
+
id: 'disclosure',
|
|
29
|
+
question: 'What this user may see, and what they must not',
|
|
30
|
+
terms: ['privacy', 'consent', 'disclos', 'confidential', 'information governance', 'data sharing']
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
id: 'writes',
|
|
34
|
+
question: 'Whether this user writes to the record, and how it is attributed',
|
|
35
|
+
terms: ['write back', 'write-back', 'correction', 'attributed']
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
id: 'bulk-access',
|
|
39
|
+
question: 'Whether this user looks at one record or at many',
|
|
40
|
+
terms: ['bulk', 'postcode-area', 'postcode area', 'area search', 'caseload']
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
// Words too common in role names to tell one role from another. Generic grade
|
|
45
|
+
// and job-family words belong here too: on NCRS, "Safeguarding practitioner
|
|
46
|
+
// (clinical)" was otherwise matched on "practitioner" alone - the one word the
|
|
47
|
+
// other users lacked - and reported three GP participants as research on it.
|
|
48
|
+
const ROLE_NOISE = new Set([
|
|
49
|
+
'and', 'the', 'for', 'officer', 'service', 'services', 'staff', 'worker', 'team', 'home', 'person',
|
|
50
|
+
'practitioner', 'clinical', 'clinician', 'admin', 'administrator', 'user', 'users', 'manager',
|
|
51
|
+
'lead', 'senior', 'specialist', 'coordinator', 'assistant', 'general'
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
function roleWords (label) {
|
|
55
|
+
return String(label || '').toLowerCase().split(/[^a-z]+/).filter((w) => w.length >= 3 && !ROLE_NOISE.has(w))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function indexBy (records) {
|
|
59
|
+
const map = new Map()
|
|
60
|
+
for (const record of records || []) map.set(record.id, record)
|
|
61
|
+
return map
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Journeys reach evidence, screens and decisions through relationship rows and
|
|
65
|
+
// through the id lists on their steps. Collect both, so a journey modelled
|
|
66
|
+
// either way is found.
|
|
67
|
+
function journeyLinks (knowledge) {
|
|
68
|
+
const links = new Map()
|
|
69
|
+
const of = (id) => {
|
|
70
|
+
if (!links.has(id)) links.set(id, { evidence: new Set(), screens: new Set(), decisions: new Set() })
|
|
71
|
+
return links.get(id)
|
|
72
|
+
}
|
|
73
|
+
for (const rel of knowledge.relationships || []) {
|
|
74
|
+
if (rel.type === 'uses-evidence') of(rel.from).evidence.add(rel.to)
|
|
75
|
+
if (rel.type === 'renders-screen') of(rel.from).screens.add(rel.to)
|
|
76
|
+
if (rel.type === 'records-decision') of(rel.from).decisions.add(rel.to)
|
|
77
|
+
}
|
|
78
|
+
for (const journey of knowledge.journeys || []) {
|
|
79
|
+
for (const step of journey.steps || []) {
|
|
80
|
+
for (const id of step.evidenceIds || []) of(journey.id).evidence.add(id)
|
|
81
|
+
for (const id of step.screenIds || []) of(journey.id).screens.add(id)
|
|
82
|
+
for (const id of step.decisionIds || []) of(journey.id).decisions.add(id)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return links
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @param {object} knowledge from store.getKnowledge()
|
|
90
|
+
* @param {string} scenarioId the scenario for the new or changed journey
|
|
91
|
+
* @param {object} [options]
|
|
92
|
+
* @param {Array} [options.concerns] replaces STANDING_CONCERNS
|
|
93
|
+
*/
|
|
94
|
+
function checkConsequences (knowledge, scenarioId, { concerns = STANDING_CONCERNS } = {}) {
|
|
95
|
+
const scenarios = indexBy(knowledge.scenarios)
|
|
96
|
+
const scenario = scenarios.get(scenarioId)
|
|
97
|
+
if (!scenario) {
|
|
98
|
+
const known = [...scenarios.keys()]
|
|
99
|
+
throw new Error(`No scenario with id "${scenarioId}".` + (known.length ? ` Scenarios here: ${known.join(', ')}` : ' This knowledge base has no scenarios.'))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const users = indexBy(knowledge.users)
|
|
103
|
+
const needs = indexBy(knowledge.needs)
|
|
104
|
+
const evidence = indexBy(knowledge.evidence)
|
|
105
|
+
const decisions = indexBy(knowledge.decisions)
|
|
106
|
+
const screens = indexBy(knowledge.screens)
|
|
107
|
+
const rounds = indexBy(knowledge.researchRounds)
|
|
108
|
+
const persona = scenario.userId
|
|
109
|
+
const personaLabel = users.get(persona)?.label || persona
|
|
110
|
+
|
|
111
|
+
// A need's evidence lives in its own evidenceIds and in supported-by rows;
|
|
112
|
+
// the insights that test it live only in tests-need rows. Read all three, so
|
|
113
|
+
// a knowledge base modelled either way has the same ground.
|
|
114
|
+
const insightById = indexBy(knowledge.insights)
|
|
115
|
+
const needEvidence = new Map()
|
|
116
|
+
const needInsights = new Map()
|
|
117
|
+
const addTo = (map, key, value) => {
|
|
118
|
+
if (!map.has(key)) map.set(key, new Set())
|
|
119
|
+
map.get(key).add(value)
|
|
120
|
+
}
|
|
121
|
+
for (const need of knowledge.needs || []) {
|
|
122
|
+
for (const id of need.evidenceIds || []) addTo(needEvidence, need.id, id)
|
|
123
|
+
}
|
|
124
|
+
for (const rel of knowledge.relationships || []) {
|
|
125
|
+
if (rel.type === 'supported-by' && needs.has(rel.from) && evidence.has(rel.to)) addTo(needEvidence, rel.from, rel.to)
|
|
126
|
+
if (rel.type === 'tests-need' && insightById.has(rel.from) && needs.has(rel.to)) addTo(needInsights, rel.to, rel.from)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 1. The journey's own needs, and what they stand on: the evidence under them
|
|
130
|
+
// and the insights that test them. This is the ground. Insights matter as
|
|
131
|
+
// much as evidence: where each persona has its own evidence record, as on
|
|
132
|
+
// NCRS, evidence is almost never shared between users and the insights are
|
|
133
|
+
// the only common ground there is.
|
|
134
|
+
const ownNeeds = (scenario.needIds || []).map((id) => needs.get(id)).filter(Boolean)
|
|
135
|
+
const citedBy = new Map()
|
|
136
|
+
const testedBy = new Map()
|
|
137
|
+
for (const need of ownNeeds) {
|
|
138
|
+
for (const id of needEvidence.get(need.id) || []) {
|
|
139
|
+
if (!citedBy.has(id)) citedBy.set(id, [])
|
|
140
|
+
citedBy.get(id).push(need.id)
|
|
141
|
+
}
|
|
142
|
+
for (const id of needInsights.get(need.id) || []) {
|
|
143
|
+
if (!testedBy.has(id)) testedBy.set(id, [])
|
|
144
|
+
testedBy.get(id).push(need.id)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const ground = [...citedBy.entries()].map(([id, by]) => {
|
|
148
|
+
const record = evidence.get(id) || {}
|
|
149
|
+
return {
|
|
150
|
+
id,
|
|
151
|
+
label: record.title || id,
|
|
152
|
+
sourceType: record.sourceType || null,
|
|
153
|
+
confidence: record.confidence || null,
|
|
154
|
+
assertion: ASSERTION_TYPES.test(record.sourceType || ''),
|
|
155
|
+
citedBy: by
|
|
156
|
+
}
|
|
157
|
+
}).sort((a, b) => Number(b.assertion) - Number(a.assertion) || a.id.localeCompare(b.id))
|
|
158
|
+
const groundIds = new Set(citedBy.keys())
|
|
159
|
+
const groundInsightIds = new Set(testedBy.keys())
|
|
160
|
+
const groundInsights = [...testedBy.entries()].map(([id, by]) => {
|
|
161
|
+
const record = insightById.get(id) || {}
|
|
162
|
+
const round = rounds.get(record.roundId)
|
|
163
|
+
return {
|
|
164
|
+
id,
|
|
165
|
+
label: record.title || id,
|
|
166
|
+
confidence: record.confidence || null,
|
|
167
|
+
round: round ? { id: round.id, title: round.title, date: round.date } : null,
|
|
168
|
+
testsNeeds: by
|
|
169
|
+
}
|
|
170
|
+
}).sort((a, b) => a.id.localeCompare(b.id))
|
|
171
|
+
|
|
172
|
+
// 2. Other users' needs that stand on the same evidence or are tested by the
|
|
173
|
+
// same insights. These are the people the journey can hurt.
|
|
174
|
+
const reachedNeeds = new Map()
|
|
175
|
+
for (const need of knowledge.needs || []) {
|
|
176
|
+
if (need.userId === persona) continue
|
|
177
|
+
const shared = [
|
|
178
|
+
...[...(needEvidence.get(need.id) || [])].filter((id) => groundIds.has(id)),
|
|
179
|
+
...[...(needInsights.get(need.id) || [])].filter((id) => groundInsightIds.has(id))
|
|
180
|
+
].sort()
|
|
181
|
+
if (shared.length) reachedNeeds.set(need.id, { need, via: shared })
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 3. Journeys already built on that ground, and what they carry: the decisions
|
|
185
|
+
// taken there and the screens they render.
|
|
186
|
+
const links = journeyLinks(knowledge)
|
|
187
|
+
const journeysOnGround = []
|
|
188
|
+
for (const [journeyId, link] of links) {
|
|
189
|
+
const shared = [...link.evidence].filter((id) => groundIds.has(id))
|
|
190
|
+
if (shared.length) journeysOnGround.push({ id: journeyId, via: shared, link })
|
|
191
|
+
}
|
|
192
|
+
const decisionVia = new Map()
|
|
193
|
+
const screensOnGround = new Map()
|
|
194
|
+
|
|
195
|
+
// Design actions responding to the ground's insights, and the decisions that
|
|
196
|
+
// resolve them. This is where most decisions live when research drives the
|
|
197
|
+
// design: a decision resolves an action, the action responds to an insight.
|
|
198
|
+
const actionInsights = new Map()
|
|
199
|
+
for (const action of knowledge.designActions || []) {
|
|
200
|
+
for (const id of action.insightIds || []) addTo(actionInsights, action.id, id)
|
|
201
|
+
}
|
|
202
|
+
const resolvedBy = new Map()
|
|
203
|
+
for (const rel of knowledge.relationships || []) {
|
|
204
|
+
if (rel.type === 'responds-to-insight') addTo(actionInsights, rel.from, rel.to)
|
|
205
|
+
if (rel.type === 'resolves-action') addTo(resolvedBy, rel.to, rel.from)
|
|
206
|
+
}
|
|
207
|
+
const actionsById = indexBy(knowledge.designActions)
|
|
208
|
+
const actionsOnGround = []
|
|
209
|
+
for (const [actionId, insightIds] of actionInsights) {
|
|
210
|
+
const via = [...insightIds].filter((id) => groundInsightIds.has(id)).sort()
|
|
211
|
+
if (!via.length || !actionsById.has(actionId)) continue
|
|
212
|
+
const record = actionsById.get(actionId)
|
|
213
|
+
actionsOnGround.push({ id: actionId, label: record.title, status: record.status || null, via })
|
|
214
|
+
for (const decisionId of resolvedBy.get(actionId) || []) {
|
|
215
|
+
if (!decisionVia.has(decisionId)) decisionVia.set(decisionId, new Set())
|
|
216
|
+
decisionVia.get(decisionId).add(actionId)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
actionsOnGround.sort((a, b) => a.id.localeCompare(b.id))
|
|
220
|
+
|
|
221
|
+
for (const { id: journeyId, link } of journeysOnGround) {
|
|
222
|
+
for (const id of link.decisions) {
|
|
223
|
+
if (!decisionVia.has(id)) decisionVia.set(id, new Set())
|
|
224
|
+
decisionVia.get(id).add(journeyId)
|
|
225
|
+
}
|
|
226
|
+
for (const id of link.screens) {
|
|
227
|
+
if (!screensOnGround.has(id)) screensOnGround.set(id, new Set())
|
|
228
|
+
screensOnGround.get(id).add(journeyId)
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Screens are listed, not walked. A screen on this ground is where the new
|
|
233
|
+
// journey is likely to land, which matters to whoever builds it - but walking
|
|
234
|
+
// out from a screen to its needs reaches every user of a shared page and buries
|
|
235
|
+
// the few whose needs actually stand on this ground.
|
|
236
|
+
const screensBuilt = [...screensOnGround.entries()].map(([id, via]) => {
|
|
237
|
+
const record = screens.get(id) || {}
|
|
238
|
+
return { id, label: record.title || id, route: record.route || null, via: [...via].sort() }
|
|
239
|
+
}).sort((a, b) => a.id.localeCompare(b.id))
|
|
240
|
+
|
|
241
|
+
const priorityRank = { high: 0, medium: 1, low: 2 }
|
|
242
|
+
const byUser = new Map()
|
|
243
|
+
for (const { need, via } of reachedNeeds.values()) {
|
|
244
|
+
if (!byUser.has(need.userId)) byUser.set(need.userId, [])
|
|
245
|
+
byUser.get(need.userId).push({ id: need.id, label: need.statement, priority: need.priority, via })
|
|
246
|
+
}
|
|
247
|
+
const reaches = [...byUser.entries()].map(([userId, list]) => ({
|
|
248
|
+
userId,
|
|
249
|
+
label: users.get(userId)?.label || userId,
|
|
250
|
+
needs: list.sort((a, b) => (priorityRank[a.priority] ?? 3) - (priorityRank[b.priority] ?? 3) || a.id.localeCompare(b.id))
|
|
251
|
+
})).sort((a, b) => b.needs.length - a.needs.length || a.userId.localeCompare(b.userId))
|
|
252
|
+
|
|
253
|
+
const statusRank = { accepted: 0, proposed: 1, rejected: 2, superseded: 3 }
|
|
254
|
+
const decisionsOnGround = [...decisionVia.entries()].map(([id, via]) => {
|
|
255
|
+
const record = decisions.get(id) || {}
|
|
256
|
+
return { id, label: record.title || id, status: record.status || null, via: [...via].sort() }
|
|
257
|
+
}).sort((a, b) => (statusRank[a.status] ?? 4) - (statusRank[b.status] ?? 4) || a.id.localeCompare(b.id))
|
|
258
|
+
|
|
259
|
+
// 4. Weak ground: evidence that is an assertion or held at low confidence, and
|
|
260
|
+
// insights drawn from the ground that are not held at high confidence.
|
|
261
|
+
const weakEvidence = ground.filter((g) => g.assertion || g.confidence === 'low')
|
|
262
|
+
const weakInsights = (knowledge.insights || [])
|
|
263
|
+
.filter((insight) => insight.confidence !== 'high' &&
|
|
264
|
+
(groundInsightIds.has(insight.id) || (insight.evidenceIds || []).some((id) => groundIds.has(id))))
|
|
265
|
+
.map((insight) => {
|
|
266
|
+
const round = rounds.get(insight.roundId)
|
|
267
|
+
return {
|
|
268
|
+
id: insight.id,
|
|
269
|
+
label: insight.title,
|
|
270
|
+
confidence: insight.confidence,
|
|
271
|
+
round: round ? { id: round.id, title: round.title, date: round.date } : null
|
|
272
|
+
}
|
|
273
|
+
})
|
|
274
|
+
.sort((a, b) => (priorityRank[b.confidence] ?? 3) - (priorityRank[a.confidence] ?? 3) || a.id.localeCompare(b.id))
|
|
275
|
+
|
|
276
|
+
// Assumptions attached to the journey's own needs or to its ground - by any
|
|
277
|
+
// relationship row, or by a needIds list on the assumption. The skill tells
|
|
278
|
+
// people to record a missing-evidence gap as an assumption, so the check has
|
|
279
|
+
// to find the ones they record.
|
|
280
|
+
const touches = new Set([...ownNeeds.map((n) => n.id), ...groundIds, ...groundInsightIds])
|
|
281
|
+
const assumptionIds = new Set()
|
|
282
|
+
const assumptionsById = indexBy(knowledge.assumptions)
|
|
283
|
+
for (const rel of knowledge.relationships || []) {
|
|
284
|
+
if (assumptionsById.has(rel.from) && touches.has(rel.to)) assumptionIds.add(rel.from)
|
|
285
|
+
if (assumptionsById.has(rel.to) && touches.has(rel.from)) assumptionIds.add(rel.to)
|
|
286
|
+
}
|
|
287
|
+
for (const a of knowledge.assumptions || []) {
|
|
288
|
+
if ((a.needIds || []).some((id) => touches.has(id))) assumptionIds.add(a.id)
|
|
289
|
+
}
|
|
290
|
+
const weakAssumptions = [...assumptionIds].sort().map((id) => {
|
|
291
|
+
const a = assumptionsById.get(id)
|
|
292
|
+
return { id, label: a.statement, risk: a.risk || null }
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
// 5. Whether this kind of user has ever been in a research round. Matched on
|
|
296
|
+
// role names, so it is a heuristic, and is labelled as one.
|
|
297
|
+
// Only words that tell this role apart from the other users count: "safety"
|
|
298
|
+
// in "fire safety officer" must not match an "MRI safety officer".
|
|
299
|
+
const otherWords = new Set((knowledge.users || []).filter((u) => u.id !== persona).flatMap((u) => roleWords(u.label)))
|
|
300
|
+
const ownWords = roleWords(personaLabel)
|
|
301
|
+
const distinctive = ownWords.filter((w) => !otherWords.has(w))
|
|
302
|
+
const words = distinctive.length ? distinctive : ownWords
|
|
303
|
+
const participants = (knowledge.participants || []).filter((p) => {
|
|
304
|
+
const role = roleWords(p.role)
|
|
305
|
+
return words.some((w) => role.includes(w))
|
|
306
|
+
})
|
|
307
|
+
const personaRounds = [...new Set(participants.flatMap((p) => p.roundIds || []))]
|
|
308
|
+
.map((id) => rounds.get(id)).filter(Boolean)
|
|
309
|
+
.map((r) => ({ id: r.id, title: r.title, date: r.date }))
|
|
310
|
+
.sort((a, b) => `${a.date}`.localeCompare(`${b.date}`))
|
|
311
|
+
|
|
312
|
+
// 6. The standing concerns, checked by coverage across the whole knowledge base.
|
|
313
|
+
const concernResults = concerns.map((concern) => {
|
|
314
|
+
const known = whatsKnown(knowledge, concern.terms, { hops: 0 })
|
|
315
|
+
const namedBy = [
|
|
316
|
+
...known.design.map((d) => ({ id: d.id, label: d.label, kind: d.kind, status: d.status })),
|
|
317
|
+
...known.needs.map((n) => ({ id: n.id, label: n.label, kind: 'needs', status: null })),
|
|
318
|
+
...known.assumptions.map((a) => ({ id: a.id, label: a.label, kind: 'assumptions', status: null }))
|
|
319
|
+
]
|
|
320
|
+
return {
|
|
321
|
+
id: concern.id,
|
|
322
|
+
question: concern.question,
|
|
323
|
+
terms: concern.terms,
|
|
324
|
+
findings: known.findings.length,
|
|
325
|
+
roundsWithFindings: known.coverage.roundsWithFindings.length,
|
|
326
|
+
namedBy,
|
|
327
|
+
nobodyAsked: known.findings.length === 0 && namedBy.length === 0
|
|
328
|
+
}
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
return {
|
|
332
|
+
scenario: { id: scenario.id, title: scenario.title, userId: persona, userLabel: personaLabel, riskLevel: scenario.riskLevel || null },
|
|
333
|
+
persona: { id: persona, label: personaLabel, matchedOn: words, participants: participants.map((p) => ({ id: p.id, role: p.role })), rounds: personaRounds },
|
|
334
|
+
ownNeeds: ownNeeds.map((n) => ({ id: n.id, label: n.statement, priority: n.priority })),
|
|
335
|
+
ground,
|
|
336
|
+
groundInsights,
|
|
337
|
+
reaches,
|
|
338
|
+
designActions: actionsOnGround,
|
|
339
|
+
journeys: journeysOnGround.map((j) => ({ id: j.id, via: j.via })).sort((a, b) => a.id.localeCompare(b.id)),
|
|
340
|
+
screens: screensBuilt,
|
|
341
|
+
decisions: decisionsOnGround,
|
|
342
|
+
weakGround: { assumptions: weakAssumptions, evidence: weakEvidence, insights: weakInsights },
|
|
343
|
+
concerns: concernResults,
|
|
344
|
+
researchRounds: (knowledge.researchRounds || []).length
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
module.exports = { checkConsequences, STANDING_CONCERNS }
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
const { spawnSync } = require('child_process')
|
|
4
|
+
const { z } = require('zod')
|
|
5
|
+
const packagePaths = require('./package-paths')
|
|
6
|
+
const { brief, readBuildSpecs, MAX_CHARS } = require('./brief')
|
|
7
|
+
|
|
8
|
+
// An MCP server that gives agents in other tools read-only access to a
|
|
9
|
+
// Hippocampus knowledge base - the "design brain" half of two brains and a join.
|
|
10
|
+
//
|
|
11
|
+
// Ed Hiley wrote the first version inside the NAER prototype, for Hippo Agents
|
|
12
|
+
// to read the design knowledge base while it builds. It lives here instead so
|
|
13
|
+
// every project that installs the package gets it, and so the tools answer from
|
|
14
|
+
// the package's own commands (known, consequences) rather than a copy of them.
|
|
15
|
+
//
|
|
16
|
+
// The tool names keep his `design_brain_` prefix: Hippo Agents' skills already
|
|
17
|
+
// look for `design_brain_*` tools, and a client should not have to change to
|
|
18
|
+
// move from the project's server to the package's.
|
|
19
|
+
//
|
|
20
|
+
// Read-only by construction: there is no tool that writes, and `read` refuses
|
|
21
|
+
// anything outside the project root and anything that looks like a secret.
|
|
22
|
+
|
|
23
|
+
const TOOL_PREFIX = 'design_brain_'
|
|
24
|
+
const SECRET = /(^|[\\/])(\.env[^\\/]*|\.git|\.npmrc|node_modules)([\\/]|$)/i
|
|
25
|
+
|
|
26
|
+
function clip (text) {
|
|
27
|
+
return text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}\n\n[Cut at ${MAX_CHARS} of ${text.length} characters.]` : text
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// known and consequences answer through the package's own CLIs, so an agent
|
|
31
|
+
// gets exactly what a person running the command sees.
|
|
32
|
+
function runCommand (script, args, root) {
|
|
33
|
+
const result = spawnSync(process.execPath, [path.join(packagePaths.scriptsDir, script), ...args, '--root', root],
|
|
34
|
+
{ cwd: root, encoding: 'utf8', timeout: 120000 })
|
|
35
|
+
if (result.status !== 0) return `The command failed.\n${(result.stderr || result.stdout || '').slice(-2000)}`
|
|
36
|
+
return clip(result.stdout)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function tree (dir, depth, prefix = '') {
|
|
40
|
+
const lines = []
|
|
41
|
+
for (const name of fs.readdirSync(dir).sort()) {
|
|
42
|
+
if (SECRET.test(name)) continue
|
|
43
|
+
const full = path.join(dir, name)
|
|
44
|
+
const isDir = fs.statSync(full).isDirectory()
|
|
45
|
+
lines.push(`${prefix}${name}${isDir ? '/' : ''}`)
|
|
46
|
+
if (isDir && depth > 1) lines.push(...tree(full, depth - 1, `${prefix} `))
|
|
47
|
+
}
|
|
48
|
+
return lines
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function createTools (ctx, { env = process.env } = {}) {
|
|
52
|
+
const root = ctx.root
|
|
53
|
+
const knowledge = () => ctx.requireProjects()[0].store.getKnowledge()
|
|
54
|
+
|
|
55
|
+
const tools = {
|
|
56
|
+
brief: (subject) => brief(knowledge(), subject, { buildSpecs: readBuildSpecs(root) }),
|
|
57
|
+
|
|
58
|
+
known: (topic) => runCommand('known.js', [topic], root),
|
|
59
|
+
|
|
60
|
+
consequences: (scenarioId) => runCommand('consequences.js', [scenarioId], root),
|
|
61
|
+
|
|
62
|
+
overview: () => {
|
|
63
|
+
const k = knowledge()
|
|
64
|
+
const lines = [
|
|
65
|
+
`Knowledge base root: ${root}`,
|
|
66
|
+
'All paths are inside this project, not the one you are building. Read them with design_brain_read.',
|
|
67
|
+
'Start with design_brain_brief for a user role, journey or feature. Use design_brain_known for a topic,',
|
|
68
|
+
'design_brain_consequences for a new or changed journey, and design_brain_ask for anything else.',
|
|
69
|
+
'',
|
|
70
|
+
'Knowledge base (record count):'
|
|
71
|
+
]
|
|
72
|
+
for (const [key, value] of Object.entries(k)) {
|
|
73
|
+
if (Array.isArray(value)) lines.push(`- ${key}: ${value.length}`)
|
|
74
|
+
}
|
|
75
|
+
const scenarios = k.scenarios || []
|
|
76
|
+
if (scenarios.length) {
|
|
77
|
+
lines.push('', 'Scenarios (for design_brain_consequences):')
|
|
78
|
+
for (const s of scenarios) lines.push(`- ${s.id} (${s.userId})`)
|
|
79
|
+
}
|
|
80
|
+
if (fs.existsSync(path.join(root, 'build-specs'))) lines.push('', 'Build specs: build-specs/')
|
|
81
|
+
const manifest = path.join(packagePaths.skillsDir, 'skills.json')
|
|
82
|
+
if (fs.existsSync(manifest)) {
|
|
83
|
+
lines.push('', 'Skills that ship with Hippocampus:')
|
|
84
|
+
for (const s of JSON.parse(fs.readFileSync(manifest, 'utf8')).skills || []) lines.push(`- ${s.id}: ${s.purpose || ''}`)
|
|
85
|
+
}
|
|
86
|
+
return lines.join('\n')
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
read: (relPath) => {
|
|
90
|
+
const target = path.resolve(root, String(relPath || '.'))
|
|
91
|
+
const rel = path.relative(root, target)
|
|
92
|
+
if (rel.startsWith('..') || path.isAbsolute(rel) || SECRET.test(rel) || !fs.existsSync(target)) {
|
|
93
|
+
return `Not found in the knowledge base project: ${relPath}`
|
|
94
|
+
}
|
|
95
|
+
// A folder returns a tree three levels deep, so that one call shows what is inside.
|
|
96
|
+
if (fs.statSync(target).isDirectory()) return clip(tree(target, 3).join('\n'))
|
|
97
|
+
return clip(fs.readFileSync(target, 'utf8'))
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
ask: async (question) => ask(question, { tools, env })
|
|
101
|
+
}
|
|
102
|
+
return tools
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A small model loop that answers with the package's own whats-known-about skill.
|
|
106
|
+
// Optional: it needs @google/genai installed, GEMINI_API_KEY and DESIGN_BRAIN_MODEL.
|
|
107
|
+
async function ask (question, { tools, env }) {
|
|
108
|
+
const apiKey = env.GEMINI_API_KEY || env.GOOGLE_API_KEY
|
|
109
|
+
const model = env.DESIGN_BRAIN_MODEL
|
|
110
|
+
if (!apiKey || !model) return 'design_brain_ask is off. Set GEMINI_API_KEY and DESIGN_BRAIN_MODEL, or use design_brain_brief.'
|
|
111
|
+
let genai
|
|
112
|
+
try {
|
|
113
|
+
genai = await import('@google/genai')
|
|
114
|
+
} catch {
|
|
115
|
+
return 'design_brain_ask needs the @google/genai package. Run `npm install @google/genai` in this project, or use design_brain_brief.'
|
|
116
|
+
}
|
|
117
|
+
const { GoogleGenAI, Type } = genai
|
|
118
|
+
const skill = fs.readFileSync(path.join(packagePaths.skillsDir, 'whats-known-about', 'SKILL.md'), 'utf8')
|
|
119
|
+
.split('---').slice(2).join('---')
|
|
120
|
+
const systemInstruction = [
|
|
121
|
+
'You answer questions about this design knowledge base for another agent that is building the service.',
|
|
122
|
+
'Use design_brain_brief first when the question is about a user, journey or feature. Then use known, consequences and read for detail.',
|
|
123
|
+
'Rules: every claim names its record ID. Keep assumptions apart from research. Say plainly what the knowledge base does not cover. Do not guess. Answer in 400 words or fewer.',
|
|
124
|
+
'Follow this skill:',
|
|
125
|
+
skill
|
|
126
|
+
].join('\n')
|
|
127
|
+
const loop = {
|
|
128
|
+
design_brain_brief: { run: (a) => tools.brief(a.subject), params: { subject: Type.STRING } },
|
|
129
|
+
design_brain_known: { run: (a) => tools.known(a.topic), params: { topic: Type.STRING } },
|
|
130
|
+
design_brain_consequences: { run: (a) => tools.consequences(a.scenarioId), params: { scenarioId: Type.STRING } },
|
|
131
|
+
design_brain_read: { run: (a) => tools.read(a.path), params: { path: Type.STRING } }
|
|
132
|
+
}
|
|
133
|
+
const functionDeclarations = Object.entries(loop).map(([name, t]) => ({
|
|
134
|
+
name,
|
|
135
|
+
description: name.replace(TOOL_PREFIX, ''),
|
|
136
|
+
parameters: { type: Type.OBJECT, properties: Object.fromEntries(Object.entries(t.params).map(([k, type]) => [k, { type }])), required: Object.keys(t.params) }
|
|
137
|
+
}))
|
|
138
|
+
const chat = new GoogleGenAI({ apiKey }).chats.create({ model, config: { systemInstruction, tools: [{ functionDeclarations }] } })
|
|
139
|
+
let response = await chat.sendMessage({ message: question })
|
|
140
|
+
// Stop after 12 rounds of tool calls, so that one question cannot run for ever.
|
|
141
|
+
for (let round = 0; round < 12 && response.functionCalls?.length; round++) {
|
|
142
|
+
const parts = response.functionCalls.map((call) => ({
|
|
143
|
+
functionResponse: { name: call.name, response: { result: loop[call.name]?.run(call.args || {}) ?? 'Unknown tool.' } }
|
|
144
|
+
}))
|
|
145
|
+
response = await chat.sendMessage({ message: parts })
|
|
146
|
+
}
|
|
147
|
+
// At the limit, turn tools off so that the model must answer with what it found.
|
|
148
|
+
if (response.functionCalls?.length || !response.text) {
|
|
149
|
+
response = await chat.sendMessage({
|
|
150
|
+
message: 'Stop searching. Answer now with what you found, and say plainly what the knowledge base does not cover.',
|
|
151
|
+
config: { toolConfig: { functionCallingConfig: { mode: 'NONE' } } }
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
return response.text || 'No answer.'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function createServer (ctx, { env = process.env, version = require('../package.json').version } = {}) {
|
|
158
|
+
const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js')
|
|
159
|
+
const tools = createTools(ctx, { env })
|
|
160
|
+
const logFile = env.DESIGN_BRAIN_MCP_LOG
|
|
161
|
+
const reply = (name, arg, text) => {
|
|
162
|
+
if (logFile) fs.appendFileSync(logFile, `\n=== ${name}(${arg}) -> ${text.length} chars\n${text.slice(0, 3000)}\n`)
|
|
163
|
+
return { content: [{ type: 'text', text }] }
|
|
164
|
+
}
|
|
165
|
+
const server = new McpServer({ name: 'design_brain', version })
|
|
166
|
+
server.registerTool(`${TOOL_PREFIX}brief`, {
|
|
167
|
+
description: "Start here for a feature, journey or user role (for example 'paramedic' or 'discharge coordinator'). One brief with the needs, scenarios, journey steps, build spec acceptance criteria, screens, decisions, assumptions and insights, each with its record ID. No model.",
|
|
168
|
+
inputSchema: { subject: z.string() }
|
|
169
|
+
}, async ({ subject }) => reply('brief', subject, tools.brief(subject)))
|
|
170
|
+
server.registerTool(`${TOOL_PREFIX}known`, {
|
|
171
|
+
description: "What the knowledge base already holds on a topic: findings with round, date and confidence, assumptions kept apart, what was built on them, and whether nothing found means nobody asked. Use short topics, for example 'oxygen'.",
|
|
172
|
+
inputSchema: { topic: z.string() }
|
|
173
|
+
}, async ({ topic }) => reply('known', topic, tools.known(topic)))
|
|
174
|
+
server.registerTool(`${TOOL_PREFIX}consequences`, {
|
|
175
|
+
description: 'Run a new or changed journey (a scenario id) against the users the knowledge base already knows: who stands on the same ground, the decisions already taken there, weak ground, and questions nobody has asked. Candidates, not verdicts.',
|
|
176
|
+
inputSchema: { scenarioId: z.string() }
|
|
177
|
+
}, async ({ scenarioId }) => reply('consequences', scenarioId, tools.consequences(scenarioId)))
|
|
178
|
+
server.registerTool(`${TOOL_PREFIX}overview`, {
|
|
179
|
+
description: 'A map of the knowledge base: record counts, scenario ids, build specs and the skills that ship with Hippocampus.',
|
|
180
|
+
inputSchema: {}
|
|
181
|
+
}, async () => reply('overview', '', tools.overview()))
|
|
182
|
+
server.registerTool(`${TOOL_PREFIX}read`, {
|
|
183
|
+
description: "Read a file, or see a folder as a tree, in the knowledge base project. Use a path relative to its root, for example 'build-specs'. Secrets such as .env are never returned.",
|
|
184
|
+
inputSchema: { path: z.string() }
|
|
185
|
+
}, async ({ path: p }) => reply('read', p, tools.read(p)))
|
|
186
|
+
server.registerTool(`${TOOL_PREFIX}ask`, {
|
|
187
|
+
description: 'Ask a question in plain words. A model searches the knowledge base with the whats-known-about skill and answers with record IDs. Slower than brief (up to a minute). Needs GEMINI_API_KEY and DESIGN_BRAIN_MODEL.',
|
|
188
|
+
inputSchema: { question: z.string() }
|
|
189
|
+
}, async ({ question }) => reply('ask', question, await tools.ask(question)))
|
|
190
|
+
return server
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { createServer, createTools, TOOL_PREFIX }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hippo-digital/hippocampus",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.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",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"prepublishOnly": "node ../../scripts/check-release.js"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
+
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
35
36
|
"adm-zip": "^0.5.18",
|
|
36
37
|
"fast-xml-parser": "^5.9.3",
|
|
37
38
|
"marked": "^18.0.13",
|
|
@@ -42,9 +43,15 @@
|
|
|
42
43
|
"sass": "^1.80.0"
|
|
43
44
|
},
|
|
44
45
|
"peerDependencies": {
|
|
46
|
+
"@google/genai": "^2.24.0",
|
|
45
47
|
"nhsuk-frontend": ">=10.5.1",
|
|
46
48
|
"nhsuk-prototype-kit": ">=8.3.0"
|
|
47
49
|
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"@google/genai": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
48
55
|
"engines": {
|
|
49
56
|
"node": ">=22.16.0"
|
|
50
57
|
},
|
|
@@ -65,7 +72,8 @@
|
|
|
65
72
|
"user-research",
|
|
66
73
|
"knowledge-base",
|
|
67
74
|
"service-design",
|
|
68
|
-
"accessibility"
|
|
75
|
+
"accessibility",
|
|
76
|
+
"mcp"
|
|
69
77
|
],
|
|
70
78
|
"author": "Hippo Digital",
|
|
71
79
|
"publishConfig": {
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const { createContextOrExit } = require('../lib/context')
|
|
3
|
+
const { checkConsequences } = require('../lib/consequences')
|
|
4
|
+
|
|
5
|
+
// hippocampus consequences <scenario-id> [--json] [--all]
|
|
6
|
+
//
|
|
7
|
+
// Run a new or changed journey against the users the knowledge base already
|
|
8
|
+
// knows: who stands on the same ground, which decisions were already taken
|
|
9
|
+
// there, which parts of the ground are weak, and which questions every new kind
|
|
10
|
+
// of user raises that nobody may have asked. Lists candidates, not verdicts -
|
|
11
|
+
// see the find-unintended-consequences skill for the judgement. Always exits 0
|
|
12
|
+
// when the knowledge base loads and the scenario exists.
|
|
13
|
+
|
|
14
|
+
const argv = process.argv.slice(2)
|
|
15
|
+
const ctx = createContextOrExit({ argv })
|
|
16
|
+
|
|
17
|
+
const flags = { json: false, all: false }
|
|
18
|
+
const args = []
|
|
19
|
+
for (let i = 0; i < argv.length; i++) {
|
|
20
|
+
const arg = argv[i]
|
|
21
|
+
if (arg === '--root') { i++; continue }
|
|
22
|
+
if (arg.startsWith('--root=')) continue
|
|
23
|
+
if (arg === '--json') flags.json = true
|
|
24
|
+
else if (arg === '--all') flags.all = true
|
|
25
|
+
else if (arg.startsWith('--')) { console.error(`Unknown option: ${arg}`); process.exit(1) }
|
|
26
|
+
else args.push(arg)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const project = ctx.requireProjects()[0]
|
|
30
|
+
const knowledge = project.store.getKnowledge()
|
|
31
|
+
|
|
32
|
+
if (args.length !== 1) {
|
|
33
|
+
console.error('Usage: hippocampus consequences <scenario-id> [--json] [--all]')
|
|
34
|
+
const scenarios = knowledge.scenarios || []
|
|
35
|
+
if (scenarios.length) {
|
|
36
|
+
console.error('\nScenarios in this knowledge base:')
|
|
37
|
+
for (const s of scenarios) console.error(` ${s.id} (${s.userId})`)
|
|
38
|
+
}
|
|
39
|
+
process.exit(1)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let result
|
|
43
|
+
try {
|
|
44
|
+
result = checkConsequences(knowledge, args[0])
|
|
45
|
+
} catch (error) {
|
|
46
|
+
console.error(error.message)
|
|
47
|
+
process.exit(1)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (flags.json) {
|
|
51
|
+
console.log(JSON.stringify(result, null, 2))
|
|
52
|
+
process.exit(0)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const LIMIT = flags.all ? Infinity : 25
|
|
56
|
+
const clip = (text, n = 108) => (text && text.length > n ? `${text.slice(0, n - 1)}…` : text || '')
|
|
57
|
+
const roundLabel = (round) => (round ? `${round.title}, ${round.date}` : 'no research round')
|
|
58
|
+
let clipped = false
|
|
59
|
+
|
|
60
|
+
function section (title, items, render, note) {
|
|
61
|
+
if (!items.length) return
|
|
62
|
+
console.log(`\n${title} (${items.length})${note ? ` - ${note}` : ''}`)
|
|
63
|
+
for (const item of items.slice(0, LIMIT)) console.log(render(item))
|
|
64
|
+
if (items.length > LIMIT) {
|
|
65
|
+
clipped = true
|
|
66
|
+
console.log(` ... and ${items.length - LIMIT} more`)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const { scenario, persona } = result
|
|
71
|
+
console.log('Checking a journey against the users we already know')
|
|
72
|
+
console.log(` ${scenario.title}`)
|
|
73
|
+
console.log(` ${scenario.id} · ${scenario.userLabel} (${scenario.userId})`)
|
|
74
|
+
console.log(` (${ctx.root}, ${result.researchRounds} research rounds)`)
|
|
75
|
+
|
|
76
|
+
console.log('\nThis user in the research')
|
|
77
|
+
if (persona.participants.length) {
|
|
78
|
+
console.log(` ${persona.participants.length} participant(s) whose role matches "${persona.matchedOn.join('", "')}", in ${persona.rounds.length} round(s): ` +
|
|
79
|
+
persona.rounds.map((r) => `${r.title} (${r.date})`).join('; '))
|
|
80
|
+
} else {
|
|
81
|
+
console.log(` No participant's role matches "${persona.matchedOn.join('", "')}". No round has included this kind of user,`)
|
|
82
|
+
console.log(' so every need below rests on evidence gathered from other roles. Matched on role names.')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const standsOn = [
|
|
86
|
+
...result.ground.map((g) => ({ ...g, kind: 'evidence' })),
|
|
87
|
+
...result.groundInsights.map((i) => ({ ...i, kind: 'insight' }))
|
|
88
|
+
]
|
|
89
|
+
section('What this journey stands on', standsOn, (g) => g.kind === 'insight'
|
|
90
|
+
? ` insight ${g.id} [${g.confidence}, ${roundLabel(g.round)}]\n tests ${g.testsNeeds.join(', ')}`
|
|
91
|
+
: g.assertion
|
|
92
|
+
? ` evidence ${g.id} [${g.sourceType} - an assertion, not a finding]\n cited by ${g.citedBy.join(', ')}`
|
|
93
|
+
: ` evidence ${g.id} [${g.confidence}, ${g.sourceType}]\n cited by ${g.citedBy.join(', ')}`,
|
|
94
|
+
'the evidence under this journey\'s own needs, and the insights that test them')
|
|
95
|
+
|
|
96
|
+
const needCount = result.reaches.reduce((n, u) => n + u.needs.length, 0)
|
|
97
|
+
if (result.reaches.length) {
|
|
98
|
+
console.log(`\nUsers we already know who stand on the same ground (${result.reaches.length} roles, ${needCount} needs)`)
|
|
99
|
+
for (const user of result.reaches) {
|
|
100
|
+
console.log(` ${user.label} (${user.userId})`)
|
|
101
|
+
for (const need of user.needs.slice(0, LIMIT)) {
|
|
102
|
+
console.log(` ${need.id} [${need.priority}]\n ${clip(need.label, 100)}\n via ${need.via.join(', ')}`)
|
|
103
|
+
}
|
|
104
|
+
if (user.needs.length > LIMIT) { clipped = true; console.log(` ... and ${user.needs.length - LIMIT} more`) }
|
|
105
|
+
}
|
|
106
|
+
} else {
|
|
107
|
+
console.log('\nNo other user\'s needs stand on this ground.')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
section('Design actions already responding to this ground', result.designActions,
|
|
111
|
+
(a) => ` [${(a.status || 'no status').padEnd(11)}] ${a.id}\n ${clip(a.label, 100)}\n via ${a.via.join(', ')}`)
|
|
112
|
+
|
|
113
|
+
section('Decisions already taken on this ground', result.decisions,
|
|
114
|
+
(d) => ` [${(d.status || 'no status').padEnd(8)}] ${d.id}\n ${clip(d.label, 100)}\n via ${d.via.join(', ')}`,
|
|
115
|
+
'check the journey against each one')
|
|
116
|
+
|
|
117
|
+
section('Weak ground', [
|
|
118
|
+
...result.weakGround.assumptions.map((a) => ({ ...a, kind: 'assumption' })),
|
|
119
|
+
...result.weakGround.evidence.map((e) => ({ ...e, kind: 'evidence' })),
|
|
120
|
+
...result.weakGround.insights.map((i) => ({ ...i, kind: 'insight' }))
|
|
121
|
+
],
|
|
122
|
+
(w) => w.kind === 'assumption'
|
|
123
|
+
? ` assumption ${w.id} [${w.risk} risk]\n ${clip(w.label)}`
|
|
124
|
+
: w.kind === 'evidence'
|
|
125
|
+
? ` evidence ${w.id} [${w.confidence}${w.assertion ? `, ${w.sourceType}` : ''}]\n ${clip(w.label)}`
|
|
126
|
+
: ` insight ${w.id} [${w.confidence}, ${roundLabel(w.round)}]\n ${clip(w.label)}`,
|
|
127
|
+
'assumptions, and findings not held at high confidence')
|
|
128
|
+
|
|
129
|
+
section('Screens already built on this ground', result.screens,
|
|
130
|
+
(s) => ` ${s.id}${s.route ? ` ${s.route}` : ''}\n ${clip(s.label)}`,
|
|
131
|
+
'where this journey is likely to land')
|
|
132
|
+
|
|
133
|
+
console.log('\nQuestions every new kind of user raises')
|
|
134
|
+
for (const c of result.concerns) {
|
|
135
|
+
console.log(` ${c.id.padEnd(12)} ${c.question}`)
|
|
136
|
+
if (c.nobodyAsked) {
|
|
137
|
+
console.log(` Nobody has asked. No record in ${result.researchRounds} rounds names it. That is the finding.`)
|
|
138
|
+
} else {
|
|
139
|
+
if (c.findings) console.log(` ${c.findings} finding(s), in ${c.roundsWithFindings} round(s)`)
|
|
140
|
+
for (const n of c.namedBy.slice(0, 6)) console.log(` named by ${n.id}${n.status ? ` [${n.status}]` : ''}`)
|
|
141
|
+
if (c.namedBy.length > 6) console.log(` ... and ${c.namedBy.length - 6} more`)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
console.log('\nThese are candidates, not verdicts. Whether each decision is a collision, whether a finding is')
|
|
146
|
+
console.log('already handled, and which gaps need research are judgements - see the find-unintended-consequences skill.')
|
|
147
|
+
if (clipped) console.log('\nSome lists were cut at 25. Run with --all for everything, or --json for the full result.')
|
package/scripts/mcp.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const http = require('http')
|
|
3
|
+
const { createContextOrExit } = require('../lib/context')
|
|
4
|
+
|
|
5
|
+
// hippocampus mcp [--stdio] [--port N] [--root <dir>]
|
|
6
|
+
//
|
|
7
|
+
// Serve this knowledge base to agents over MCP, read-only. By default it runs
|
|
8
|
+
// as its own HTTP service on http://127.0.0.1:3100/mcp, so several agents can
|
|
9
|
+
// share it; --stdio is for a client that starts the server itself. It binds to
|
|
10
|
+
// localhost only. See lib/mcp-server.js for the tools.
|
|
11
|
+
|
|
12
|
+
const USAGE = 'Usage: hippocampus mcp [--stdio] [--port N] [--root <dir>]'
|
|
13
|
+
const argv = process.argv.slice(2)
|
|
14
|
+
|
|
15
|
+
let stdio = false
|
|
16
|
+
let help = false
|
|
17
|
+
let port = Number(process.env.DESIGN_BRAIN_MCP_PORT || 3100)
|
|
18
|
+
for (let i = 0; i < argv.length; i++) {
|
|
19
|
+
const arg = argv[i]
|
|
20
|
+
if (arg === '--root') { i++; continue }
|
|
21
|
+
if (arg.startsWith('--root=')) continue
|
|
22
|
+
if (arg === '--stdio') stdio = true
|
|
23
|
+
else if (arg === '--port') port = Number(argv[++i])
|
|
24
|
+
else if (arg === '--help' || arg === '-h') help = true
|
|
25
|
+
else { console.error(`Unknown option: ${arg}\n${USAGE}`); process.exit(1) }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Load the SDK before anything else, --help included, so a broken install
|
|
29
|
+
// says so rather than printing usage for a command that cannot run.
|
|
30
|
+
let createServer
|
|
31
|
+
try {
|
|
32
|
+
({ createServer } = require('../lib/mcp-server'))
|
|
33
|
+
require.resolve('@modelcontextprotocol/sdk/server/mcp.js')
|
|
34
|
+
} catch (error) {
|
|
35
|
+
console.error(`The MCP server could not load: ${error.message.split('\n')[0]}`)
|
|
36
|
+
process.exit(1)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (help) {
|
|
40
|
+
console.log(`${USAGE}
|
|
41
|
+
|
|
42
|
+
Serves this knowledge base to agents over MCP, read-only, as design_brain_* tools.
|
|
43
|
+
(default) HTTP on http://127.0.0.1:<port>/mcp (DESIGN_BRAIN_MCP_PORT, default 3100)
|
|
44
|
+
--stdio for a client that starts the server itself
|
|
45
|
+
--port N another port
|
|
46
|
+
|
|
47
|
+
design_brain_ask needs GEMINI_API_KEY and DESIGN_BRAIN_MODEL, and @google/genai installed.
|
|
48
|
+
DESIGN_BRAIN_MCP_LOG=<file> appends each tool call and its answer to that file.`)
|
|
49
|
+
process.exit(0)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ctx = createContextOrExit({ argv })
|
|
53
|
+
try {
|
|
54
|
+
ctx.requireProjects()
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error(error.message)
|
|
57
|
+
process.exit(1)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function main () {
|
|
61
|
+
if (stdio) {
|
|
62
|
+
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js')
|
|
63
|
+
await createServer(ctx).connect(new StdioServerTransport())
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
if (!Number.isInteger(port) || port <= 0) { console.error('--port needs a port number.'); process.exit(1) }
|
|
67
|
+
const { StreamableHTTPServerTransport } = require('@modelcontextprotocol/sdk/server/streamableHttp.js')
|
|
68
|
+
http.createServer(async (req, res) => {
|
|
69
|
+
if (req.url !== '/mcp') { res.writeHead(404).end(); return }
|
|
70
|
+
// Stateless: one server and transport for each request.
|
|
71
|
+
const server = createServer(ctx)
|
|
72
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined })
|
|
73
|
+
res.on('close', () => { transport.close(); server.close() })
|
|
74
|
+
let body = ''
|
|
75
|
+
for await (const chunk of req) body += chunk
|
|
76
|
+
try {
|
|
77
|
+
await server.connect(transport)
|
|
78
|
+
await transport.handleRequest(req, res, body ? JSON.parse(body) : undefined)
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (!res.headersSent) res.writeHead(400, { 'content-type': 'application/json' })
|
|
81
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: error.message }, id: null }))
|
|
82
|
+
}
|
|
83
|
+
}).listen(port, '127.0.0.1', () => console.error(`Hippocampus MCP server for ${ctx.root}\n http://127.0.0.1:${port}/mcp`))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
main().catch((error) => { console.error(error.message); process.exit(1) })
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: find-unintended-consequences
|
|
3
|
+
description: "Runs a new or changed journey against the users the knowledge base already knows and reports where it could cause them problems, with the record behind each finding. Use when a new persona arrives, before designing a new journey, or before changing one that other roles rely on."
|
|
4
|
+
id: find-unintended-consequences
|
|
5
|
+
title: Find unintended consequences of a journey
|
|
6
|
+
purpose: Before a new or changed journey is designed, find which users we already know it could hurt, which decisions it runs into, and which questions nobody has asked - so the consequences are found in the knowledge base instead of in production.
|
|
7
|
+
owners:
|
|
8
|
+
- knowledge-builder
|
|
9
|
+
- workflow-orchestrator
|
|
10
|
+
composes:
|
|
11
|
+
- whats-known-about
|
|
12
|
+
- record-design-decision
|
|
13
|
+
reads:
|
|
14
|
+
- hippocampus/source/scenarios.json
|
|
15
|
+
- hippocampus/source/users.json
|
|
16
|
+
- hippocampus/source/needs.json
|
|
17
|
+
- hippocampus/source/evidence.json
|
|
18
|
+
- hippocampus/source/insights.json
|
|
19
|
+
- hippocampus/source/decisions.json
|
|
20
|
+
- hippocampus/source/design-actions.json
|
|
21
|
+
- hippocampus/source/assumptions.json
|
|
22
|
+
- hippocampus/source/participants.json
|
|
23
|
+
- hippocampus/source/relationships.json
|
|
24
|
+
edits:
|
|
25
|
+
- artefacts/consequence-reviews/
|
|
26
|
+
runs:
|
|
27
|
+
- npx hippocampus consequences <scenario-id>
|
|
28
|
+
- npx hippocampus known "<topic>"
|
|
29
|
+
- npx hippocampus validate
|
|
30
|
+
outputs:
|
|
31
|
+
- A review sorting every candidate into collides with a decision, rests on weak ground, already handled, or nobody asked
|
|
32
|
+
- For each finding, the existing user and need it affects and the record behind it
|
|
33
|
+
- A plain statement of whether this kind of user has ever been in a research round
|
|
34
|
+
- Proposed fixes, naming the existing decision each one reuses or saying that a new decision is needed
|
|
35
|
+
- A dated review under `artefacts/consequence-reviews/`
|
|
36
|
+
guardrails:
|
|
37
|
+
- The command lists candidates, not verdicts. Classify every one; never paste its output as the answer.
|
|
38
|
+
- Walk the shared ground, never the screen. Do not add users who are reached only because they use a screen this journey might land on - a shared page reaches everyone and hides the few whose needs actually stand on this ground.
|
|
39
|
+
- Report what is already handled. A review that flags everything gets ignored, and the findings that matter go with it.
|
|
40
|
+
- Never invent evidence for a new persona. If no round has included this kind of user, say so first, and record the gap as an assumption - never as a finding.
|
|
41
|
+
- A decision's status is part of the finding. `proposed` is not settled; `rejected` means the journey may be asking for something the team already refused. Surface it; do not overturn it quietly.
|
|
42
|
+
- Do not answer a "nobody asked" by guessing. It is a research question, or a decision somebody has to own.
|
|
43
|
+
- Every finding names the existing user, their need and the record id behind it.
|
|
44
|
+
acceptance:
|
|
45
|
+
- Every candidate is classified into one of the four kinds, naming the existing user, the need and the record id behind it.
|
|
46
|
+
- The review says whether this kind of user has ever been in a research round.
|
|
47
|
+
- Every standing concern is reported, including any that nobody has asked.
|
|
48
|
+
- Each proposed fix names the existing decision it reuses, or says a new decision is needed.
|
|
49
|
+
- Nothing is asserted that cannot be pointed at in `hippocampus/source/`.
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
# Find unintended consequences of a journey
|
|
53
|
+
|
|
54
|
+
## Use when
|
|
55
|
+
|
|
56
|
+
A new kind of user is arriving and their journeys are about to be designed.
|
|
57
|
+
Also before changing a journey other roles rely on, or whenever someone asks
|
|
58
|
+
"what could this break for the people we already serve?"
|
|
59
|
+
|
|
60
|
+
## Workflow
|
|
61
|
+
|
|
62
|
+
1. **Get the journey into the knowledge base as a scenario.** A new persona
|
|
63
|
+
goes in through `add-user-needs` and `add-scenario`, or through the ingestion
|
|
64
|
+
skills if there is real research. Cite the evidence the needs genuinely rest
|
|
65
|
+
on. Where there is none, add an assumption rather than borrowing evidence and
|
|
66
|
+
calling it support. The check reads a scenario id.
|
|
67
|
+
|
|
68
|
+
2. **Run the check.**
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
npx hippocampus consequences scenario-the-new-journey
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Run it with no argument to list the scenario ids.
|
|
75
|
+
|
|
76
|
+
3. **Read `This user in the research` first.** If no round has included this
|
|
77
|
+
kind of user, every need rests on evidence gathered from other roles. Put
|
|
78
|
+
that at the top of the review - it qualifies everything after it.
|
|
79
|
+
|
|
80
|
+
4. **Classify every decision on the ground.** Decisions arrive two ways: taken
|
|
81
|
+
in a journey built on the same evidence, or resolving a design action that
|
|
82
|
+
responds to one of the journey's insights. Each one says which. Read the
|
|
83
|
+
decision text, not only its title, and treat a design action with no decision
|
|
84
|
+
yet as work in progress on the same ground.
|
|
85
|
+
- **Collides** - the journey needs something the decision deferred or refused.
|
|
86
|
+
- **Already handled** - the decision answers a question the journey raises.
|
|
87
|
+
- Otherwise it is on the ground but not in the way; say so in one line.
|
|
88
|
+
|
|
89
|
+
5. **Go through the users it reaches, high-priority needs first.** For each,
|
|
90
|
+
ask whether the new journey changes what they see, what they can trust, or
|
|
91
|
+
what gets written to the record they rely on. Name the need and the evidence.
|
|
92
|
+
|
|
93
|
+
6. **Name the weak ground the journey adds weight to.** An assumption that
|
|
94
|
+
carried four needs and now carries eight is more dangerous than it was, even
|
|
95
|
+
though nothing about it changed.
|
|
96
|
+
|
|
97
|
+
7. **Report the standing concerns.** `Nobody has asked` is a finding, not a
|
|
98
|
+
pass. Use `npx hippocampus known "<topic>"` for anything the journey raises
|
|
99
|
+
that the standing concerns do not cover.
|
|
100
|
+
|
|
101
|
+
8. **Propose fixes.** Prefer an existing decision applied to the new role over a
|
|
102
|
+
new one. A genuinely new decision goes through `record-design-decision`. An
|
|
103
|
+
open question is raised as `[DECISION NEEDED]` with the person who has to
|
|
104
|
+
answer it.
|
|
105
|
+
|
|
106
|
+
9. **Write the review** to `artefacts/consequence-reviews/` with today's date
|
|
107
|
+
and the scenario id, in four sections: collides with a decision, rests on
|
|
108
|
+
weak ground, already handled, nobody asked.
|
|
109
|
+
|
|
110
|
+
## Guardrails
|
|
111
|
+
|
|
112
|
+
- Candidates are not verdicts. Every one gets classified.
|
|
113
|
+
- Users reached only through a shared screen are not reached.
|
|
114
|
+
- Already-handled findings are reported, not dropped.
|
|
115
|
+
- No invented evidence for a new persona; the gap is an assumption.
|
|
116
|
+
- A rejected decision the journey needs is surfaced, never quietly reversed.
|
|
117
|
+
- A "nobody asked" is research or a decision to own, never a guess.
|
|
118
|
+
|
|
119
|
+
## Finish
|
|
120
|
+
|
|
121
|
+
End with the fixes that reuse existing decisions, then the open questions and
|
|
122
|
+
who has to answer each one. The review is what lets the build start from the
|
|
123
|
+
consequences instead of discovering them - so it has to be readable by someone
|
|
124
|
+
who never ran the command.
|
package/skills/skills.json
CHANGED
|
@@ -120,6 +120,39 @@
|
|
|
120
120
|
"Nothing is asserted that cannot be pointed at in `hippocampus/source/`."
|
|
121
121
|
]
|
|
122
122
|
},
|
|
123
|
+
{
|
|
124
|
+
"id": "find-unintended-consequences",
|
|
125
|
+
"title": "Find unintended consequences of a journey",
|
|
126
|
+
"purpose": "Before a new or changed journey is designed, find which users we already know it could hurt, which decisions it runs into, and which questions nobody has asked - so the consequences are found in the knowledge base instead of in production.",
|
|
127
|
+
"file": "find-unintended-consequences/SKILL.md",
|
|
128
|
+
"owners": [
|
|
129
|
+
"knowledge-builder",
|
|
130
|
+
"workflow-orchestrator"
|
|
131
|
+
],
|
|
132
|
+
"composes": [
|
|
133
|
+
"whats-known-about",
|
|
134
|
+
"record-design-decision"
|
|
135
|
+
],
|
|
136
|
+
"runs": [
|
|
137
|
+
"npx hippocampus consequences <scenario-id>",
|
|
138
|
+
"npx hippocampus known \"<topic>\"",
|
|
139
|
+
"npx hippocampus validate"
|
|
140
|
+
],
|
|
141
|
+
"outputs": [
|
|
142
|
+
"A review sorting every candidate into collides with a decision, rests on weak ground, already handled, or nobody asked",
|
|
143
|
+
"For each finding, the existing user and need it affects and the record behind it",
|
|
144
|
+
"A plain statement of whether this kind of user has ever been in a research round",
|
|
145
|
+
"Proposed fixes, naming the existing decision each one reuses or saying that a new decision is needed",
|
|
146
|
+
"A dated review under `artefacts/consequence-reviews/`"
|
|
147
|
+
],
|
|
148
|
+
"acceptance": [
|
|
149
|
+
"Every candidate is classified into one of the four kinds, naming the existing user, the need and the record id behind it.",
|
|
150
|
+
"The review says whether this kind of user has ever been in a research round.",
|
|
151
|
+
"Every standing concern is reported, including any that nobody has asked.",
|
|
152
|
+
"Each proposed fix names the existing decision it reuses, or says a new decision is needed.",
|
|
153
|
+
"Nothing is asserted that cannot be pointed at in `hippocampus/source/`."
|
|
154
|
+
]
|
|
155
|
+
},
|
|
123
156
|
{
|
|
124
157
|
"id": "capture-route-review-pack",
|
|
125
158
|
"title": "Capture route review pack",
|