opencastle 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/cli.mjs +1 -1
  2. package/dist/cli/adapters/claude-code.d.ts +7 -2
  3. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  4. package/dist/cli/adapters/claude-code.js +13 -2
  5. package/dist/cli/adapters/claude-code.js.map +1 -1
  6. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  7. package/dist/cli/adapters/rules-dir-base.js +12 -2
  8. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  9. package/dist/cli/adapters/rules-dir-base.test.js +3 -1
  10. package/dist/cli/adapters/rules-dir-base.test.js.map +1 -1
  11. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  12. package/dist/cli/adapters/vscode.js +12 -2
  13. package/dist/cli/adapters/vscode.js.map +1 -1
  14. package/dist/cli/ci.d.ts +8 -0
  15. package/dist/cli/ci.d.ts.map +1 -1
  16. package/dist/cli/ci.js +24 -17
  17. package/dist/cli/ci.js.map +1 -1
  18. package/dist/cli/convoy/findings.js +3 -2
  19. package/dist/cli/convoy/findings.js.map +1 -1
  20. package/dist/cli/init.d.ts.map +1 -1
  21. package/dist/cli/init.js +9 -0
  22. package/dist/cli/init.js.map +1 -1
  23. package/dist/cli/lesson.js +3 -2
  24. package/dist/cli/lesson.js.map +1 -1
  25. package/dist/cli/lessons-rules.d.ts +45 -0
  26. package/dist/cli/lessons-rules.d.ts.map +1 -0
  27. package/dist/cli/lessons-rules.js +130 -0
  28. package/dist/cli/lessons-rules.js.map +1 -0
  29. package/dist/cli/lessons-rules.test.d.ts +2 -0
  30. package/dist/cli/lessons-rules.test.d.ts.map +1 -0
  31. package/dist/cli/lessons-rules.test.js +65 -0
  32. package/dist/cli/lessons-rules.test.js.map +1 -0
  33. package/dist/cli/memory-hooks.d.ts +51 -0
  34. package/dist/cli/memory-hooks.d.ts.map +1 -0
  35. package/dist/cli/memory-hooks.js +200 -0
  36. package/dist/cli/memory-hooks.js.map +1 -0
  37. package/dist/cli/memory-hooks.test.d.ts +2 -0
  38. package/dist/cli/memory-hooks.test.d.ts.map +1 -0
  39. package/dist/cli/memory-hooks.test.js +83 -0
  40. package/dist/cli/memory-hooks.test.js.map +1 -0
  41. package/dist/cli/memory-sources.d.ts.map +1 -1
  42. package/dist/cli/memory-sources.js +3 -2
  43. package/dist/cli/memory-sources.js.map +1 -1
  44. package/dist/cli/promote-command.test.js +40 -10
  45. package/dist/cli/promote-command.test.js.map +1 -1
  46. package/dist/cli/promote.d.ts.map +1 -1
  47. package/dist/cli/promote.js +41 -11
  48. package/dist/cli/promote.js.map +1 -1
  49. package/dist/cli/remove.d.ts.map +1 -1
  50. package/dist/cli/remove.js +27 -0
  51. package/dist/cli/remove.js.map +1 -1
  52. package/dist/cli/status.d.ts +0 -5
  53. package/dist/cli/status.d.ts.map +1 -1
  54. package/dist/cli/status.js +2 -24
  55. package/dist/cli/status.js.map +1 -1
  56. package/dist/cli/sync-check.d.ts +1 -1
  57. package/dist/cli/sync-check.d.ts.map +1 -1
  58. package/dist/cli/sync-check.js +27 -2
  59. package/dist/cli/sync-check.js.map +1 -1
  60. package/dist/cli/update.d.ts.map +1 -1
  61. package/dist/cli/update.js +17 -0
  62. package/dist/cli/update.js.map +1 -1
  63. package/package.json +1 -1
  64. package/src/cli/adapters/claude-code.ts +15 -2
  65. package/src/cli/adapters/rules-dir-base.test.ts +3 -1
  66. package/src/cli/adapters/rules-dir-base.ts +11 -2
  67. package/src/cli/adapters/vscode.ts +11 -2
  68. package/src/cli/ci.ts +23 -16
  69. package/src/cli/convoy/findings.ts +2 -2
  70. package/src/cli/init.ts +10 -0
  71. package/src/cli/lesson.ts +2 -2
  72. package/src/cli/lessons-rules.test.ts +71 -0
  73. package/src/cli/lessons-rules.ts +128 -0
  74. package/src/cli/memory-hooks.test.ts +102 -0
  75. package/src/cli/memory-hooks.ts +207 -0
  76. package/src/cli/memory-sources.ts +3 -2
  77. package/src/cli/promote-command.test.ts +43 -10
  78. package/src/cli/promote.ts +37 -11
  79. package/src/cli/remove.ts +22 -0
  80. package/src/cli/status.ts +2 -28
  81. package/src/cli/sync-check.ts +30 -3
  82. package/src/cli/update.ts +17 -0
  83. package/src/orchestrator/instructions/general.instructions.md +1 -1
  84. package/src/orchestrator/prompts/implement-feature.prompt.md +1 -1
  85. package/src/orchestrator/skills/self-improvement/SKILL.md +20 -3
@@ -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
+ })
@@ -0,0 +1,207 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { opencastleRunner } from './ci.js'
4
+ import { cliVersionOf } from './layers.js'
5
+ import { writeLessonRules } from './lessons-rules.js'
6
+
7
+ /**
8
+ * The team's memory, shared by the assistant's own hook.
9
+ *
10
+ * Every earlier way to share what agents learn asked an agent, or a person, to
11
+ * do something extra: write a lesson when a retry worked, log a session, run a
12
+ * command later and pick memories. The record shows how that went — 25 lessons
13
+ * in 794 pull requests on the one project that used them, against 72 memories
14
+ * Claude Code wrote by itself on the same project, nearly all about the
15
+ * project and none about the person.
16
+ *
17
+ * So agents keep writing their own memory, which they already do reliably, and
18
+ * the assistant runs `promote memory` when an agent stops: Claude Code on
19
+ * SessionEnd, from the project's `.claude/settings.json`; VS Code on Stop,
20
+ * from `.github/hooks/opencastle.json`. It copies what is about the project
21
+ * into lessons and leaves what is about the person, and the lessons go into
22
+ * the pull request with the work, where the team reviews them.
23
+ *
24
+ * Both files are the project's, committed, so every teammate's assistant runs
25
+ * the hook once they trust the folder. The settings file is the user's too:
26
+ * only OpenCastle's own entry is ever added, replaced or removed.
27
+ */
28
+
29
+ export const CLAUDE_SETTINGS = '.claude/settings.json'
30
+ export const VSCODE_HOOK_FILE = '.github/hooks/opencastle.json'
31
+
32
+ /** Recognises OpenCastle's entry whatever runner or version it was written with. */
33
+ const OURS = /\bopencastle(?:@\S+)?\s+promote\s+memory\b/
34
+
35
+ /** The command the hook runs. `--json` keeps it quiet and always exits 0. */
36
+ export function memoryHookCommand(projectRoot: string, cliVersion: string): string {
37
+ return `${opencastleRunner(projectRoot, cliVersion)} promote memory --json`
38
+ }
39
+
40
+ type Json = Record<string, unknown>
41
+
42
+ function hookEntry(command: string): Json {
43
+ return { type: 'command', command, timeout: 30 }
44
+ }
45
+
46
+ function isOurs(entry: unknown): boolean {
47
+ return Boolean(entry && typeof entry === 'object' && typeof (entry as Json).command === 'string' && OURS.test((entry as Json).command as string))
48
+ }
49
+
50
+ /** Settings with OpenCastle's SessionEnd entry taken out, and nothing else changed. */
51
+ function withoutOurs(settings: Json): Json {
52
+ const hooks = settings.hooks && typeof settings.hooks === 'object' ? { ...(settings.hooks as Json) } : null
53
+ if (!hooks || !Array.isArray(hooks.SessionEnd)) return settings
54
+ const groups = (hooks.SessionEnd as unknown[])
55
+ .map((g) => {
56
+ if (!g || typeof g !== 'object' || !Array.isArray((g as Json).hooks)) return g
57
+ const kept = ((g as Json).hooks as unknown[]).filter((h) => !isOurs(h))
58
+ return kept.length === 0 ? null : { ...(g as Json), hooks: kept }
59
+ })
60
+ .filter((g) => g !== null)
61
+ if (groups.length > 0) hooks.SessionEnd = groups
62
+ else delete hooks.SessionEnd
63
+ const out = { ...settings }
64
+ if (Object.keys(hooks).length > 0) out.hooks = hooks
65
+ else delete out.hooks
66
+ return out
67
+ }
68
+
69
+ function readJson(abs: string): Json | null | 'unreadable' {
70
+ if (!existsSync(abs)) return null
71
+ try {
72
+ const value = JSON.parse(readFileSync(abs, 'utf8')) as unknown
73
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : 'unreadable'
74
+ } catch {
75
+ return 'unreadable'
76
+ }
77
+ }
78
+
79
+ function expectedClaudeSettings(current: Json | null, command: string): Json {
80
+ const base = withoutOurs(current ?? {})
81
+ const hooks = base.hooks && typeof base.hooks === 'object' ? { ...(base.hooks as Json) } : {}
82
+ const groups = Array.isArray(hooks.SessionEnd) ? [...(hooks.SessionEnd as unknown[])] : []
83
+ hooks.SessionEnd = [...groups, { hooks: [hookEntry(command)] }]
84
+ return { ...base, hooks }
85
+ }
86
+
87
+ function hasOurEntry(settings: Json, command: string): boolean {
88
+ const groups = (settings.hooks as Json | undefined)?.SessionEnd
89
+ if (!Array.isArray(groups)) return false
90
+ const want = JSON.stringify(hookEntry(command))
91
+ return groups.some((g) => Array.isArray((g as Json)?.hooks) && ((g as Json).hooks as unknown[]).some((h) => JSON.stringify(h) === want))
92
+ }
93
+
94
+ function vscodeHookText(command: string): string {
95
+ return `${JSON.stringify({ hooks: { Stop: [hookEntry(command)] } }, null, 2)}\n`
96
+ }
97
+
98
+ export interface HookWrite {
99
+ path: string
100
+ outcome: 'created' | 'updated' | 'unchanged' | 'unreadable'
101
+ }
102
+
103
+ /** Add or update OpenCastle's hook for each assistant that has one. */
104
+ export function writeMemoryHooks(projectRoot: string, ides: readonly string[], cliVersion: string): HookWrite[] {
105
+ const command = memoryHookCommand(projectRoot, cliVersion)
106
+ const out: HookWrite[] = []
107
+ if (ides.includes('claude-code')) {
108
+ const abs = join(projectRoot, CLAUDE_SETTINGS)
109
+ const current = readJson(abs)
110
+ if (current === 'unreadable') out.push({ path: CLAUDE_SETTINGS, outcome: 'unreadable' })
111
+ else if (current && hasOurEntry(current, command)) out.push({ path: CLAUDE_SETTINGS, outcome: 'unchanged' })
112
+ else {
113
+ mkdirSync(dirname(abs), { recursive: true })
114
+ writeFileSync(abs, `${JSON.stringify(expectedClaudeSettings(current, command), null, 2)}\n`)
115
+ out.push({ path: CLAUDE_SETTINGS, outcome: current ? 'updated' : 'created' })
116
+ }
117
+ }
118
+ if (ides.includes('vscode')) {
119
+ const abs = join(projectRoot, VSCODE_HOOK_FILE)
120
+ const text = vscodeHookText(command)
121
+ let current: string | null = null
122
+ try {
123
+ current = readFileSync(abs, 'utf8')
124
+ } catch {
125
+ current = null
126
+ }
127
+ if (current === text) out.push({ path: VSCODE_HOOK_FILE, outcome: 'unchanged' })
128
+ else {
129
+ mkdirSync(dirname(abs), { recursive: true })
130
+ writeFileSync(abs, text)
131
+ out.push({ path: VSCODE_HOOK_FILE, outcome: current === null ? 'created' : 'updated' })
132
+ }
133
+ }
134
+ return out
135
+ }
136
+
137
+ /** Hooks that are missing or no longer run the command this release writes. */
138
+ export function memoryHooksDrift(
139
+ projectRoot: string,
140
+ ides: readonly string[],
141
+ cliVersion: string,
142
+ ): Array<{ ide: string; path: string; detail: string; unreadable?: boolean }> {
143
+ const command = memoryHookCommand(projectRoot, cliVersion)
144
+ const out: Array<{ ide: string; path: string; detail: string; unreadable?: boolean }> = []
145
+ if (ides.includes('claude-code')) {
146
+ const current = readJson(join(projectRoot, CLAUDE_SETTINGS))
147
+ if (current === 'unreadable') {
148
+ out.push({ ide: 'claude-code', path: CLAUDE_SETTINGS, detail: 'is not valid JSON, so the memory hook cannot be checked', unreadable: true })
149
+ } else if (!current || !hasOurEntry(current, command)) {
150
+ out.push({ ide: 'claude-code', path: CLAUDE_SETTINGS, detail: `has no SessionEnd hook running ${command}` })
151
+ }
152
+ }
153
+ if (ides.includes('vscode')) {
154
+ let current: string | null = null
155
+ try {
156
+ current = readFileSync(join(projectRoot, VSCODE_HOOK_FILE), 'utf8')
157
+ } catch {
158
+ current = null
159
+ }
160
+ if (current !== vscodeHookText(command)) {
161
+ out.push({ ide: 'vscode', path: VSCODE_HOOK_FILE, detail: current === null ? 'the memory hook is missing' : `no longer runs ${command}` })
162
+ }
163
+ }
164
+ return out
165
+ }
166
+
167
+ /**
168
+ * What every compile of an assistant ends with, so a project is never
169
+ * compiled without it: the lessons it loads and, for Claude Code and VS Code,
170
+ * the hook that shares what its agents remember. Run by each adapter, so
171
+ * `init`, `sync` and anything else that compiles a target agree with
172
+ * `sync --check` by construction.
173
+ */
174
+ export function compileTeamMemory(pkgRoot: string, projectRoot: string, ide: string): HookWrite[] {
175
+ writeLessonRules(projectRoot, [ide])
176
+ return writeMemoryHooks(projectRoot, [ide], cliVersionOf(pkgRoot))
177
+ }
178
+
179
+ /** The files that hold an OpenCastle memory hook now. */
180
+ export function memoryHookPaths(projectRoot: string): string[] {
181
+ const out: string[] = []
182
+ const settings = readJson(join(projectRoot, CLAUDE_SETTINGS))
183
+ if (settings && settings !== 'unreadable' && JSON.stringify(withoutOurs(settings)) !== JSON.stringify(settings)) out.push(CLAUDE_SETTINGS)
184
+ if (existsSync(join(projectRoot, VSCODE_HOOK_FILE))) out.push(VSCODE_HOOK_FILE)
185
+ return out
186
+ }
187
+
188
+ /** Take OpenCastle's hooks out: its entry from the settings, and its own hook file. */
189
+ export function stripMemoryHooks(projectRoot: string): string[] {
190
+ const removed: string[] = []
191
+ const settingsPath = join(projectRoot, CLAUDE_SETTINGS)
192
+ const current = readJson(settingsPath)
193
+ if (current && current !== 'unreadable') {
194
+ const next = withoutOurs(current)
195
+ if (JSON.stringify(next) !== JSON.stringify(current)) {
196
+ if (Object.keys(next).length === 0) rmSync(settingsPath)
197
+ else writeFileSync(settingsPath, `${JSON.stringify(next, null, 2)}\n`)
198
+ removed.push(CLAUDE_SETTINGS)
199
+ }
200
+ }
201
+ const hookFile = join(projectRoot, VSCODE_HOOK_FILE)
202
+ if (existsSync(hookFile)) {
203
+ rmSync(hookFile)
204
+ removed.push(VSCODE_HOOK_FILE)
205
+ }
206
+ return removed
207
+ }
@@ -208,8 +208,9 @@ function readMemoryFiles(dir: string): MemoryFile[] {
208
208
  function fromMemoryFiles(dir: string, prefix: string, skipped: Array<[string, string]>): MemoryCandidate[] {
209
209
  const out: MemoryCandidate[] = []
210
210
  for (const memory of readMemoryFiles(dir)) {
211
- // Corrections and project notes are the team's; the rest are about one person.
212
- if (memory.type && !['feedback', 'project'].includes(memory.type)) {
211
+ // Corrections, project notes and pointers to where things live are the
212
+ // team's; a `user` memory is about one person, and stays theirs.
213
+ if (memory.type && !['feedback', 'project', 'reference'].includes(memory.type)) {
213
214
  skipped.push([memory.file, memory.type === 'user' ? 'about you, not the project' : `a ${memory.type} memory`])
214
215
  continue
215
216
  }
@@ -265,16 +265,49 @@ describe.skipIf(!built)('opencastle promote', () => {
265
265
  expect(text).toMatch(/source: "codex-memory:app test runs#[0-9a-f]{12}"/)
266
266
  })
267
267
 
268
- it('the status screen says how much this machine has not shared, until it is promoted', () => {
269
- write(memoryDir(), { 'a.md': memory('quote-paths', 'feedback', 'Quote paths with spaces.') })
270
- const before = run(project)
271
- expect(before.stdout).toContain('1 memory on this machine the team has not got yet (Claude Code 1)')
272
- expect(before.stdout).toContain('npx opencastle promote memory')
273
- expect(before.stdout).toContain('Everything is current')
274
- expect(JSON.parse(run(project, '--json').stdout).unsharedMemories).toEqual([{ assistant: 'Claude Code', count: 1 }])
275
- expect(run(project, 'promote', 'memory').status).toBe(0)
276
- const after = run(project)
277
- expect(after.stdout).not.toContain('the team has not got yet')
268
+ it('as the hook runs it: shares the project’s memory, keeps the user’s, refreshes what agents load, exits 0', () => {
269
+ write(memoryDir(), {
270
+ 'build.md': memory('build', 'project', 'Set CI=1 before pnpm build.'),
271
+ 'dashboards.md': memory('dashboards', 'reference', 'Errors are in the Sentry project acme-web.'),
272
+ 'terse.md': memory('terse', 'user', 'Keep answers short.'),
273
+ })
274
+ const out = spawnSync('node', [cli, 'promote', 'memory', '--json'], {
275
+ cwd: project,
276
+ encoding: 'utf8',
277
+ env: env(),
278
+ input: '{"hook_event_name":"SessionEnd","reason":"exit"}',
279
+ })
280
+ expect(out.status).toBe(0)
281
+ const report = JSON.parse(out.stdout) as { shared: Array<{ lesson: string }>; left: Array<{ memory: string; why: string }> }
282
+ expect(report.shared).toHaveLength(2)
283
+ expect(report.left).toEqual([{ assistant: 'Claude Code', memory: 'terse.md', why: 'about you, not the project' }])
284
+ const rule = readFileSync(join(project, '.claude', 'rules', 'opencastle-lessons.md'), 'utf8')
285
+ expect(rule).toContain('**Build**')
286
+ expect(rule).toContain('**Dashboards**')
287
+ expect(rule).not.toContain('Terse')
288
+ expect(run(project, 'sync', '--check').status).toBe(0)
289
+
290
+ const again = spawnSync('node', [cli, 'promote', 'memory', '--json'], { cwd: project, encoding: 'utf8', env: env(), input: '{}' })
291
+ expect(JSON.parse(again.stdout).shared).toEqual([])
292
+
293
+ const nowhere = spawnSync('node', [cli, 'promote', 'memory', '--json'], { cwd: root, encoding: 'utf8', env: env(), input: '{}' })
294
+ expect(nowhere.status).toBe(0)
295
+ expect(JSON.parse(nowhere.stdout).note).toContain('no .opencastle/ here')
296
+ })
297
+
298
+ it('init adds the memory hook beside the project’s own settings, and sync --check holds it', () => {
299
+ const settings = JSON.parse(readFileSync(join(project, '.claude', 'settings.json'), 'utf8')) as { hooks: { SessionEnd: Array<{ hooks: Array<{ command: string; timeout: number }> }> } }
300
+ const ours = settings.hooks.SessionEnd.flatMap((g) => g.hooks).find((h) => h.command.includes('promote memory --json'))
301
+ expect(ours?.timeout).toBe(30)
302
+ writeFileSync(join(project, '.claude', 'settings.json'), JSON.stringify({ permissions: { allow: ['Bash(npm test)'] } }))
303
+ const check = run(project, 'sync', '--check')
304
+ expect(check.status).toBe(1)
305
+ expect(check.stdout + check.stderr).toContain('.claude/settings.json')
306
+ expect(run(project, 'sync', '--yes').status).toBe(0)
307
+ const merged = JSON.parse(readFileSync(join(project, '.claude', 'settings.json'), 'utf8')) as { permissions: unknown; hooks: unknown }
308
+ expect(merged.permissions).toEqual({ allow: ['Bash(npm test)'] })
309
+ expect(JSON.stringify(merged.hooks)).toContain('promote memory --json')
310
+ expect(run(project, 'sync', '--check').status).toBe(0)
278
311
  })
279
312
  })
280
313
  })