opencastle 1.7.3 → 1.8.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.
@@ -1,11 +1,10 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { execFileSync } from 'node:child_process'
3
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
4
3
  import { homedir } from 'node:os'
5
4
  import { basename, dirname, join, relative, resolve } from 'node:path'
6
- import { parse as parseYaml } from 'yaml'
7
5
  import { checkSkill } from './agent-plugin.js'
8
6
  import { LESSONS_DIR, newLessonId, readLessons, renderLesson, syncLessons, today, type Lesson } from './lessons.js'
7
+ import { readMemoryDir, readRepositoryMemory, type MemorySource } from './memory-sources.js'
9
8
  import { scanForSecrets } from './secret-scan.js'
10
9
  import { getOrchestratorRoot } from './copy.js'
11
10
  import { c } from './prompt.js'
@@ -16,8 +15,8 @@ import type { CliContext } from './types.js'
16
15
  *
17
16
  * Knowledge starts personal. A developer writes a skill for their own
18
17
  * assistant, or the assistant remembers a correction it was given — Claude
19
- * Code's auto memory keeps those on one machine, in one person's home
20
- * directory, and no teammate's agent ever sees them. Productboard's Spark
18
+ * Code, VS Code and Codex keep those on one machine, in one person's home
19
+ * directory, and no teammate's agent ever sees them (memory-sources.ts). Productboard's Spark
21
20
  * draws the same line between personal and workspace skills, and makes the
22
21
  * step between them an explicit promotion after the author has tried it.
23
22
  *
@@ -42,11 +41,15 @@ const HELP = `
42
41
  spec and for credentials, then copied to
43
42
  .opencastle/skills/<name>/ — or with --to, into a
44
43
  baseline or Agent Plugin every repository extends.
45
- memory What Claude Code's auto memory learned in this
46
- repository — each correction (feedback) and project note
47
- — written as lessons in .opencastle/lessons/. Memories
48
- about you, credentials, and ones already promoted are
49
- left out; your home directory is written as ~.
44
+ memory What your assistant remembered about this repository,
45
+ written as lessons in .opencastle/lessons/: Claude
46
+ Code's auto memory (corrections and project notes),
47
+ VS Code's repository memory (Copilot Chat), and the
48
+ Codex memories whose directory is this repository.
49
+ Memories about you, credentials, and ones already
50
+ promoted are left out; your home directory is written
51
+ as ~. Cursor keeps its memories on its servers and
52
+ Copilot Memory lives on GitHub; neither can be read.
50
53
 
51
54
  Options:
52
55
  --to <dir> skill: a baseline or Agent Plugin directory to put it in
@@ -211,98 +214,28 @@ function promoteSkill(pkgRoot: string, args: string[], dryRun: boolean): void {
211
214
 
212
215
  // ── memory ────────────────────────────────────────────────────
213
216
 
214
- /** The directory Claude Code's settings point auto memory at, if any of them does. */
215
- function configuredMemoryDir(projectRoot: string, configDir: string): string | null {
216
- for (const file of [
217
- join(projectRoot, '.claude', 'settings.local.json'),
218
- join(projectRoot, '.claude', 'settings.json'),
219
- join(configDir, 'settings.json'),
220
- ]) {
221
- try {
222
- const value = (JSON.parse(readFileSync(file, 'utf8')) as { autoMemoryDirectory?: unknown }).autoMemoryDirectory
223
- if (typeof value === 'string' && value) return value.replace(/^~(?=\/|$)/, home())
224
- } catch {
225
- // Absent or unreadable: the next one, or the default.
226
- }
227
- }
228
- return null
229
- }
230
-
231
- /**
232
- * Where Claude Code keeps this repository's auto memory:
233
- * `<config>/projects/<repository path, every other character a hyphen>/memory/`.
234
- * Every worktree of one repository shares it, so the path is the main
235
- * checkout's, which git names as the common directory's parent.
236
- */
237
- export function claudeMemoryDir(projectRoot: string): string {
238
- const configDir = process.env.CLAUDE_CONFIG_DIR || join(home(), '.claude')
239
- const configured = configuredMemoryDir(projectRoot, configDir)
240
- if (configured) return configured
241
- let repo = projectRoot
242
- try {
243
- const common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
244
- cwd: projectRoot,
245
- encoding: 'utf8',
246
- stdio: ['ignore', 'pipe', 'ignore'],
247
- }).trim()
248
- repo = basename(common) === '.git' ? dirname(common) : projectRoot
249
- } catch {
250
- repo = projectRoot
251
- }
252
- const slug = process.env.CLAUDE_CODE_PROJECT_DIR_NAME || repo.replace(/[^A-Za-z0-9]/g, '-')
253
- return join(configDir, 'projects', slug, 'memory')
254
- }
255
-
256
- interface Memory {
257
- file: string
258
- name: string
259
- description?: string
260
- type?: string
261
- body: string
262
- }
263
-
264
- function readMemories(dir: string): Memory[] {
265
- const out: Memory[] = []
266
- for (const file of readdirSync(dir).sort()) {
267
- if (!file.endsWith('.md') || file === 'MEMORY.md') continue
268
- const abs = join(dir, file)
269
- if (!statSync(abs).isFile()) continue
270
- const text = readFileSync(abs, 'utf8').replace(/^\uFEFF/, '')
271
- const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text)
272
- let meta: Record<string, unknown> = {}
273
- try {
274
- meta = m ? ((parseYaml(m[1]) ?? {}) as Record<string, unknown>) : {}
275
- } catch {
276
- meta = {}
277
- }
278
- const nested = meta.metadata && typeof meta.metadata === 'object' ? (meta.metadata as Record<string, unknown>) : {}
279
- const type = typeof meta.type === 'string' ? meta.type : typeof nested.type === 'string' ? nested.type : undefined
280
- out.push({
281
- file,
282
- name: typeof meta.name === 'string' ? meta.name : file.replace(/\.md$/, ''),
283
- description: typeof meta.description === 'string' ? meta.description : undefined,
284
- type,
285
- body: (m ? m[2] : text).trim(),
286
- })
287
- }
288
- return out
289
- }
290
-
291
- /** A title for a memory: its description, else its name read as words. */
292
- function titleOf(memory: Memory): string {
293
- const raw = memory.description ?? memory.name.replace(/[-_]+/g, ' ')
294
- const one = raw.replace(/[\r\n]+/g, ' ').trim()
295
- return one.charAt(0).toUpperCase() + one.slice(1)
296
- }
217
+ export { claudeMemoryDir } from './memory-sources.js'
297
218
 
298
219
  function promoteMemory(args: string[], dryRun: boolean): void {
299
220
  const projectRoot = projectRootFrom(process.cwd())
300
221
  const customizations = join(projectRoot, '.opencastle')
301
222
  if (!existsSync(customizations)) fail('no .opencastle/ here — run npx opencastle init first')
302
223
  const from = flag(args, '--from')
303
- const dir = from ? resolve(process.cwd(), from.replace(/^~(?=\/|$)/, home())) : claudeMemoryDir(projectRoot)
304
- if (!existsSync(dir)) {
305
- fail(`no memory at ${tilde(dir)} — Claude Code keeps it there once it has saved one for this repository; --from <dir> reads another`)
224
+ let sources: MemorySource[]
225
+ if (from) {
226
+ const dir = resolve(process.cwd(), from.replace(/^~(?=\/|$)/, home()))
227
+ if (!existsSync(dir)) fail(`no memory at ${tilde(dir)}`)
228
+ sources = [readMemoryDir(dir, 'Memory')]
229
+ } else {
230
+ const found = readRepositoryMemory(projectRoot)
231
+ sources = found.sources
232
+ if (sources.length === 0) {
233
+ fail(
234
+ `no memory at ${tilde(found.looked[0])}, in VS Code's storage for this folder, or in ${tilde(dirname(found.looked[found.looked.length - 1]))}/memories — ` +
235
+ 'each assistant writes it once it has saved one for this repository; --from <dir> reads another. ' +
236
+ 'Cursor keeps its memories on its servers and Copilot Memory lives on GitHub, so neither can be read here.',
237
+ )
238
+ }
306
239
  }
307
240
 
308
241
  syncLessons(customizations)
@@ -310,58 +243,45 @@ function promoteMemory(args: string[], dryRun: boolean): void {
310
243
  const promoted = new Set(lessons.map((l) => l.source).filter((s): s is string => Boolean(s)))
311
244
  const taken = new Set(lessons.map((l) => l.id))
312
245
  const written: string[] = []
313
- const skipped: Array<[string, string]> = []
314
- const h = home()
315
246
 
316
- for (const memory of readMemories(dir)) {
317
- if (memory.type && !['feedback', 'project'].includes(memory.type)) {
318
- skipped.push([memory.file, memory.type === 'user' ? 'about you, not the project' : `a ${memory.type} memory`])
319
- continue
320
- }
321
- if (!memory.body) {
322
- skipped.push([memory.file, 'empty'])
323
- continue
324
- }
325
- const digest = createHash('sha256').update(memory.body).digest('hex').slice(0, 12)
326
- const source = `claude-code-memory:${memory.file}#${digest}`
327
- if (promoted.has(source)) {
328
- skipped.push([memory.file, 'already a lesson'])
329
- continue
330
- }
331
- // A memory names paths on its author's machine; the team's copy says ~.
332
- const body = memory.body.split(h).join('~')
333
- const scan = scanForSecrets(body, memory.file)
334
- if (!scan.clean) {
335
- skipped.push([memory.file, `holds what looks like a ${scan.findings[0].pattern} (line ${scan.findings[0].line})`])
336
- continue
337
- }
338
- const title = titleOf(memory)
339
- const id = newLessonId(title, today(), taken)
340
- taken.add(id)
341
- const lesson: Omit<Lesson, 'file'> = {
342
- id,
343
- title,
344
- category: 'general',
345
- severity: 'medium',
346
- added: today(),
347
- citations: [],
348
- status: 'active',
349
- source,
350
- body,
351
- }
352
- written.push(`${LESSONS_DIR}/${id}.md`)
353
- if (!dryRun) {
354
- mkdirSync(join(customizations, LESSONS_DIR), { recursive: true })
355
- writeFileSync(join(customizations, LESSONS_DIR, `${id}.md`), renderLesson(lesson))
247
+ console.log(`\n 🏰 ${c.bold('Promote memory')}`)
248
+ for (const source of sources) {
249
+ const wrote: string[] = []
250
+ const skipped = [...source.skipped]
251
+ for (const memory of source.candidates) {
252
+ if (promoted.has(memory.source)) {
253
+ skipped.push([memory.label, 'already a lesson'])
254
+ continue
255
+ }
256
+ promoted.add(memory.source)
257
+ const id = newLessonId(memory.title, today(), taken)
258
+ taken.add(id)
259
+ const lesson: Omit<Lesson, 'file'> = {
260
+ id,
261
+ title: memory.title,
262
+ category: 'general',
263
+ severity: 'medium',
264
+ added: today(),
265
+ citations: [],
266
+ status: 'active',
267
+ source: memory.source,
268
+ body: memory.body,
269
+ }
270
+ wrote.push(`${LESSONS_DIR}/${id}.md`)
271
+ if (!dryRun) {
272
+ mkdirSync(join(customizations, LESSONS_DIR), { recursive: true })
273
+ writeFileSync(join(customizations, LESSONS_DIR, `${id}.md`), renderLesson(lesson))
274
+ }
356
275
  }
276
+ written.push(...wrote)
277
+ console.log(`\n ${c.bold(source.assistant)} ${c.dim(`from ${tilde(source.where)}`)}`)
278
+ for (const w of wrote) console.log(` ${c.green(dryRun ? '+' : '✓')} ${dryRun ? 'Would write' : 'Wrote'} .opencastle/${w}`)
279
+ for (const [file, why] of skipped) console.log(` ${c.dim(`- ${file}: ${why}`)}`)
357
280
  }
358
281
  if (!dryRun && written.length > 0) syncLessons(customizations)
359
282
 
360
- console.log(`\n 🏰 ${c.bold('Promote memory')} ${c.dim(`from ${tilde(dir)}`)}\n`)
361
- if (written.length === 0) console.log(` ${c.dim('Nothing new to promote.')}`)
362
- for (const w of written) console.log(` ${c.green(dryRun ? '+' : '✓')} ${dryRun ? 'Would write' : 'Wrote'} .opencastle/${w}`)
363
- for (const [file, why] of skipped) console.log(` ${c.dim(`- ${file}: ${why}`)}`)
364
- if (written.length > 0 && !dryRun) {
283
+ if (written.length === 0) console.log(`\n ${c.dim('Nothing new to promote.')}\n`)
284
+ else if (!dryRun) {
365
285
  console.log(
366
286
  `\n ${c.dim('Each is category general, severity medium: set them, add --cite where a lesson is about code,')}` +
367
287
  `\n ${c.dim('and delete any that are yours alone. The pull request that commits them is where the team agrees.')}\n`,
package/src/cli/status.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { resolve } from 'node:path'
1
+ import { join, resolve } from 'node:path'
2
2
  import { existsSync, statSync } from 'node:fs'
3
3
  import { readdir, stat } from 'node:fs/promises'
4
4
  import { readManifest } from './manifest.js'
@@ -21,7 +21,8 @@ import type { CliContext, IdeAdapter, Manifest } from './types.js'
21
21
  const STATUS_HELP = `
22
22
  opencastle
23
23
 
24
- Show what is installed, whether generated files are current, and what to run next.
24
+ Show what is installed, whether generated files are current, what to run next,
25
+ and how many of your assistant's memories the team has not got yet.
25
26
 
26
27
  Options:
27
28
  --json Machine-readable output
@@ -53,6 +54,8 @@ export interface StatusReport {
53
54
  nextReason?: string
54
55
  /** The baselines the committed lock records, as `name version`. */
55
56
  baselines?: string[]
57
+ /** Memories this machine's assistants keep about the repository that no lesson holds yet. */
58
+ unsharedMemories?: Array<{ assistant: string; count: number }>
56
59
  }
57
60
 
58
61
  /** Newest mtime under a directory tree, or 0 when absent. */
@@ -334,10 +337,23 @@ export async function buildStatusReport(pkgRoot: string, projectRoot: string): P
334
337
  baselines = []
335
338
  }
336
339
 
340
+ // What this person's assistants learned here and the team has not seen.
341
+ // Not a fault, so it never becomes the next command: it only says so.
342
+ let unsharedMemories: Array<{ assistant: string; count: number }> = []
343
+ try {
344
+ const { readLessons } = await import('./lessons.js')
345
+ const { unsharedMemory } = await import('./memory-sources.js')
346
+ const { lessons } = readLessons(join(projectRoot, '.opencastle'))
347
+ unsharedMemories = unsharedMemory(projectRoot, new Set(lessons.map((l) => l.source).filter((s): s is string => Boolean(s))))
348
+ } catch {
349
+ unsharedMemories = []
350
+ }
351
+
337
352
  return {
338
353
  installed: true,
339
354
  missingRequired,
340
355
  ...(baselines.length > 0 && { baselines }),
356
+ ...(unsharedMemories.length > 0 && { unsharedMemories }),
341
357
  version: manifest.version,
342
358
  ides: adapters.map((a) => a.ide),
343
359
  targets,
@@ -402,6 +418,17 @@ function render(report: StatusReport): void {
402
418
  console.log(` ${c.dim('Not compiled:')} ${report.unmanaged.join(', ')}`)
403
419
  }
404
420
 
421
+ const unshared = report.unsharedMemories ?? []
422
+ if (unshared.length > 0) {
423
+ const n = unshared.reduce((sum, u) => sum + u.count, 0)
424
+ console.log('')
425
+ console.log(
426
+ ` ${c.dim('Memory')} ${n} ${n === 1 ? 'memory' : 'memories'} on this machine the team has not got yet ` +
427
+ c.dim(`(${unshared.map((u) => `${u.assistant} ${u.count}`).join(', ')})`),
428
+ )
429
+ console.log(` ${c.cyan('npx opencastle promote memory')} ${c.dim(n === 1 ? 'makes it a lesson for everyone' : 'makes them lessons for everyone')}`)
430
+ }
431
+
405
432
  console.log('')
406
433
  if (report.nextCommand) {
407
434
  console.log(` ${c.bold('Next:')} ${c.cyan(report.nextCommand)}`)
@@ -3,7 +3,7 @@
3
3
  * teammate and a CI job drive them — against a baseline installed where npm
4
4
  * would install it.
5
5
  */
6
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs'
6
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, existsSync } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve, dirname } from 'node:path'
9
9
  import { execFileSync } from 'node:child_process'
@@ -70,6 +70,19 @@ describe.skipIf(!built)('a repository extending a baseline', () => {
70
70
  rmSync(dir, { recursive: true, force: true })
71
71
  })
72
72
 
73
+ it('archives a lesson into a skill the baseline gives the repository, and refuses one nothing gives it', () => {
74
+ const add = run(dir, ['lesson', '--title', 'Escape user input in SQL', '--category', 'database', '--severity', 'high', '--problem', 'A raw string reached the query'])
75
+ expect(add.code, add.out).toBe(0)
76
+ const id = readdirSync(join(dir, '.opencastle', 'lessons'))[0].replace(/\.md$/, '')
77
+ const missing = run(dir, ['lesson', 'archive', id, '--into', 'skills/no-such-skill'])
78
+ expect(missing.code).toBe(1)
79
+ expect(missing.out).toContain('neither a file in this project nor an item any layer gives it')
80
+ const done = run(dir, ['lesson', 'archive', id, '--into', 'skills/secure-coding'])
81
+ expect(done.code, done.out).toBe(0)
82
+ expect(done.out).toContain('merged into skills/secure-coding from @acme/base')
83
+ expect(readFileSync(join(dir, '.opencastle', 'LESSONS-LEARNED.md'), 'utf8')).toContain('**Escape user input in SQL** → `skills/secure-coding`')
84
+ })
85
+
73
86
  it("compiles the baseline and the project's own server, writes the lock, and checks clean", () => {
74
87
  expect(existsSync(join(dir, '.github', 'skills', 'secure-coding', 'SKILL.md'))).toBe(true)
75
88
  expect(JSON.parse(readFileSync(join(dir, '.vscode', 'mcp.json'), 'utf8')).servers['acme-db']).toBeDefined()
@@ -41,7 +41,7 @@ rg -i "CRON_SECRET" .opencastle/lessons/ || true
41
41
 
42
42
  Every agent reads every active lesson before every task, so a lesson that has proven itself belongs in the skill or instruction file it is about, where only the agents that need it read it. `doctor` warns when the index passes about 2,000 tokens. Candidates: older than 60 days and still true, a problem two lessons describe, or `severity: high`.
43
43
 
44
- 1. Rewrite it as a rule or an example in that file, beside the rules it belongs with — a rule, not an incident report, and no new file.
45
- 2. `npx opencastle lesson archive <id> --into <that file>`. The lesson keeps its file and moves to the index's Archived section; never delete one.
44
+ 1. Rewrite it as a rule or an example in that file, beside the rules it belongs with — a rule, not an incident report, and no new file. A lesson that holds in every repository belongs in the skill it is about in the organisation's baseline: change it there, and once the baseline version carrying it is installed here, archive it.
45
+ 2. `npx opencastle lesson archive <id> --into <that file>`, or `--into skills/<name>` for a skill the baseline gives this repository. The lesson keeps its file and moves to the index's Archived section; never delete one.
46
46
 
47
47
  Resolve two lessons that contradict each other before you merge either.