@hippo-digital/hippocampus 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -32,12 +32,13 @@ function main () {
32
32
  return
33
33
  }
34
34
 
35
- const reused = reconcileSharedRecords(current, draft)
35
+ const { reused, notes } = reconcileSharedRecords(current, draft)
36
36
  const proposed = mergeCollections(current, draft)
37
37
  validateNoDuplicateIds(current, draft)
38
38
  validateDraftReferences(proposed)
39
39
 
40
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)
41
42
 
42
43
  const counts = Object.keys(collections).map((key) => `${key}: +${(draft[key] || []).length}`)
43
44
  console.log(`Promotion checked: ${counts.join(', ')}`)
@@ -125,21 +126,37 @@ function markPromoted (draftPath) {
125
126
 
126
127
  /**
127
128
  * A round is fieldwork, not a file, so several artefacts promote into the same
128
- * 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
129
130
  * participant already seen in a sibling artefact, is expected rather than a
130
131
  * collision - the duplicate check should only fire on genuinely conflicting data.
131
132
  *
132
- * 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.
133
142
  */
134
143
  function reconcileSharedRecords (current, draft) {
135
144
  const reused = []
145
+ const notes = []
136
146
 
137
147
  const existingRounds = new Map(current.researchRounds.map((round) => [round.id, round]))
138
148
  draft.researchRounds = (draft.researchRounds || []).filter((round) => {
139
149
  const existing = existingRounds.get(round.id)
140
150
  if (!existing) return true
141
- if (existing.title !== round.title || existing.date !== round.date) {
142
- 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.')
143
160
  }
144
161
  reused.push(`round ${round.id}`)
145
162
  return false
@@ -172,7 +189,7 @@ function reconcileSharedRecords (current, draft) {
172
189
  })
173
190
  void draftIds
174
191
 
175
- return reused
192
+ return { reused, notes }
176
193
  }
177
194
 
178
195
  function validateDraft (draft) {
@@ -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