opencastle 1.9.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +28 -14
  2. package/bin/cli.mjs +2 -2
  3. package/dist/cli/adapters/claude-code.d.ts +7 -2
  4. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  5. package/dist/cli/adapters/claude-code.js +13 -2
  6. package/dist/cli/adapters/claude-code.js.map +1 -1
  7. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  8. package/dist/cli/adapters/rules-dir-base.js +12 -2
  9. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  10. package/dist/cli/adapters/rules-dir-base.test.js +3 -1
  11. package/dist/cli/adapters/rules-dir-base.test.js.map +1 -1
  12. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  13. package/dist/cli/adapters/vscode.js +12 -2
  14. package/dist/cli/adapters/vscode.js.map +1 -1
  15. package/dist/cli/ci.d.ts +8 -0
  16. package/dist/cli/ci.d.ts.map +1 -1
  17. package/dist/cli/ci.js +24 -17
  18. package/dist/cli/ci.js.map +1 -1
  19. package/dist/cli/convoy/findings.js +3 -2
  20. package/dist/cli/convoy/findings.js.map +1 -1
  21. package/dist/cli/docs-accuracy.test.js +4 -4
  22. package/dist/cli/docs-accuracy.test.js.map +1 -1
  23. package/dist/cli/init.d.ts.map +1 -1
  24. package/dist/cli/init.js +9 -0
  25. package/dist/cli/init.js.map +1 -1
  26. package/dist/cli/lesson.js +3 -2
  27. package/dist/cli/lesson.js.map +1 -1
  28. package/dist/cli/lessons-rules.d.ts +45 -0
  29. package/dist/cli/lessons-rules.d.ts.map +1 -0
  30. package/dist/cli/lessons-rules.js +130 -0
  31. package/dist/cli/lessons-rules.js.map +1 -0
  32. package/dist/cli/lessons-rules.test.d.ts +2 -0
  33. package/dist/cli/lessons-rules.test.d.ts.map +1 -0
  34. package/dist/cli/lessons-rules.test.js +65 -0
  35. package/dist/cli/lessons-rules.test.js.map +1 -0
  36. package/dist/cli/memory-hooks.d.ts +51 -0
  37. package/dist/cli/memory-hooks.d.ts.map +1 -0
  38. package/dist/cli/memory-hooks.js +200 -0
  39. package/dist/cli/memory-hooks.js.map +1 -0
  40. package/dist/cli/memory-hooks.test.d.ts +2 -0
  41. package/dist/cli/memory-hooks.test.d.ts.map +1 -0
  42. package/dist/cli/memory-hooks.test.js +83 -0
  43. package/dist/cli/memory-hooks.test.js.map +1 -0
  44. package/dist/cli/memory-sources.d.ts.map +1 -1
  45. package/dist/cli/memory-sources.js +3 -2
  46. package/dist/cli/memory-sources.js.map +1 -1
  47. package/dist/cli/promote-command.test.js +40 -10
  48. package/dist/cli/promote-command.test.js.map +1 -1
  49. package/dist/cli/promote.d.ts.map +1 -1
  50. package/dist/cli/promote.js +41 -11
  51. package/dist/cli/promote.js.map +1 -1
  52. package/dist/cli/remove.d.ts.map +1 -1
  53. package/dist/cli/remove.js +27 -0
  54. package/dist/cli/remove.js.map +1 -1
  55. package/dist/cli/status.d.ts +0 -5
  56. package/dist/cli/status.d.ts.map +1 -1
  57. package/dist/cli/status.js +2 -24
  58. package/dist/cli/status.js.map +1 -1
  59. package/dist/cli/sync-check.d.ts +1 -1
  60. package/dist/cli/sync-check.d.ts.map +1 -1
  61. package/dist/cli/sync-check.js +27 -2
  62. package/dist/cli/sync-check.js.map +1 -1
  63. package/dist/cli/update.d.ts.map +1 -1
  64. package/dist/cli/update.js +17 -0
  65. package/dist/cli/update.js.map +1 -1
  66. package/package.json +2 -2
  67. package/src/cli/adapters/claude-code.ts +15 -2
  68. package/src/cli/adapters/rules-dir-base.test.ts +3 -1
  69. package/src/cli/adapters/rules-dir-base.ts +11 -2
  70. package/src/cli/adapters/vscode.ts +11 -2
  71. package/src/cli/ci.ts +23 -16
  72. package/src/cli/convoy/findings.ts +2 -2
  73. package/src/cli/docs-accuracy.test.ts +4 -4
  74. package/src/cli/init.ts +10 -0
  75. package/src/cli/lesson.ts +2 -2
  76. package/src/cli/lessons-rules.test.ts +71 -0
  77. package/src/cli/lessons-rules.ts +128 -0
  78. package/src/cli/memory-hooks.test.ts +102 -0
  79. package/src/cli/memory-hooks.ts +207 -0
  80. package/src/cli/memory-sources.ts +3 -2
  81. package/src/cli/promote-command.test.ts +43 -10
  82. package/src/cli/promote.ts +37 -11
  83. package/src/cli/remove.ts +22 -0
  84. package/src/cli/status.ts +2 -28
  85. package/src/cli/sync-check.ts +30 -3
  86. package/src/cli/update.ts +17 -0
  87. package/src/orchestrator/instructions/general.instructions.md +1 -1
  88. package/src/orchestrator/prompts/implement-feature.prompt.md +1 -1
  89. package/src/orchestrator/skills/self-improvement/SKILL.md +14 -13
@@ -4,6 +4,8 @@ import { existsSync, readdirSync, realpathSync } from 'node:fs'
4
4
  import { writeManagedBlock, recordMerge } from '../managed-block.js'
5
5
  import { mergeCopyResults, copyDir } from '../copy.js'
6
6
  import { scaffoldMcpConfigInto } from '../mcp.js'
7
+ import { compileTeamMemory } from '../memory-hooks.js'
8
+ import { isLessonRule } from '../lessons-rules.js'
7
9
  import { getAgentTransform } from '../stack-config.js'
8
10
  import { withSource, type CompileSource } from '../layers.js'
9
11
  import type { CopyResults, CopyDirOptions, DoctorCheck, ManagedPaths, RepoInfo, StackConfig } from '../types.js'
@@ -117,7 +119,9 @@ export async function install(
117
119
  repoInfo?: RepoInfo,
118
120
  source?: CompileSource,
119
121
  ): Promise<CopyResults> {
120
- return withSource(pkgRoot, stack, source, (src) => installFrom(src, projectRoot, stack, repoInfo))
122
+ const results = await withSource(pkgRoot, stack, source, (src) => installFrom(src, projectRoot, stack, repoInfo))
123
+ compileTeamMemory(pkgRoot, projectRoot, IDE_ID)
124
+ return results
121
125
  }
122
126
 
123
127
  async function installFrom(
@@ -173,7 +177,12 @@ export async function update(
173
177
  _repoInfo?: RepoInfo,
174
178
  source?: CompileSource,
175
179
  ): Promise<CopyResults> {
176
- return withSource(pkgRoot, stack, source, (src) => updateFrom(src, projectRoot, stack))
180
+ const results = await withSource(pkgRoot, stack, source, (src) => updateFrom(src, projectRoot, stack))
181
+ compileTeamMemory(pkgRoot, projectRoot, IDE_ID)
182
+ // The sweep took the lessons rule with the rest of the directory, and it is
183
+ // back: not a file this sync removed.
184
+ if (results.deleted) results.deleted = results.deleted.filter((rel) => !isLessonRule(rel))
185
+ return results
177
186
  }
178
187
 
179
188
  async function updateFrom(src: CompileSource, projectRoot: string, stack: StackConfig | undefined): Promise<CopyResults> {
package/src/cli/ci.ts CHANGED
@@ -94,6 +94,27 @@ function findUp(start: string, names: string[], stop: string): string | null {
94
94
  * `extraPaths`: directories outside the project the check depends on — a
95
95
  * baseline kept elsewhere in the repository, whose change must run it too.
96
96
  */
97
+ /**
98
+ * How to run OpenCastle in this project from a workflow or a hook. The
99
+ * project's own copy when it has one: then every laptop and CI run the version
100
+ * its lockfile pins, and nobody's global install decides the output. Otherwise
101
+ * the release that compiled the project.
102
+ */
103
+ export function opencastleRunner(projectRoot: string, cliVersion: string, pm?: PackageManager): string {
104
+ let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> } = {}
105
+ try {
106
+ pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'))
107
+ } catch {
108
+ pkg = {}
109
+ }
110
+ if (!(pkg.devDependencies?.opencastle ?? pkg.dependencies?.opencastle)) return `npx -y opencastle@${cliVersion}`
111
+ const manager = pm ?? (() => {
112
+ const root = findUp(projectRoot, ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'bun.lock'], repoRootOf(projectRoot))
113
+ return root ? packageManagerOf(root) : 'npm'
114
+ })()
115
+ return manager === 'pnpm' ? 'pnpm exec opencastle' : manager === 'yarn' ? 'yarn opencastle' : 'npx --no opencastle'
116
+ }
117
+
97
118
  export function planCi(projectRoot: string, cliVersion: string, owners?: string, extraPaths: string[] = []): Plan {
98
119
  const repoRoot = repoRootOf(projectRoot)
99
120
  const prefix = (git(projectRoot, ['rev-parse', '--show-prefix']) ?? '').replace(/\/$/, '')
@@ -104,22 +125,8 @@ export function planCi(projectRoot: string, cliVersion: string, owners?: string,
104
125
  (existsSync(join(projectRoot, 'package.json')) ? projectRoot : null)
105
126
  const pm = installRoot ? packageManagerOf(installRoot) : 'npm'
106
127
 
107
- let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> } = {}
108
- try {
109
- pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'))
110
- } catch {
111
- pkg = {}
112
- }
113
- // The project's own copy when it has one: then every laptop and CI run the
114
- // version its lockfile pins, and nobody's global install decides the output.
115
- const pinned = Boolean(pkg.devDependencies?.opencastle ?? pkg.dependencies?.opencastle)
116
- const run = pinned
117
- ? pm === 'pnpm'
118
- ? 'pnpm exec opencastle'
119
- : pm === 'yarn'
120
- ? 'yarn opencastle'
121
- : 'npx --no opencastle'
122
- : `npx -y opencastle@${cliVersion}`
128
+ const run = opencastleRunner(projectRoot, cliVersion, pm)
129
+ const pinned = !run.startsWith('npx -y ')
123
130
 
124
131
  const install: string[] = []
125
132
  let installRel = ''
@@ -19,9 +19,9 @@ import {
19
19
  newLessonId,
20
20
  readLessons,
21
21
  renderLesson,
22
- syncLessons,
23
22
  today,
24
23
  } from '../lessons.js'
24
+ import { refreshLessons } from '../lessons-rules.js'
25
25
 
26
26
  export interface ReportedLesson {
27
27
  taskId: string
@@ -124,6 +124,6 @@ export function recordLessons(
124
124
  }
125
125
  // Also moves an old single-file log into lesson files, which is why the
126
126
  // commit takes the whole folder and not only the files written here.
127
- if (written.length > 0) syncLessons(customizationsDir)
127
+ if (written.length > 0) refreshLessons(customizationsDir)
128
128
  return written
129
129
  }
@@ -473,12 +473,12 @@ describe('website matches the shipped CLI', () => {
473
473
  })
474
474
  })
475
475
 
476
- describe('the pitch leads with the compiler', () => {
476
+ describe('the pitch leads with shared memory', () => {
477
477
  it('says what the tool does before listing what is inside', () => {
478
- const compiles = readme.search(/compiles one source/i)
478
+ const does = readme.search(/OpenCastle makes it the team's/i)
479
479
  const inside = readme.indexOf('## What gets compiled')
480
- expect(compiles).toBeGreaterThan(-1)
481
- expect(compiles).toBeLessThan(inside)
480
+ expect(does).toBeGreaterThan(-1)
481
+ expect(does).toBeLessThan(inside)
482
482
  })
483
483
 
484
484
  it('marks the convoy engine experimental wherever it is introduced', () => {
package/src/cli/init.ts CHANGED
@@ -20,6 +20,8 @@ import { stripManagedBlock, stripManagedBlockFromFile } from './managed-block.js
20
20
  import { resolveManagedPaths, declaredManagedPaths, ownerOf, removeOwnedFiles } from './managed-paths.js'
21
21
  import { noteUnreadable, whyLeftAlone } from './unreadable-report.js'
22
22
  import { resolveSources, materialize, hasErrors, formatIssues, requiredEnvVars } from './layers.js'
23
+ import { writeLessonRules } from './lessons-rules.js'
24
+ import { memoryHooksDrift } from './memory-hooks.js'
23
25
  import { buildLock, writeLock, priorTeam } from './lock.js'
24
26
  import { parseVersion, compareVersions } from './version-range.js'
25
27
  import { COMMAND_NAMESPACE } from './command-namespace.js'
@@ -718,8 +720,16 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
718
720
  const envVars = requiredEnvVars(resolved, stack, combinedRepoInfo)
719
721
  const gitignoreResult = await updateGitignore(projectRoot)
720
722
 
723
+ // ── The team's memory ───────────────────────────────────────────
724
+ // Each target's compile wrote the lessons it loads and its memory hook.
725
+ writeLessonRules(projectRoot, ides)
726
+ const unreadableHook = memoryHooksDrift(projectRoot, ides, pkg.version).find((h) => h.unreadable)
727
+
721
728
  // ── Summary ─────────────────────────────────────────────────────
722
729
  console.log(` ${c.green('✓')} Created ${c.bold(String(totalCreated))} files`)
730
+ if (unreadableHook) {
731
+ console.log(` ${c.yellow('!')} ${unreadableHook.path} is not valid JSON, so the memory hook was not added — fix it and run npx opencastle sync`)
732
+ }
723
733
  for (const { ide, message } of failedTargets) {
724
734
  console.log(` ${c.red('✗')} ${IDE_LABELS[ide as IdeChoice] ?? ide} could not be installed:`)
725
735
  console.log(` ${c.dim(message)}`)
package/src/cli/lesson.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { stat, writeFile, mkdir } from 'node:fs/promises'
2
2
  import { join, dirname } from 'node:path'
3
3
  import type { CliContext } from './types.js'
4
+ import { refreshLessons } from './lessons-rules.js'
4
5
  import { scanForSecrets } from './secret-scan.js'
5
6
  import {
6
7
  LESSON_CATEGORIES,
@@ -16,7 +17,6 @@ import {
16
17
  newLessonId,
17
18
  readLessons,
18
19
  renderLesson,
19
- syncLessons,
20
20
  today,
21
21
  type Lesson,
22
22
  } from './lessons.js'
@@ -166,7 +166,7 @@ async function writeLessonFile(dir: string, lesson: Omit<Lesson, 'file'>, file:
166
166
 
167
167
  /** Rewrite the index, after moving anything still in the old single file. */
168
168
  function reindex(dir: string): void {
169
- const outcome = syncLessons(dir)
169
+ const outcome = refreshLessons(dir)
170
170
  if (outcome.migrated > 0) {
171
171
  console.log(
172
172
  ` Moved ${outcome.migrated} lesson(s) from ${LESSONS_INDEX} into .opencastle/${LESSONS_DIR}/` +
@@ -0,0 +1,71 @@
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
5
+ import { renderLesson, type Lesson } from './lessons.js'
6
+ import { LESSON_RULES, isLessonRule, lessonRulesDrift, refreshLessons, renderLessonsRule, writeLessonRules } from './lessons-rules.js'
7
+
8
+ const lesson = (over: Partial<Lesson> = {}): Omit<Lesson, 'file'> => ({
9
+ id: '2026-10-07-quote-paths',
10
+ title: 'Quote paths with spaces',
11
+ category: 'terminal',
12
+ severity: 'medium',
13
+ added: '2026-10-07',
14
+ citations: [],
15
+ status: 'active',
16
+ body: 'Unquoted paths break.',
17
+ ...over,
18
+ })
19
+
20
+ describe('the lessons every assistant loads', () => {
21
+ let dir: string
22
+ const addLesson = (l: Omit<Lesson, 'file'>): void => {
23
+ mkdirSync(join(dir, '.opencastle', 'lessons'), { recursive: true })
24
+ writeFileSync(join(dir, '.opencastle', 'lessons', `${l.id}.md`), renderLesson(l))
25
+ }
26
+
27
+ beforeEach(() => {
28
+ dir = mkdtempSync(join(tmpdir(), 'oc-lessons-rules-'))
29
+ mkdirSync(join(dir, '.opencastle'), { recursive: true })
30
+ })
31
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
32
+
33
+ it('lists the active lessons in each assistant’s own always-on form, and none for a root-file-only one', () => {
34
+ const lessons: Lesson[] = [
35
+ { ...lesson(), file: '2026-10-07-quote-paths.md' },
36
+ { ...lesson({ id: 'old', title: 'Merged long ago', status: 'archived', mergedInto: 'skills/x' }), file: 'old.md' },
37
+ ]
38
+ const vscode = renderLessonsRule('vscode', lessons) ?? ''
39
+ expect(vscode.startsWith("---\napplyTo: '**'\n---\n")).toBe(true)
40
+ expect(vscode).toContain('- **Quote paths with spaces** — `medium`, terminal · `.opencastle/lessons/2026-10-07-quote-paths.md`')
41
+ expect(vscode).not.toContain('Merged long ago')
42
+ expect(renderLessonsRule('claude-code', lessons)?.startsWith('<!--')).toBe(true)
43
+ expect(renderLessonsRule('cursor', lessons)).toContain('alwaysApply: true')
44
+ expect(renderLessonsRule('windsurf', lessons)).toContain('trigger: always_on')
45
+ expect(renderLessonsRule('codex', lessons)).toBeNull()
46
+ })
47
+
48
+ it('writes what differs, and holds each file to the lessons', () => {
49
+ addLesson(lesson())
50
+ expect(writeLessonRules(dir, ['claude-code', 'vscode', 'codex'])).toEqual([LESSON_RULES['claude-code'].path, LESSON_RULES.vscode.path])
51
+ expect(writeLessonRules(dir, ['claude-code', 'vscode'])).toEqual([])
52
+ expect(lessonRulesDrift(dir, ['claude-code', 'vscode'])).toEqual([])
53
+ addLesson(lesson({ id: '2026-10-08-ci-flag', title: 'Set CI=1 before the build' }))
54
+ expect(lessonRulesDrift(dir, ['claude-code', 'vscode']).map((d) => d.path)).toEqual([LESSON_RULES['claude-code'].path, LESSON_RULES.vscode.path])
55
+ })
56
+
57
+ it('refreshes the index and the rules of the assistants the manifest names, in one call', () => {
58
+ writeFileSync(join(dir, '.opencastle', 'manifest.json'), JSON.stringify({ version: '1.8.0', ides: ['vscode'] }))
59
+ addLesson(lesson())
60
+ refreshLessons(join(dir, '.opencastle'))
61
+ expect(readFileSync(join(dir, '.opencastle', 'LESSONS-LEARNED.md'), 'utf8')).toContain('Quote paths with spaces')
62
+ expect(readFileSync(join(dir, LESSON_RULES.vscode.path), 'utf8')).toContain('Quote paths with spaces')
63
+ expect(lessonRulesDrift(dir, ['vscode'])).toEqual([])
64
+ })
65
+
66
+ it('knows its own paths, which the compile does not produce', () => {
67
+ expect(isLessonRule('.github/instructions/opencastle-lessons.instructions.md')).toBe(true)
68
+ expect(isLessonRule('./.cursor/rules/opencastle-lessons.mdc')).toBe(true)
69
+ expect(isLessonRule('.github/instructions/general.instructions.md')).toBe(false)
70
+ })
71
+ })
@@ -0,0 +1,128 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { LESSONS_DIR, readLessons, syncLessons, type Lesson, type LessonsSync } from './lessons.js'
4
+
5
+ /**
6
+ * The team's lessons, in a file each assistant loads before every task on its
7
+ * own.
8
+ *
9
+ * Lessons used to reach agents through a sentence in their instructions —
10
+ * "read the index before you start" — which an agent follows when it decides
11
+ * to. Project facts stopped depending on that by being compiled into what
12
+ * every assistant loads; this does the same for lessons, through the place
13
+ * each assistant loads rules from with no instruction at all: Claude Code's
14
+ * `.claude/rules/` (a rule with no `paths` loads at launch), VS Code's
15
+ * instructions with `applyTo: '**'`, and Cursor's and Windsurf's always-on
16
+ * rules. Codex, OpenCode and Antigravity have one root file and no such place;
17
+ * their agents still read the index by instruction.
18
+ *
19
+ * The file is derived from the lessons, like the index, so whatever writes a
20
+ * lesson — `opencastle lesson`, `promote memory`, a convoy run, `sync` —
21
+ * rewrites it at once, and `sync --check` holds it to the lessons, not to the
22
+ * compile.
23
+ */
24
+
25
+ export const LESSON_RULES: Readonly<Record<string, { path: string; frontmatter: string }>> = {
26
+ 'claude-code': { path: '.claude/rules/opencastle-lessons.md', frontmatter: '' },
27
+ vscode: { path: '.github/instructions/opencastle-lessons.instructions.md', frontmatter: "---\napplyTo: '**'\n---\n\n" },
28
+ cursor: {
29
+ path: '.cursor/rules/opencastle-lessons.mdc',
30
+ frontmatter: '---\ndescription: "What this team learned the hard way. Read before any task."\nalwaysApply: true\n---\n\n',
31
+ },
32
+ windsurf: { path: '.windsurf/rules/opencastle-lessons.md', frontmatter: '---\ntrigger: always_on\n---\n\n' },
33
+ }
34
+
35
+ /** True for a path one of these files sits at, which the compile does not produce. */
36
+ export function isLessonRule(rel: string): boolean {
37
+ const norm = rel.replace(/\\/g, '/').replace(/^\.\//, '')
38
+ return Object.values(LESSON_RULES).some((r) => r.path === norm)
39
+ }
40
+
41
+ /** The rule's text: the active lessons, titles and paths, newest first in each category. */
42
+ export function renderLessonsRule(ide: string, lessons: Lesson[]): string | null {
43
+ const rule = LESSON_RULES[ide]
44
+ if (!rule) return null
45
+ const active = lessons.filter((l) => l.status === 'active').sort((a, b) => (a.added < b.added ? 1 : -1))
46
+ const lines = [
47
+ '<!-- Written by OpenCastle from .opencastle/lessons/ — edit the lessons, not this file. -->',
48
+ '',
49
+ '# Team lessons',
50
+ '',
51
+ 'What agents on this team confirmed the hard way, each reviewed in a pull request.',
52
+ 'Before a task, open the lessons that touch it.',
53
+ '',
54
+ ]
55
+ if (active.length === 0) lines.push('No lessons yet.')
56
+ for (const l of active) {
57
+ lines.push(`- **${l.title.replace(/\s+/g, ' ').trim()}** — \`${l.severity}\`, ${l.category} · \`.opencastle/${LESSONS_DIR}/${l.file}\``)
58
+ }
59
+ return `${rule.frontmatter}${lines.join('\n')}\n`
60
+ }
61
+
62
+ /** The assistants this project compiles for, from its manifest. */
63
+ export function manifestIdes(projectRoot: string): string[] {
64
+ try {
65
+ const manifest = JSON.parse(readFileSync(join(projectRoot, '.opencastle', 'manifest.json'), 'utf8')) as { ides?: unknown }
66
+ return Array.isArray(manifest.ides) ? manifest.ides.filter((i): i is string => typeof i === 'string') : []
67
+ } catch {
68
+ return []
69
+ }
70
+ }
71
+
72
+ /** Write each assistant's lessons rule that differs from the lessons; returns the paths written. */
73
+ export function writeLessonRules(projectRoot: string, ides: readonly string[]): string[] {
74
+ const { lessons } = readLessons(join(projectRoot, '.opencastle'))
75
+ const written: string[] = []
76
+ for (const ide of ides) {
77
+ const text = renderLessonsRule(ide, lessons)
78
+ if (text === null) continue
79
+ const abs = join(projectRoot, LESSON_RULES[ide].path)
80
+ let current: string | null = null
81
+ try {
82
+ current = readFileSync(abs, 'utf8')
83
+ } catch {
84
+ current = null
85
+ }
86
+ if (current === text) continue
87
+ mkdirSync(dirname(abs), { recursive: true })
88
+ writeFileSync(abs, text)
89
+ written.push(LESSON_RULES[ide].path)
90
+ }
91
+ return written
92
+ }
93
+
94
+ /** Each assistant's lessons rule that is missing or no longer matches the lessons. */
95
+ export function lessonRulesDrift(projectRoot: string, ides: readonly string[]): Array<{ ide: string; path: string; detail: string }> {
96
+ const { lessons } = readLessons(join(projectRoot, '.opencastle'))
97
+ const out: Array<{ ide: string; path: string; detail: string }> = []
98
+ for (const ide of ides) {
99
+ const text = renderLessonsRule(ide, lessons)
100
+ if (text === null) continue
101
+ const rel = LESSON_RULES[ide].path
102
+ const abs = join(projectRoot, rel)
103
+ if (!existsSync(abs)) {
104
+ out.push({ ide, path: rel, detail: 'the lessons rule this assistant loads is missing' })
105
+ continue
106
+ }
107
+ let current = ''
108
+ try {
109
+ current = readFileSync(abs, 'utf8')
110
+ } catch {
111
+ current = ''
112
+ }
113
+ if (current !== text) out.push({ ide, path: rel, detail: 'no longer lists the lessons in .opencastle/lessons/' })
114
+ }
115
+ return out
116
+ }
117
+
118
+ /**
119
+ * Rewrite everything derived from the lessons: the index agents read, and each
120
+ * assistant's rule. What every writer of a lesson calls instead of the index
121
+ * alone, so the two can never disagree.
122
+ */
123
+ export function refreshLessons(customizationsDir: string): LessonsSync {
124
+ const outcome = syncLessons(customizationsDir)
125
+ const projectRoot = dirname(customizationsDir)
126
+ writeLessonRules(projectRoot, manifestIdes(projectRoot))
127
+ return outcome
128
+ }
@@ -0,0 +1,102 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
5
+ import {
6
+ CLAUDE_SETTINGS,
7
+ VSCODE_HOOK_FILE,
8
+ memoryHookCommand,
9
+ memoryHookPaths,
10
+ memoryHooksDrift,
11
+ stripMemoryHooks,
12
+ writeMemoryHooks,
13
+ } from './memory-hooks.js'
14
+
15
+ describe('memory hooks', () => {
16
+ let dir: string
17
+ const read = (rel: string): string => readFileSync(join(dir, rel), 'utf8')
18
+ const write = (rel: string, text: string): void => {
19
+ mkdirSync(dirname(join(dir, rel)), { recursive: true })
20
+ writeFileSync(join(dir, rel), text)
21
+ }
22
+ const settings = (): { hooks?: { SessionEnd?: Array<{ hooks: Array<{ command: string }> }> }; [k: string]: unknown } =>
23
+ JSON.parse(read(CLAUDE_SETTINGS))
24
+ const ourCommands = (): string[] =>
25
+ (settings().hooks?.SessionEnd ?? []).flatMap((g) => g.hooks.map((h) => h.command)).filter((c) => c.includes('promote memory'))
26
+
27
+ beforeEach(() => {
28
+ dir = mkdtempSync(join(tmpdir(), 'oc-memory-hooks-'))
29
+ })
30
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
31
+
32
+ it('runs the project’s own copy when it has one, and the compiling release when not', () => {
33
+ expect(memoryHookCommand(dir, '1.8.0')).toBe('npx -y opencastle@1.8.0 promote memory --json')
34
+ write('package.json', JSON.stringify({ devDependencies: { opencastle: '^1.8.0' } }))
35
+ expect(memoryHookCommand(dir, '1.8.0')).toBe('npx --no opencastle promote memory --json')
36
+ })
37
+
38
+ it('writes a SessionEnd hook for Claude Code and a Stop hook for VS Code', () => {
39
+ const out = writeMemoryHooks(dir, ['claude-code', 'vscode'], '1.8.0')
40
+ expect(out).toEqual([
41
+ { path: CLAUDE_SETTINGS, outcome: 'created' },
42
+ { path: VSCODE_HOOK_FILE, outcome: 'created' },
43
+ ])
44
+ expect(settings()).toEqual({
45
+ hooks: { SessionEnd: [{ hooks: [{ type: 'command', command: 'npx -y opencastle@1.8.0 promote memory --json', timeout: 30 }] }] },
46
+ })
47
+ expect(JSON.parse(read(VSCODE_HOOK_FILE))).toEqual({
48
+ hooks: { Stop: [{ type: 'command', command: 'npx -y opencastle@1.8.0 promote memory --json', timeout: 30 }] },
49
+ })
50
+ expect(memoryHooksDrift(dir, ['claude-code', 'vscode'], '1.8.0')).toEqual([])
51
+ })
52
+
53
+ it('adds its entry beside the project’s own settings and hooks, and changes nothing on a second run', () => {
54
+ write(CLAUDE_SETTINGS, JSON.stringify({ permissions: { allow: ['Bash(npm test)'] }, hooks: { SessionEnd: [{ hooks: [{ type: 'command', command: 'echo bye' }] }], PreToolUse: [] } }))
55
+ expect(writeMemoryHooks(dir, ['claude-code'], '1.8.0')).toEqual([{ path: CLAUDE_SETTINGS, outcome: 'updated' }])
56
+ const first = read(CLAUDE_SETTINGS)
57
+ expect(settings().permissions).toEqual({ allow: ['Bash(npm test)'] })
58
+ expect((settings().hooks as Record<string, unknown>).PreToolUse).toEqual([])
59
+ expect(settings().hooks?.SessionEnd?.[0].hooks[0].command).toBe('echo bye')
60
+ expect(ourCommands()).toEqual(['npx -y opencastle@1.8.0 promote memory --json'])
61
+ expect(writeMemoryHooks(dir, ['claude-code'], '1.8.0')).toEqual([{ path: CLAUDE_SETTINGS, outcome: 'unchanged' }])
62
+ expect(read(CLAUDE_SETTINGS)).toBe(first)
63
+ })
64
+
65
+ it('replaces its own entry when the release changes, and keeps just one', () => {
66
+ writeMemoryHooks(dir, ['claude-code'], '1.8.0')
67
+ expect(memoryHooksDrift(dir, ['claude-code'], '1.9.0')).toHaveLength(1)
68
+ writeMemoryHooks(dir, ['claude-code'], '1.9.0')
69
+ expect(ourCommands()).toEqual(['npx -y opencastle@1.9.0 promote memory --json'])
70
+ })
71
+
72
+ it('leaves a settings file it cannot read alone, and says so', () => {
73
+ write(CLAUDE_SETTINGS, '{ "hooks": ')
74
+ expect(writeMemoryHooks(dir, ['claude-code'], '1.8.0')).toEqual([{ path: CLAUDE_SETTINGS, outcome: 'unreadable' }])
75
+ expect(read(CLAUDE_SETTINGS)).toBe('{ "hooks": ')
76
+ expect(memoryHooksDrift(dir, ['claude-code'], '1.8.0')[0].unreadable).toBe(true)
77
+ })
78
+
79
+ it('reports a hook that was removed or edited', () => {
80
+ writeMemoryHooks(dir, ['claude-code', 'vscode'], '1.8.0')
81
+ write(CLAUDE_SETTINGS, JSON.stringify({ permissions: {} }))
82
+ write(VSCODE_HOOK_FILE, '{"hooks":{}}\n')
83
+ expect(memoryHooksDrift(dir, ['claude-code', 'vscode'], '1.8.0').map((d) => d.path)).toEqual([CLAUDE_SETTINGS, VSCODE_HOOK_FILE])
84
+ expect(memoryHooksDrift(dir, ['cursor'], '1.8.0')).toEqual([])
85
+ })
86
+
87
+ it('takes back only its own: the entry from the settings, and its hook file', () => {
88
+ write(CLAUDE_SETTINGS, JSON.stringify({ permissions: { allow: ['Bash(npm test)'] }, hooks: { SessionEnd: [{ hooks: [{ type: 'command', command: 'echo bye' }] }] } }))
89
+ writeMemoryHooks(dir, ['claude-code', 'vscode'], '1.8.0')
90
+ expect(memoryHookPaths(dir)).toEqual([CLAUDE_SETTINGS, VSCODE_HOOK_FILE])
91
+ expect(stripMemoryHooks(dir)).toEqual([CLAUDE_SETTINGS, VSCODE_HOOK_FILE])
92
+ expect(settings()).toEqual({ permissions: { allow: ['Bash(npm test)'] }, hooks: { SessionEnd: [{ hooks: [{ type: 'command', command: 'echo bye' }] }] } })
93
+ expect(existsSync(join(dir, VSCODE_HOOK_FILE))).toBe(false)
94
+ expect(memoryHookPaths(dir)).toEqual([])
95
+ })
96
+
97
+ it('deletes a settings file that held nothing but its hook', () => {
98
+ writeMemoryHooks(dir, ['claude-code'], '1.8.0')
99
+ stripMemoryHooks(dir)
100
+ expect(existsSync(join(dir, CLAUDE_SETTINGS))).toBe(false)
101
+ })
102
+ })