opencastle 1.9.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 +14 -13
@@ -3,7 +3,8 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync
3
3
  import { homedir } from 'node:os'
4
4
  import { basename, dirname, join, relative, resolve } from 'node:path'
5
5
  import { checkSkill } from './agent-plugin.js'
6
- import { LESSONS_DIR, newLessonId, readLessons, renderLesson, syncLessons, today, type Lesson } from './lessons.js'
6
+ import { LESSONS_DIR, newLessonId, readLessons, renderLesson, today, type Lesson } from './lessons.js'
7
+ import { refreshLessons } from './lessons-rules.js'
7
8
  import { readMemoryDir, readRepositoryMemory, type MemorySource } from './memory-sources.js'
8
9
  import { scanForSecrets } from './secret-scan.js'
9
10
  import { getOrchestratorRoot } from './copy.js'
@@ -56,6 +57,8 @@ const HELP = `
56
57
  --from <dir> memory: read memory files from this directory instead
57
58
  --force skill: replace a team skill with the same name
58
59
  --dry-run Say what would be written, and write nothing
60
+ --json memory: one line of JSON and exit 0, as the assistants'
61
+ memory hooks run it
59
62
  --help, -h Show this help
60
63
  `
61
64
 
@@ -217,20 +220,29 @@ function promoteSkill(pkgRoot: string, args: string[], dryRun: boolean): void {
217
220
  export { claudeMemoryDir } from './memory-sources.js'
218
221
 
219
222
  function promoteMemory(args: string[], dryRun: boolean): void {
223
+ // --json is how the assistants' hooks run it: one line of JSON, no prose,
224
+ // and exit 0 whatever happens, because a hook's exit code means something to
225
+ // the assistant (on Stop, 2 tells the agent to keep going) and a session
226
+ // ending is no time to report a missing memory directory.
227
+ const json = args.includes('--json')
228
+ const stop = (message: string): void => {
229
+ if (!json) fail(message)
230
+ console.log(JSON.stringify({ shared: [], left: [], note: message }))
231
+ }
220
232
  const projectRoot = projectRootFrom(process.cwd())
221
233
  const customizations = join(projectRoot, '.opencastle')
222
- if (!existsSync(customizations)) fail('no .opencastle/ here — run npx opencastle init first')
234
+ if (!existsSync(customizations)) return stop('no .opencastle/ here — run npx opencastle init first')
223
235
  const from = flag(args, '--from')
224
236
  let sources: MemorySource[]
225
237
  if (from) {
226
238
  const dir = resolve(process.cwd(), from.replace(/^~(?=\/|$)/, home()))
227
- if (!existsSync(dir)) fail(`no memory at ${tilde(dir)}`)
239
+ if (!existsSync(dir)) return stop(`no memory at ${tilde(dir)}`)
228
240
  sources = [readMemoryDir(dir, 'Memory')]
229
241
  } else {
230
242
  const found = readRepositoryMemory(projectRoot)
231
243
  sources = found.sources
232
244
  if (sources.length === 0) {
233
- fail(
245
+ return stop(
234
246
  `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
247
  'each assistant writes it once it has saved one for this repository; --from <dir> reads another. ' +
236
248
  'Cursor keeps its memories on its servers and Copilot Memory lives on GitHub, so neither can be read here.',
@@ -238,13 +250,15 @@ function promoteMemory(args: string[], dryRun: boolean): void {
238
250
  }
239
251
  }
240
252
 
241
- syncLessons(customizations)
253
+ refreshLessons(customizations)
242
254
  const { lessons } = readLessons(customizations)
243
255
  const promoted = new Set(lessons.map((l) => l.source).filter((s): s is string => Boolean(s)))
244
256
  const taken = new Set(lessons.map((l) => l.id))
245
257
  const written: string[] = []
258
+ const shared: Array<{ assistant: string; lesson: string }> = []
259
+ const left: Array<{ assistant: string; memory: string; why: string }> = []
246
260
 
247
- console.log(`\n 🏰 ${c.bold('Promote memory')}`)
261
+ if (!json) console.log(`\n 🏰 ${c.bold('Promote memory')}`)
248
262
  for (const source of sources) {
249
263
  const wrote: string[] = []
250
264
  const skipped = [...source.skipped]
@@ -274,17 +288,24 @@ function promoteMemory(args: string[], dryRun: boolean): void {
274
288
  }
275
289
  }
276
290
  written.push(...wrote)
291
+ shared.push(...wrote.map((w) => ({ assistant: source.assistant, lesson: `.opencastle/${w}` })))
292
+ left.push(...skipped.filter(([, why]) => why !== 'already a lesson').map(([memory, why]) => ({ assistant: source.assistant, memory, why })))
293
+ if (json) continue
277
294
  console.log(`\n ${c.bold(source.assistant)} ${c.dim(`from ${tilde(source.where)}`)}`)
278
295
  for (const w of wrote) console.log(` ${c.green(dryRun ? '+' : '✓')} ${dryRun ? 'Would write' : 'Wrote'} .opencastle/${w}`)
279
296
  for (const [file, why] of skipped) console.log(` ${c.dim(`- ${file}: ${why}`)}`)
280
297
  }
281
- if (!dryRun && written.length > 0) syncLessons(customizations)
298
+ if (!dryRun && written.length > 0) refreshLessons(customizations)
282
299
 
300
+ if (json) {
301
+ console.log(JSON.stringify({ shared, left }))
302
+ return
303
+ }
283
304
  if (written.length === 0) console.log(`\n ${c.dim('Nothing new to promote.')}\n`)
284
305
  else if (!dryRun) {
285
306
  console.log(
286
- `\n ${c.dim('Each is category general, severity medium: set them, add --cite where a lesson is about code,')}` +
287
- `\n ${c.dim('and delete any that are yours alone. The pull request that commits them is where the team agrees.')}\n`,
307
+ `\n ${c.dim('Each is category general, severity medium: set them, and add --cite where a lesson is about code.')}` +
308
+ `\n ${c.dim('The pull request that commits them is where the team agrees.')}\n`,
288
309
  )
289
310
  } else {
290
311
  console.log('')
@@ -299,7 +320,12 @@ export default async function promote({ pkgRoot, args }: CliContext): Promise<vo
299
320
  return
300
321
  }
301
322
  const dryRun = rest.includes('--dry-run')
302
- if (sub === 'skill') promoteSkill(pkgRoot, rest, dryRun)
303
- else promoteMemory(rest, dryRun)
323
+ if (sub === 'skill') return promoteSkill(pkgRoot, rest, dryRun)
324
+ if (!rest.includes('--json')) return promoteMemory(rest, dryRun)
325
+ try {
326
+ promoteMemory(rest, dryRun)
327
+ } catch (err) {
328
+ console.log(JSON.stringify({ shared: [], left: [], note: (err as Error).message }))
329
+ }
304
330
  }
305
331
 
package/src/cli/remove.ts CHANGED
@@ -5,6 +5,8 @@ import { readManifest } from './manifest.js'
5
5
  import { removeDirIfExists } from './copy.js'
6
6
  import { removeGitignoreBlock, predictGitignoreStrip, LOCAL_DIRS } from './gitignore.js'
7
7
  import { confirm, select, closePrompts, c } from './prompt.js'
8
+ import { memoryHookPaths, stripMemoryHooks } from './memory-hooks.js'
9
+ import { LESSON_RULES } from './lessons-rules.js'
8
10
  import { stripManagedBlockFromFile, predictStripFile } from './managed-block.js'
9
11
  import { resolveManagedPaths, ownerOf, removeOwnedFiles } from './managed-paths.js'
10
12
  import { stripManagedMcpServers, getMcpConfigRelPath, willKeepSomethingAfterStrip, retireLegacyMcpConfig, LEGACY_MCP_CONFIGS } from './mcp.js'
@@ -248,9 +250,14 @@ export default async function remove({ args }: CliContext): Promise<void> {
248
250
 
249
251
  console.log(`\n 🏰 ${c.bold('OpenCastle remove')}\n`)
250
252
 
253
+ // The memory hook runs OpenCastle, which this is the step before uninstalling,
254
+ // so it goes in both modes; the lessons rules are text, and stay with the files.
255
+ const hookPaths = memoryHookPaths(projectRoot)
256
+ const lessonRulePaths = Object.values(LESSON_RULES).map((r) => r.path).filter((p) => existsSync(resolve(projectRoot, p)))
251
257
  if (mode === 'keep-files') {
252
258
  console.log(' Will remove:')
253
259
  console.log(` ${c.dim('.opencastle/manifest.json')}`)
260
+ for (const p of hookPaths) console.log(` ${c.dim(`the memory hook in ${p}`)}`)
254
261
  console.log('\n Every generated file stays exactly where it is.')
255
262
  console.log(` Afterwards: ${c.bold('npm uninstall opencastle')}\n`)
256
263
  } else {
@@ -267,6 +274,8 @@ export default async function remove({ args }: CliContext): Promise<void> {
267
274
  ` ${c.yellow('→')} ${c.dim('.opencastle/')} ${c.yellow(`moved to ${relative(projectRoot, parkedDirFor(projectRoot))}/ — your conventions and lessons`)}`,
268
275
  )
269
276
  if (hasLegacy) console.log(` ${c.red('-')} ${c.dim('.opencastle.json')}`)
277
+ for (const p of hookPaths) console.log(` ${c.red('-')} ${c.dim(`the memory hook in ${p}`)}`)
278
+ for (const p of lessonRulePaths) console.log(` ${c.red('-')} ${c.dim(p)}`)
270
279
 
271
280
  // Co-owned files are only *sometimes* kept: one holding nothing but our
272
281
  // block is deleted. Announcing "your own writing stays" over a file about to
@@ -329,6 +338,7 @@ export default async function remove({ args }: CliContext): Promise<void> {
329
338
  // `readManifest`, so dropping only the new path left the project still
330
339
  // reporting as installed under a heading that said otherwise.
331
340
  if (hasLegacy) await unlink(legacyManifestPath).catch(() => {})
341
+ stripMemoryHooks(projectRoot)
332
342
  console.log(`\n ${c.green('✓')} Files are now standalone.`)
333
343
  console.log(` You can uninstall: ${c.bold('npm uninstall opencastle')}\n`)
334
344
  closePrompts()
@@ -400,6 +410,18 @@ export default async function remove({ args }: CliContext): Promise<void> {
400
410
  }
401
411
  }
402
412
 
413
+ for (const p of stripMemoryHooks(projectRoot)) {
414
+ if (existsSync(resolve(projectRoot, p))) stripped++
415
+ else removed++
416
+ parents.add(dirname(resolve(projectRoot, p)))
417
+ }
418
+ for (const p of lessonRulePaths) {
419
+ if (!existsSync(resolve(projectRoot, p))) continue
420
+ await unlink(resolve(projectRoot, p))
421
+ removed++
422
+ parents.add(dirname(resolve(projectRoot, p)))
423
+ }
424
+
403
425
  // The containers our own directories lived in. `.claude/agents/`, `skills/`
404
426
  // and `commands/` were each removed by name and `.claude/` itself was left
405
427
  // behind — an empty directory the user has to notice and delete, after a
package/src/cli/status.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { join, resolve } from 'node:path'
1
+ import { 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,8 +21,7 @@ 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, what to run next,
25
- and how many of your assistant's memories the team has not got yet.
24
+ Show what is installed, whether generated files are current, and what to run next.
26
25
 
27
26
  Options:
28
27
  --json Machine-readable output
@@ -54,8 +53,6 @@ export interface StatusReport {
54
53
  nextReason?: string
55
54
  /** The baselines the committed lock records, as `name version`. */
56
55
  baselines?: string[]
57
- /** Memories this machine's assistants keep about the repository that no lesson holds yet. */
58
- unsharedMemories?: Array<{ assistant: string; count: number }>
59
56
  }
60
57
 
61
58
  /** Newest mtime under a directory tree, or 0 when absent. */
@@ -337,23 +334,10 @@ export async function buildStatusReport(pkgRoot: string, projectRoot: string): P
337
334
  baselines = []
338
335
  }
339
336
 
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
-
352
337
  return {
353
338
  installed: true,
354
339
  missingRequired,
355
340
  ...(baselines.length > 0 && { baselines }),
356
- ...(unsharedMemories.length > 0 && { unsharedMemories }),
357
341
  version: manifest.version,
358
342
  ides: adapters.map((a) => a.ide),
359
343
  targets,
@@ -418,16 +402,6 @@ function render(report: StatusReport): void {
418
402
  console.log(` ${c.dim('Not compiled:')} ${report.unmanaged.join(', ')}`)
419
403
  }
420
404
 
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
406
  console.log('')
433
407
  if (report.nextCommand) {
@@ -7,6 +7,8 @@ import { detectRepoInfo, mergeStackIntoRepoInfo } from './detect.js'
7
7
  import { getMcpConfigRelPath, expectedTeamEntries, containerKeyFor } from './mcp.js'
8
8
  import { parseMcpConfigText } from './mcp-file.js'
9
9
  import { lessonsIndexDrift, LESSONS_INDEX } from './lessons.js'
10
+ import { isLessonRule, lessonRulesDrift } from './lessons-rules.js'
11
+ import { memoryHooksDrift } from './memory-hooks.js'
10
12
  import { resolveStack, getIncludedMcpServers } from './stack-config.js'
11
13
  import { auditMcpConfig, describeFindingUnder, remedyFor, isFailure, type TeamAuditContext } from './mcp-audit.js'
12
14
  import { resolveSources, materialize, hasErrors, cliVersionOf, type CompileSource } from './layers.js'
@@ -63,7 +65,7 @@ export interface Drift {
63
65
  * parse, a baseline that is not installed, a policy the sources break. The
64
66
  * comparison cannot run until it is fixed, and `sync` refuses to compile.
65
67
  */
66
- origin?: 'mcp' | 'team' | 'version'
68
+ origin?: 'mcp' | 'team' | 'version' | 'memory'
67
69
  /** The classifier's own words, so the checker and `doctor` cannot diverge. */
68
70
  detail?: string
69
71
  /** What resolves it, per entry — these do not share a remedy. */
@@ -215,6 +217,9 @@ function comparePath(
215
217
  // A file the target shares the directory with someone over — their own
216
218
  // prompt beside ours in `.github/prompts/` — is not drift.
217
219
  if (owns && !owns(shown)) continue
220
+ // The lessons rule sits among compiled rules but is derived from the
221
+ // lessons, and checked against them below.
222
+ if (isLessonRule(shown)) continue
218
223
  drift.push({ ide, path: shown, kind: 'extra' })
219
224
  }
220
225
  return checked
@@ -661,6 +666,19 @@ async function compareProject(
661
666
  if (why) drift.push({ ide: 'all', path: `.opencastle/${LESSONS_INDEX}`, kind: 'outdated', detail: why, fix: 'npx opencastle sync' })
662
667
  }
663
668
 
669
+ // The team's memory: the lessons rule each assistant loads, derived from the
670
+ // lessons like the index, and the hook that shares what agents remember.
671
+ for (const d of lessonRulesDrift(projectRoot, ides)) {
672
+ drift.push({ ide: d.ide, path: d.path, kind: 'outdated', detail: d.detail, fix: 'npx opencastle sync', origin: 'memory' })
673
+ }
674
+ for (const d of memoryHooksDrift(projectRoot, ides, cliVersionOf(pkgRoot))) {
675
+ drift.push(
676
+ d.unreadable
677
+ ? { ide: d.ide, path: d.path, kind: 'unreducible', detail: d.detail, fix: 'fix the JSON, then run npx opencastle sync; this one needs a person', origin: 'memory' }
678
+ : { ide: d.ide, path: d.path, kind: 'outdated', detail: d.detail, fix: 'npx opencastle sync', origin: 'memory' },
679
+ )
680
+ }
681
+
664
682
  // A manifest that parses but names no target this release knows is not a
665
683
  // clean project — `sync` exits 1 on it. Reporting "0 generated files match
666
684
  // their sources across 0 targets" is an assertion that cannot fail, and it
@@ -723,11 +741,14 @@ function render(report: CheckReport): void {
723
741
  // `.opencastle/lessons/` and stale until `sync` runs. It was filed under "MCP
724
742
  // servers sync would change", which it has nothing to do with.
725
743
  const lessonsIndex = `.opencastle/${LESSONS_INDEX}`
744
+ // The lessons each assistant loads follow the index; the memory hook is
745
+ // neither a source nor an MCP server, and says so.
726
746
  const lockDrift = [
727
747
  ...[...changed, ...missing].filter((d) => d.path === LOCK_REL),
728
- ...outdated.filter((d) => d.path === lessonsIndex),
748
+ ...outdated.filter((d) => d.path === lessonsIndex || isLessonRule(d.path)),
729
749
  ]
730
- const outdatedMcp = outdated.filter((d) => d.path !== lessonsIndex)
750
+ const hookDrift = outdated.filter((d) => d.origin === 'memory' && !isLessonRule(d.path))
751
+ const outdatedMcp = outdated.filter((d) => d.path !== lessonsIndex && d.origin !== 'memory')
731
752
  const changedFiles = changed.filter((d) => d.path !== LOCK_REL)
732
753
  const missingFiles = missing.filter((d) => d.path !== LOCK_REL)
733
754
  if (lockDrift.length > 0) {
@@ -751,6 +772,12 @@ function render(report: CheckReport): void {
751
772
  console.log('')
752
773
  }
753
774
 
775
+ if (hookDrift.length > 0) {
776
+ console.log(` ${c.bold('The memory hook')} ${c.dim('(it shares what agents remember about the project when a session ends)')}`)
777
+ for (const d of hookDrift) console.log(` ${c.yellow('~')} ${d.path} ${c.dim(`(${d.detail})`)}`)
778
+ console.log('')
779
+ }
780
+
754
781
  if (outdatedMcp.length > 0) {
755
782
  console.log(
756
783
  ` ${c.bold('MCP servers sync would change')} ${c.dim('(integration defaults move forward, team servers are written as defined; entries you added or edited stay yours)')}`,
package/src/cli/update.ts CHANGED
@@ -32,6 +32,8 @@ import { buildLock, writeLock, readLock, LOCK_REL, priorTeam } from './lock.js'
32
32
  import { parseVersion, compareVersions } from './version-range.js'
33
33
  import { COMMAND_NAMESPACE } from './command-namespace.js'
34
34
  import { parseMcpConfigText } from './mcp-file.js'
35
+ import { writeLessonRules } from './lessons-rules.js'
36
+ import { memoryHooksDrift } from './memory-hooks.js'
35
37
  import { syncLessons, LESSONS_DIR, LESSONS_INDEX } from './lessons.js'
36
38
 
37
39
  /** The config that replaced a legacy one, for the sentence that reports it. */
@@ -558,6 +560,7 @@ export default async function update({
558
560
  }
559
561
 
560
562
  // ── Update each IDE ─────────────────────────────────────────────
563
+ const hooksBefore = memoryHooksDrift(projectRoot, ides, pkg.version)
561
564
  // Generated config that exists but will not parse. Filled from two places —
562
565
  // the adapters' own scaffold step and the rebuild pass below — and reported
563
566
  // once at the end, because the user needs the filename either way.
@@ -722,6 +725,13 @@ export default async function update({
722
725
  // but compiled all the same, and `sync --check` holds it to its sources.
723
726
  const lessons = syncLessons(resolve(projectRoot, '.opencastle'))
724
727
 
728
+ // ── The team's memory ───────────────────────────────────────────
729
+ // Each target's compile wrote the lessons it loads and its memory hook;
730
+ // what changed is the difference from before the targets ran. The lessons
731
+ // rules follow the index just rebuilt above.
732
+ writeLessonRules(projectRoot, ides)
733
+ const hooksAfter = memoryHooksDrift(projectRoot, ides, pkg.version)
734
+
725
735
  // ── Update manifest ─────────────────────────────────────────────
726
736
  const before = manifestMeaning(manifest as unknown as Record<string, unknown>)
727
737
  manifest.version = pkg.version
@@ -784,6 +794,13 @@ export default async function update({
784
794
  if (lessons.index === 'updated' && lessons.migrated === 0 && !lessons.backup) {
785
795
  console.log(` ${c.green('✓')} Updated .opencastle/${LESSONS_INDEX} from .opencastle/${LESSONS_DIR}/`)
786
796
  }
797
+ for (const before of hooksBefore) {
798
+ if (hooksAfter.some((a) => a.path === before.path)) continue
799
+ console.log(` ${c.green('✓')} ${before.detail.includes('missing') || before.detail.startsWith('has no') ? 'Added' : 'Updated'} the memory hook in ${before.path}`)
800
+ }
801
+ for (const after of hooksAfter.filter((a) => a.unreadable)) {
802
+ console.log(` ${c.yellow('!')} ${after.path} is not valid JSON, so the memory hook was not added — fix it and run sync again`)
803
+ }
787
804
  for (const problem of lessons.problems) {
788
805
  console.log(` ${c.yellow('!')} Left .opencastle/${problem.split(' ')[0]} out of the lessons index — ${problem.slice(problem.indexOf(' ') + 1)}`)
789
806
  }
@@ -15,6 +15,6 @@ The project's own instructions win: the Project Context loaded with these, the r
15
15
  - **Fail visibly** — surface errors; never swallow an exception.
16
16
  - **Comments say why**, not what.
17
17
  - **Git.** Never push to `main`: every change goes through a branch and a pull request (**git-workflow**).
18
- - **Memory: the team's or the user's.** Read `.opencastle/LESSONS-LEARNED.md` before you start, and open the lessons that match your task. What you confirm that is true for anyone working in this repository, record as a lesson the moment you confirm it: a fix after a failure, a convention or decision the code does not show, a tool's or service's quirk, a correction the user gives about the code (**self-improvement**). What is about the user (their preferences, role, habits, machine) stays in your own memory. Never both.
18
+ - **Memory: the team's or the user's.** The team's lessons load with these instructions (if they did not, read `.opencastle/LESSONS-LEARNED.md`); open the ones that touch your task. Save what you learn in your own memory, as you normally do: in Claude Code and VS Code, OpenCastle shares what is about the project with the team when the session ends, and leaves what is about the user. So save what is about the user (their preferences, role, habits, machine) as about the user. In any other assistant, record what you confirm about the project as a lesson (**self-improvement**).
19
19
 
20
20
  <!-- End of Coding Standards -->
@@ -36,4 +36,4 @@ Implement the change the user gave with this command — a feature, a roadmap it
36
36
 
37
37
  - Commit on a feature branch and open a pull request; never push to `main` (**git-workflow**). Link the tracker issue when there is one.
38
38
  - Report what changed (files), how you verified it, what is still open, and anything you noticed outside the task, with its file and line.
39
- - Something you confirmed that is true for anyone working here, such as a fix after a failure or a convention the code does not show: record it as a lesson (**self-improvement**).
39
+ - Something you confirmed that is true for anyone working here, such as a fix after a failure or a convention the code does not show: save it as about the project (**self-improvement**).
@@ -1,27 +1,28 @@
1
1
  ---
2
2
  name: self-improvement
3
- description: "Keeps the team's memory: decides whether what you learned belongs to the team or to the user, records the team's as lessons in .opencastle/lessons/ with npx opencastle lesson, and re-verifies and graduates them. Use when you confirm something true for anyone working in the repository (a fix after a failure, a convention, a decision, a quirk, a correction about the code), before work past lessons may cover, when doctor reports a lesson's cited code changed, or when the lessons index grows long."
3
+ description: "Keeps the team's memory: where what you learned goes (your memory, shared with the team when it is about the project, or a lesson in .opencastle/lessons/), and how lessons are cited, re-verified and graduated. Use when you confirm something true for anyone working in the repository (a fix after a failure, a convention, a decision, a quirk, a correction about the code), when you touch a lesson copied from memory, when doctor reports a lesson's cited code changed, or when the lessons index grows long."
4
4
  ---
5
5
 
6
6
  # Self-Improvement
7
7
 
8
- Lessons are the team's memory. A lesson is a file in `.opencastle/lessons/`, committed with the change you made, so the team reviews it in that pull request; `.opencastle/LESSONS-LEARNED.md` is the index every agent reads first, rewritten from those files by every sync — never edit it by hand.
8
+ Lessons are the team's memory. A lesson is a file in `.opencastle/lessons/`, committed with the change you made, so the team reviews it in that pull request. `.opencastle/LESSONS-LEARNED.md` is the index, and Claude Code, VS Code, Cursor and Windsurf load a copy of it before every task; both are rewritten from the lesson files — never edit them by hand.
9
9
 
10
10
  ## The team's or the user's
11
11
 
12
- Decide when you learn it, not later. Nobody sorts memories afterwards.
12
+ Decide when you learn it, by how you save it. Nobody sorts memories afterwards.
13
13
 
14
- | It is about | Where it goes | For example |
15
- |-------------|---------------|-------------|
16
- | The project: true for anyone working in this repository | A lesson, as soon as you have confirmed it | `pnpm build` fails without `CI=1` set; every migration ships with a down file; the staging API allows 10 requests a second; the user says "we never use default exports" |
17
- | The user: true for them, wherever they work | Your own memory, never a lesson | They want short answers; they use fish; their role; their editor; paths on their machine |
18
- | Every repository in the organisation | A lesson here, whose problem says it holds in every repository; it graduates into the baseline's skill (below) | The company's deploy pipeline needs a manual approval; an internal service's API contract |
19
- | This task only | Nowhere | A one-off workaround; a guess you have not confirmed |
14
+ In Claude Code and VS Code, save it in your own memory as you normally do. When the session ends, OpenCastle copies what is about the project into a lesson, and leaves what is about the user. In any other assistant, record what is about the project as a lesson yourself (below).
20
15
 
21
- - Confirmed means the fix worked, the code shows it, or the user said so. A suspicion is not a lesson.
22
- - A correction from the user: about the code or the project, a lesson; about how they want you to work with them, your memory.
23
- - One place only. Never save the same thing as a lesson and in your own memory.
24
- - When unsure whether a teammate's agent would need it, ask: would it have saved them time on this repository? Yes: a lesson.
16
+ | It is about | Save it as | For example |
17
+ |-------------|------------|-------------|
18
+ | The project: true for anyone working in this repository | About the project (a correction, a project note, a pointer to where something lives) | `pnpm build` fails without `CI=1` set; every migration ships with a down file; the staging API allows 10 requests a second; the user says "we never use default exports" |
19
+ | The user: true for them, wherever they work | About the user. It stays theirs and never becomes a lesson | They want short answers; they use fish; their role; their editor; paths on their machine |
20
+ | Every repository in the organisation | About the project, saying it holds in every repository; it graduates into the baseline's skill (below) | The company's deploy pipeline needs a manual approval; an internal service's API contract |
21
+ | This task only | Nothing | A one-off workaround; a guess you have not confirmed |
22
+
23
+ - Confirmed means the fix worked, the code shows it, or the user said so. A suspicion is not worth saving.
24
+ - A correction from the user: about the code or the project, it is about the project; about how they want you to work with them, it is about the user.
25
+ - A lesson copied from memory is category `general`, severity `medium`, and cites nothing. When your task touches one, set them in its file, and cite the code with `npx opencastle lesson verify <id> --cite <path>`.
25
26
 
26
27
  ## Record a lesson
27
28