opencastle 1.1.1 → 1.2.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 (221) hide show
  1. package/README.md +22 -5
  2. package/bin/cli.mjs +6 -0
  3. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  4. package/dist/cli/adapters/single-file-base.js +24 -2
  5. package/dist/cli/adapters/single-file-base.js.map +1 -1
  6. package/dist/cli/agent-plugin.d.ts +119 -0
  7. package/dist/cli/agent-plugin.d.ts.map +1 -0
  8. package/dist/cli/agent-plugin.js +449 -0
  9. package/dist/cli/agent-plugin.js.map +1 -0
  10. package/dist/cli/agent-plugin.test.d.ts +2 -0
  11. package/dist/cli/agent-plugin.test.d.ts.map +1 -0
  12. package/dist/cli/agent-plugin.test.js +227 -0
  13. package/dist/cli/agent-plugin.test.js.map +1 -0
  14. package/dist/cli/baseline.d.ts.map +1 -1
  15. package/dist/cli/baseline.js +99 -26
  16. package/dist/cli/baseline.js.map +1 -1
  17. package/dist/cli/convoy/gates.d.ts +2 -20
  18. package/dist/cli/convoy/gates.d.ts.map +1 -1
  19. package/dist/cli/convoy/gates.js +3 -111
  20. package/dist/cli/convoy/gates.js.map +1 -1
  21. package/dist/cli/copy.d.ts +0 -8
  22. package/dist/cli/copy.d.ts.map +1 -1
  23. package/dist/cli/copy.js +0 -21
  24. package/dist/cli/copy.js.map +1 -1
  25. package/dist/cli/dispatcher.test.js +2 -2
  26. package/dist/cli/dispatcher.test.js.map +1 -1
  27. package/dist/cli/docs-accuracy.test.js +2 -0
  28. package/dist/cli/docs-accuracy.test.js.map +1 -1
  29. package/dist/cli/doctor.d.ts.map +1 -1
  30. package/dist/cli/doctor.js +2 -0
  31. package/dist/cli/doctor.js.map +1 -1
  32. package/dist/cli/init.test.js +36 -24
  33. package/dist/cli/init.test.js.map +1 -1
  34. package/dist/cli/layers.d.ts +8 -0
  35. package/dist/cli/layers.d.ts.map +1 -1
  36. package/dist/cli/layers.js +130 -13
  37. package/dist/cli/layers.js.map +1 -1
  38. package/dist/cli/layers.test.js +2 -2
  39. package/dist/cli/layers.test.js.map +1 -1
  40. package/dist/cli/legacy-install.test.js +8 -1
  41. package/dist/cli/legacy-install.test.js.map +1 -1
  42. package/dist/cli/lesson-command.test.d.ts +2 -0
  43. package/dist/cli/lesson-command.test.d.ts.map +1 -0
  44. package/dist/cli/lesson-command.test.js +100 -0
  45. package/dist/cli/lesson-command.test.js.map +1 -0
  46. package/dist/cli/lesson.d.ts +0 -9
  47. package/dist/cli/lesson.d.ts.map +1 -1
  48. package/dist/cli/lesson.js +212 -276
  49. package/dist/cli/lesson.js.map +1 -1
  50. package/dist/cli/lessons.d.ts +134 -0
  51. package/dist/cli/lessons.d.ts.map +1 -0
  52. package/dist/cli/lessons.js +493 -0
  53. package/dist/cli/lessons.js.map +1 -0
  54. package/dist/cli/lessons.test.d.ts +2 -0
  55. package/dist/cli/lessons.test.d.ts.map +1 -0
  56. package/dist/cli/lessons.test.js +214 -0
  57. package/dist/cli/lessons.test.js.map +1 -0
  58. package/dist/cli/pack-plugins.d.ts +8 -0
  59. package/dist/cli/pack-plugins.d.ts.map +1 -0
  60. package/dist/cli/pack-plugins.js +70 -0
  61. package/dist/cli/pack-plugins.js.map +1 -0
  62. package/dist/cli/plugin-command.test.d.ts +2 -0
  63. package/dist/cli/plugin-command.test.d.ts.map +1 -0
  64. package/dist/cli/plugin-command.test.js +114 -0
  65. package/dist/cli/plugin-command.test.js.map +1 -0
  66. package/dist/cli/plugin.d.ts +30 -0
  67. package/dist/cli/plugin.d.ts.map +1 -0
  68. package/dist/cli/plugin.js +291 -0
  69. package/dist/cli/plugin.js.map +1 -0
  70. package/dist/cli/promote-command.test.d.ts +2 -0
  71. package/dist/cli/promote-command.test.d.ts.map +1 -0
  72. package/dist/cli/promote-command.test.js +151 -0
  73. package/dist/cli/promote-command.test.js.map +1 -0
  74. package/dist/cli/promote.d.ts +12 -0
  75. package/dist/cli/promote.d.ts.map +1 -0
  76. package/dist/cli/promote.js +364 -0
  77. package/dist/cli/promote.js.map +1 -0
  78. package/dist/cli/secret-scan.d.ts +21 -0
  79. package/dist/cli/secret-scan.d.ts.map +1 -0
  80. package/dist/cli/secret-scan.js +114 -0
  81. package/dist/cli/secret-scan.js.map +1 -0
  82. package/dist/cli/sync-check.d.ts.map +1 -1
  83. package/dist/cli/sync-check.js +9 -0
  84. package/dist/cli/sync-check.js.map +1 -1
  85. package/dist/cli/team-commands.test.js +2 -2
  86. package/dist/cli/team-commands.test.js.map +1 -1
  87. package/dist/cli/update.d.ts.map +1 -1
  88. package/dist/cli/update.js +18 -0
  89. package/dist/cli/update.js.map +1 -1
  90. package/dist/orchestrator/plugins/agent-plugins.test.d.ts +2 -0
  91. package/dist/orchestrator/plugins/agent-plugins.test.d.ts.map +1 -0
  92. package/dist/orchestrator/plugins/agent-plugins.test.js +32 -0
  93. package/dist/orchestrator/plugins/agent-plugins.test.js.map +1 -0
  94. package/package.json +2 -1
  95. package/src/cli/adapters/single-file-base.ts +23 -2
  96. package/src/cli/agent-plugin.test.ts +267 -0
  97. package/src/cli/agent-plugin.ts +469 -0
  98. package/src/cli/baseline.ts +99 -26
  99. package/src/cli/convoy/gates.ts +9 -142
  100. package/src/cli/copy.ts +0 -25
  101. package/src/cli/dispatcher.test.ts +2 -2
  102. package/src/cli/docs-accuracy.test.ts +2 -0
  103. package/src/cli/doctor.ts +2 -0
  104. package/src/cli/fixtures/lessons-template-1.0.md +70 -0
  105. package/src/cli/init.test.ts +37 -24
  106. package/src/cli/layers.test.ts +2 -2
  107. package/src/cli/layers.ts +144 -14
  108. package/src/cli/legacy-install.test.ts +11 -1
  109. package/src/cli/lesson-command.test.ts +117 -0
  110. package/src/cli/lesson.ts +215 -266
  111. package/src/cli/lessons.test.ts +254 -0
  112. package/src/cli/lessons.ts +540 -0
  113. package/src/cli/pack-plugins.ts +70 -0
  114. package/src/cli/plugin-command.test.ts +125 -0
  115. package/src/cli/plugin.ts +309 -0
  116. package/src/cli/promote-command.test.ts +170 -0
  117. package/src/cli/promote.ts +371 -0
  118. package/src/cli/secret-scan.ts +154 -0
  119. package/src/cli/sync-check.ts +9 -0
  120. package/src/cli/team-commands.test.ts +2 -2
  121. package/src/cli/update.ts +20 -0
  122. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  123. package/src/orchestrator/agents/researcher.agent.md +1 -1
  124. package/src/orchestrator/customizations/LESSONS-LEARNED.md +10 -66
  125. package/src/orchestrator/customizations/README.md +2 -1
  126. package/src/orchestrator/customizations/logs/README.md +1 -1
  127. package/src/orchestrator/plugins/agent-plugins.test.ts +34 -0
  128. package/src/orchestrator/plugins/astro/mcp.json +9 -0
  129. package/src/orchestrator/plugins/astro/plugin.json +21 -0
  130. package/src/orchestrator/plugins/chrome-devtools/mcp.json +13 -0
  131. package/src/orchestrator/plugins/chrome-devtools/plugin.json +21 -0
  132. package/src/orchestrator/plugins/cloudflare/mcp.json +9 -0
  133. package/src/orchestrator/plugins/cloudflare/plugin.json +21 -0
  134. package/src/orchestrator/plugins/contentful/mcp.json +13 -0
  135. package/src/orchestrator/plugins/contentful/plugin.json +21 -0
  136. package/src/orchestrator/plugins/convex/mcp.json +15 -0
  137. package/src/orchestrator/plugins/convex/plugin.json +21 -0
  138. package/src/orchestrator/plugins/coolify/mcp.json +13 -0
  139. package/src/orchestrator/plugins/coolify/plugin.json +25 -0
  140. package/src/orchestrator/plugins/cypress/plugin.json +21 -0
  141. package/src/orchestrator/plugins/drizzle/plugin.json +21 -0
  142. package/src/orchestrator/plugins/expo/mcp.json +9 -0
  143. package/src/orchestrator/plugins/expo/plugin.json +21 -0
  144. package/src/orchestrator/plugins/figma/mcp.json +9 -0
  145. package/src/orchestrator/plugins/figma/plugin.json +21 -0
  146. package/src/orchestrator/plugins/hetzner/plugin.json +24 -0
  147. package/src/orchestrator/plugins/jira/mcp.json +9 -0
  148. package/src/orchestrator/plugins/jira/plugin.json +21 -0
  149. package/src/orchestrator/plugins/linear/mcp.json +9 -0
  150. package/src/orchestrator/plugins/linear/plugin.json +21 -0
  151. package/src/orchestrator/plugins/netlify/mcp.json +13 -0
  152. package/src/orchestrator/plugins/netlify/plugin.json +21 -0
  153. package/src/orchestrator/plugins/nextjs/mcp.json +13 -0
  154. package/src/orchestrator/plugins/nextjs/plugin.json +21 -0
  155. package/src/orchestrator/plugins/notion/mcp.json +9 -0
  156. package/src/orchestrator/plugins/notion/plugin.json +21 -0
  157. package/src/orchestrator/plugins/nx/mcp.json +14 -0
  158. package/src/orchestrator/plugins/nx/plugin.json +21 -0
  159. package/src/orchestrator/plugins/playwright/mcp.json +13 -0
  160. package/src/orchestrator/plugins/playwright/plugin.json +21 -0
  161. package/src/orchestrator/plugins/prisma/mcp.json +14 -0
  162. package/src/orchestrator/plugins/prisma/plugin.json +21 -0
  163. package/src/orchestrator/plugins/resend/mcp.json +13 -0
  164. package/src/orchestrator/plugins/resend/plugin.json +24 -0
  165. package/src/orchestrator/plugins/sanity/mcp.json +9 -0
  166. package/src/orchestrator/plugins/sanity/plugin.json +21 -0
  167. package/src/orchestrator/plugins/sentry/mcp.json +12 -0
  168. package/src/orchestrator/plugins/sentry/plugin.json +24 -0
  169. package/src/orchestrator/plugins/slack/mcp.json +13 -0
  170. package/src/orchestrator/plugins/slack/plugin.json +24 -0
  171. package/src/orchestrator/plugins/strapi/mcp.json +13 -0
  172. package/src/orchestrator/plugins/strapi/plugin.json +21 -0
  173. package/src/orchestrator/plugins/stripe/mcp.json +9 -0
  174. package/src/orchestrator/plugins/stripe/plugin.json +21 -0
  175. package/src/orchestrator/plugins/supabase/mcp.json +9 -0
  176. package/src/orchestrator/plugins/supabase/plugin.json +21 -0
  177. package/src/orchestrator/plugins/teams/plugin.json +24 -0
  178. package/src/orchestrator/plugins/trello/mcp.json +13 -0
  179. package/src/orchestrator/plugins/trello/plugin.json +25 -0
  180. package/src/orchestrator/plugins/turborepo/plugin.json +21 -0
  181. package/src/orchestrator/plugins/vercel/mcp.json +9 -0
  182. package/src/orchestrator/plugins/vercel/plugin.json +21 -0
  183. package/src/orchestrator/plugins/vitest/plugin.json +21 -0
  184. package/src/orchestrator/skill-config-links.test.ts +2 -1
  185. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +1 -1
  186. package/src/orchestrator/skills/agent-hooks/SKILL.md +1 -1
  187. package/src/orchestrator/skills/decomposition/SKILL.md +1 -1
  188. package/src/orchestrator/skills/memory-merger/SKILL.md +17 -21
  189. package/src/orchestrator/skills/self-improvement/LESSON-CATEGORIES.md +44 -23
  190. package/src/orchestrator/skills/self-improvement/SKILL.md +30 -15
  191. /package/src/orchestrator/plugins/astro/{SKILL.md → skills/astro-framework/SKILL.md} +0 -0
  192. /package/src/orchestrator/plugins/chrome-devtools/{SKILL.md → skills/browser-testing/SKILL.md} +0 -0
  193. /package/src/orchestrator/plugins/cloudflare/{SKILL.md → skills/cloudflare-platform/SKILL.md} +0 -0
  194. /package/src/orchestrator/plugins/contentful/{SKILL.md → skills/contentful-cms/SKILL.md} +0 -0
  195. /package/src/orchestrator/plugins/convex/{SKILL.md → skills/convex-database/SKILL.md} +0 -0
  196. /package/src/orchestrator/plugins/coolify/{SKILL.md → skills/coolify-deployment/SKILL.md} +0 -0
  197. /package/src/orchestrator/plugins/cypress/{SKILL.md → skills/cypress-testing/SKILL.md} +0 -0
  198. /package/src/orchestrator/plugins/drizzle/{SKILL.md → skills/drizzle-orm/SKILL.md} +0 -0
  199. /package/src/orchestrator/plugins/expo/{SKILL.md → skills/expo-development/SKILL.md} +0 -0
  200. /package/src/orchestrator/plugins/figma/{SKILL.md → skills/figma-design/SKILL.md} +0 -0
  201. /package/src/orchestrator/plugins/hetzner/{SKILL.md → skills/hetzner-cloud/SKILL.md} +0 -0
  202. /package/src/orchestrator/plugins/jira/{SKILL.md → skills/jira-management/SKILL.md} +0 -0
  203. /package/src/orchestrator/plugins/linear/{SKILL.md → skills/linear-task-management/SKILL.md} +0 -0
  204. /package/src/orchestrator/plugins/netlify/{SKILL.md → skills/netlify-deployment/SKILL.md} +0 -0
  205. /package/src/orchestrator/plugins/nextjs/{SKILL.md → skills/nextjs-framework/SKILL.md} +0 -0
  206. /package/src/orchestrator/plugins/notion/{SKILL.md → skills/notion-knowledge-management/SKILL.md} +0 -0
  207. /package/src/orchestrator/plugins/nx/{SKILL.md → skills/nx-workspace/SKILL.md} +0 -0
  208. /package/src/orchestrator/plugins/playwright/{SKILL.md → skills/playwright-testing/SKILL.md} +0 -0
  209. /package/src/orchestrator/plugins/prisma/{SKILL.md → skills/prisma-database/SKILL.md} +0 -0
  210. /package/src/orchestrator/plugins/resend/{SKILL.md → skills/resend-email/SKILL.md} +0 -0
  211. /package/src/orchestrator/plugins/sanity/{SKILL.md → skills/sanity-cms/SKILL.md} +0 -0
  212. /package/src/orchestrator/plugins/sentry/{SKILL.md → skills/sentry-monitoring/SKILL.md} +0 -0
  213. /package/src/orchestrator/plugins/slack/{SKILL.md → skills/slack-notifications/SKILL.md} +0 -0
  214. /package/src/orchestrator/plugins/strapi/{SKILL.md → skills/strapi-cms/SKILL.md} +0 -0
  215. /package/src/orchestrator/plugins/stripe/{SKILL.md → skills/stripe-payments/SKILL.md} +0 -0
  216. /package/src/orchestrator/plugins/supabase/{SKILL.md → skills/supabase-database/SKILL.md} +0 -0
  217. /package/src/orchestrator/plugins/teams/{SKILL.md → skills/teams-notifications/SKILL.md} +0 -0
  218. /package/src/orchestrator/plugins/trello/{SKILL.md → skills/trello-task-management/SKILL.md} +0 -0
  219. /package/src/orchestrator/plugins/turborepo/{SKILL.md → skills/turborepo-monorepo/SKILL.md} +0 -0
  220. /package/src/orchestrator/plugins/vercel/{SKILL.md → skills/vercel-deployment/SKILL.md} +0 -0
  221. /package/src/orchestrator/plugins/vitest/{SKILL.md → skills/vitest-testing/SKILL.md} +0 -0
package/src/cli/lesson.ts CHANGED
@@ -1,71 +1,74 @@
1
- import { readFile, writeFile, stat } from 'node:fs/promises'
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
-
5
- const CATEGORIES = [
6
- 'task-management',
7
- 'jira',
8
- 'mcp-tools',
9
- 'codebase-tool',
10
- 'terminal',
11
- 'framework',
12
- 'cms',
13
- 'database',
14
- 'git',
15
- 'deployment',
16
- 'browser-testing',
17
- 'general',
18
- ] as const
19
-
20
- type Category = (typeof CATEGORIES)[number]
21
-
22
- const SEVERITIES = ['high', 'medium', 'low'] as const
23
- type Severity = (typeof SEVERITIES)[number]
4
+ import { scanForSecrets } from './secret-scan.js'
5
+ import {
6
+ LESSON_CATEGORIES,
7
+ LESSON_SEVERITIES,
8
+ LESSONS_DIR,
9
+ LESSONS_INDEX,
10
+ citationProblem,
11
+ findLesson,
12
+ fingerprintsOf,
13
+ isLessonCategory,
14
+ isLessonSeverity,
15
+ lessonBody,
16
+ newLessonId,
17
+ readLessons,
18
+ renderLesson,
19
+ syncLessons,
20
+ today,
21
+ type Lesson,
22
+ } from './lessons.js'
24
23
 
25
24
  const HELP = `
26
- opencastle lesson [options]
27
-
28
- Append a structured lesson to .opencastle/LESSONS-LEARNED.md
29
-
30
- Required flags:
25
+ opencastle lesson [add] --title <text> --category <cat> --severity <level> --problem <text> [options]
26
+ opencastle lesson verify <id> [--cite <path[:line]>]...
27
+ opencastle lesson archive <id> --into <file>
28
+
29
+ Record what an agent learned the hard way, as a file in .opencastle/lessons/,
30
+ and rewrite the index agents read before they start (.opencastle/${LESSONS_INDEX}).
31
+
32
+ add (the default) Write a new lesson. --title, --category, --severity and
33
+ --problem are required.
34
+ verify <id> Say a lesson still holds: stamps today's date and what
35
+ the cited files hold now, so doctor stops reporting them
36
+ as changed. --cite replaces its citations.
37
+ archive <id> Mark a lesson merged into a skill or instruction file,
38
+ named with --into. It stays on record and leaves the
39
+ list agents read.
40
+
41
+ Options:
31
42
  --title <text> Short descriptive title
32
- --category <cat> One of: ${CATEGORIES.join(', ')}
33
- --severity <level> One of: high, medium, low
43
+ --category <cat> One of: ${LESSON_CATEGORIES.join(', ')}
44
+ --severity <level> One of: ${LESSON_SEVERITIES.join(', ')}
34
45
  --problem <text> What went wrong
35
-
36
- Optional flags:
37
- --wrong <text> The wrong approach that was tried
38
- --correct <text> The correct approach that works
39
- --why <text> Root cause explanation
40
- --customizations-dir <p> Override the customizations directory path
41
- --dry-run Preview what would be appended without writing
46
+ --wrong <text> The approach that was tried and failed
47
+ --correct <text> The approach that works
48
+ --why <text> Root cause
49
+ --cite <path[:line]> Code the lesson is about, relative to the project
50
+ root; repeat for more than one. doctor reports a
51
+ lesson whose cited code changes after it was verified
52
+ --into <file> archive: where the lesson now lives
53
+ --customizations-dir <p> Use this .opencastle directory instead of finding one
54
+ --dry-run Print what would be written, and write nothing
42
55
  --help, -h Show this help
43
56
 
44
57
  Examples:
45
- opencastle lesson \\
46
- --title "Never call foo without bar" \\
47
- --category general \\
48
- --severity high \\
49
- --problem "foo throws on Node 18 without bar"
50
-
51
58
  opencastle lesson \\
52
59
  --title "Always quote shell variables" \\
53
60
  --category terminal \\
54
61
  --severity medium \\
55
62
  --problem "Unquoted variables break on paths with spaces" \\
56
- --wrong 'rm -rf \$DIR/old' \\
57
- --correct 'rm -rf "\$DIR/old"' \\
58
- --why "Word splitting expands spaces into separate arguments"
59
- `
60
-
61
- function isCategory(s: string): s is Category {
62
- return (CATEGORIES as ReadonlyArray<string>).includes(s)
63
- }
63
+ --wrong 'rm -rf \\$DIR/old' \\
64
+ --correct 'rm -rf "\\$DIR/old"' \\
65
+ --cite scripts/clean.sh:12
64
66
 
65
- function isSeverity(s: string): s is Severity {
66
- return (SEVERITIES as ReadonlyArray<string>).includes(s)
67
- }
67
+ opencastle lesson verify 2026-10-02-always-quote-shell-variables
68
+ opencastle lesson archive LES-004 --into .opencastle/skills/git-workflow/SKILL.md
69
+ `
68
70
 
71
+ /** The `.opencastle/` this lesson belongs to: the override, or the nearest one up from here. */
69
72
  async function resolveCustomizationsDir(override: string | null): Promise<string> {
70
73
  if (override) return override
71
74
  let dir = process.cwd()
@@ -83,246 +86,192 @@ async function resolveCustomizationsDir(override: string | null): Promise<string
83
86
  return join(process.cwd(), '.opencastle')
84
87
  }
85
88
 
86
- function nextLessonId(content: string): string {
87
- const matches = [...content.matchAll(/^### LES-(\d+)/gm)]
88
- if (matches.length === 0) return 'LES-001'
89
- const last = Math.max(...matches.map((m) => parseInt(m[1], 10)))
90
- return `LES-${String(last + 1).padStart(3, '0')}`
91
- }
92
-
93
- function escapeMarkdown(s: string): string {
94
- return s.replace(/\|/g, '\\|').replace(/[\n\r]/g, ' ')
95
- }
96
-
97
- function formatLesson(opts: {
98
- id: string
99
- title: string
100
- category: Category
101
- severity: Severity
102
- date: string
103
- problem: string
104
- wrong?: string
105
- correct?: string
106
- why?: string
107
- }): string {
108
- const title = opts.title.replace(/[\n\r]/g, ' ')
109
- const lines: string[] = [
110
- `### ${opts.id}: ${title}`,
111
- '',
112
- '| Field | Value |',
113
- '|-------|-------|',
114
- `| **Category** | \`${opts.category}\` |`,
115
- `| **Added** | ${opts.date} |`,
116
- `| **Severity** | \`${opts.severity}\` |`,
117
- '',
118
- `**Problem:** ${escapeMarkdown(opts.problem)}`,
119
- ]
120
- if (opts.wrong !== undefined) lines.push('', `**Wrong approach:** ${escapeMarkdown(opts.wrong)}`)
121
- if (opts.correct !== undefined) lines.push('', `**Correct approach:** ${escapeMarkdown(opts.correct)}`)
122
- if (opts.why !== undefined) lines.push('', `**Why:** ${escapeMarkdown(opts.why)}`)
123
- return lines.join('\n')
89
+ function fail(message: string): never {
90
+ console.error(` \u2717 ${message}`)
91
+ process.exit(1)
124
92
  }
125
93
 
126
- function insertLesson(content: string, block: string): string {
127
- const marker = '\n## Index by Category'
128
- const idx = content.indexOf(marker)
129
- if (idx === -1) {
130
- return content.trimEnd() + '\n\n' + block + '\n'
131
- }
132
- // Insert block right before the \n## Index sequence
133
- return content.slice(0, idx) + '\n' + block + '\n' + content.slice(idx)
94
+ interface Parsed {
95
+ positional: string[]
96
+ values: Map<string, string>
97
+ cites: string[]
98
+ dryRun: boolean
134
99
  }
135
100
 
136
- function updateIndex(content: string, category: string, lessonId: string): string {
137
- const lines = content.split('\n')
138
- let found = false
139
-
140
- for (let i = 0; i < lines.length; i++) {
141
- const m = lines[i].match(/^\| `([^`]+)` \| (.+) \|$/)
142
- if (m && m[1] === category) {
143
- const current = m[2].trim()
144
- const updated = current === '\u2014' ? lessonId : `${current}, ${lessonId}`
145
- lines[i] = `| \`${category}\` | ${updated} |`
146
- found = true
147
- break
148
- }
149
- }
150
-
151
- if (!found) {
152
- // Row doesn't exist — append after the last table row in the Index section
153
- const indexHeading = lines.findIndex((l) => l.trim() === '## Index by Category')
154
- if (indexHeading !== -1) {
155
- let lastTableRow = -1
156
- for (let i = indexHeading; i < lines.length; i++) {
157
- if (lines[i].startsWith('|')) lastTableRow = i
158
- else if (lastTableRow > indexHeading && lines[i].trim() !== '') break
159
- }
160
- if (lastTableRow !== -1) {
161
- lines.splice(lastTableRow + 1, 0, `| \`${category}\` | ${lessonId} |`)
162
- }
101
+ const VALUE_FLAGS = new Set([
102
+ '--title',
103
+ '--category',
104
+ '--severity',
105
+ '--problem',
106
+ '--wrong',
107
+ '--correct',
108
+ '--why',
109
+ '--into',
110
+ '--customizations-dir',
111
+ ])
112
+
113
+ function parse(args: string[]): Parsed {
114
+ const out: Parsed = { positional: [], values: new Map(), cites: [], dryRun: false }
115
+ for (let i = 0; i < args.length; i++) {
116
+ const a = args[i]
117
+ if (a === '--dry-run' || a === '--dryRun') {
118
+ out.dryRun = true
119
+ } else if (a === '--cite' || VALUE_FLAGS.has(a)) {
120
+ if (i + 1 >= args.length) fail(`${a} requires a value`)
121
+ const value = args[++i]
122
+ if (!value.trim()) fail(`${a} cannot be empty`)
123
+ if (a === '--cite') out.cites.push(value.trim())
124
+ else out.values.set(a, value)
125
+ } else if (a.startsWith('-')) {
126
+ fail(`unknown option ${a} — run "opencastle lesson --help"`)
127
+ } else {
128
+ out.positional.push(a)
163
129
  }
164
130
  }
165
-
166
- return lines.join('\n')
167
- }
168
-
169
- export interface LessonInput {
170
- title: string
171
- category: string
172
- severity: string
173
- problem: string
174
- wrong?: string
175
- correct?: string
176
- why?: string
131
+ return out
177
132
  }
178
133
 
179
134
  /**
180
- * Append a structured lesson to LESSONS-LEARNED.md programmatically.
181
- * Returns the generated lesson ID (e.g., "LES-005").
135
+ * A credential written into a lesson is committed with it. Refused, naming the
136
+ * line, the way a convoy refuses one in its own output.
182
137
  */
183
- async function appendLesson(
184
- input: LessonInput,
185
- customizationsDir?: string | null,
186
- ): Promise<string> {
187
- if (!isCategory(input.category)) {
188
- throw new Error(`Invalid category "${input.category}". Must be one of: ${CATEGORIES.join(', ')}`)
189
- }
190
- if (!isSeverity(input.severity)) {
191
- throw new Error(`Invalid severity "${input.severity}". Must be one of: ${SEVERITIES.join(', ')}`)
192
- }
193
- const category = input.category
194
- const severity = input.severity
195
-
196
- const resolvedDir = await resolveCustomizationsDir(customizationsDir ?? null)
197
- const lessonsFile = join(resolvedDir, 'LESSONS-LEARNED.md')
138
+ function refuseSecrets(text: string, where: string): void {
139
+ const scan = scanForSecrets(text, where)
140
+ if (scan.clean) return
141
+ const first = scan.findings[0]
142
+ fail(`${where} would hold what looks like a ${first.pattern} (line ${first.line}) — a lesson is committed, so describe the credential instead of pasting it`)
143
+ }
198
144
 
199
- let content: string
200
- try {
201
- content = await readFile(lessonsFile, 'utf8')
202
- } catch {
203
- throw new Error(`LESSONS-LEARNED.md not found at: ${lessonsFile}`)
145
+ function checkCitations(projectRoot: string, cites: string[]): void {
146
+ for (const cite of cites) {
147
+ const problem = citationProblem(projectRoot, cite)
148
+ if (problem) fail(`--cite: ${problem}`)
204
149
  }
205
-
206
- const id = nextLessonId(content)
207
- const date = new Date().toISOString().slice(0, 10)
208
-
209
- const block = formatLesson({
210
- id,
211
- title: input.title,
212
- category,
213
- severity,
214
- date,
215
- problem: input.problem,
216
- wrong: input.wrong,
217
- correct: input.correct,
218
- why: input.why,
219
- })
220
-
221
- let updated = insertLesson(content, block)
222
- updated = updateIndex(updated, category, id)
223
-
224
- await writeFile(lessonsFile, updated, 'utf8')
225
- return id
226
150
  }
227
151
 
228
- export default async function lesson({ args }: CliContext): Promise<void> {
229
- if (args.includes('--help') || args.includes('-h')) {
230
- console.log(HELP)
152
+ async function writeLessonFile(dir: string, lesson: Omit<Lesson, 'file'>, file: string, dryRun: boolean): Promise<void> {
153
+ const text = renderLesson(lesson)
154
+ const rel = `${LESSONS_DIR}/${file}`
155
+ refuseSecrets(text, rel)
156
+ if (dryRun) {
157
+ console.log(` [dry-run] Would write .opencastle/${rel}:\n`)
158
+ console.log(text)
231
159
  return
232
160
  }
161
+ await mkdir(join(dir, LESSONS_DIR), { recursive: true })
162
+ await writeFile(join(dir, LESSONS_DIR, file), text)
163
+ }
233
164
 
234
- const dryRun = args.includes('--dry-run') || args.includes('--dryRun')
235
- let title: string | null = null
236
- let category: string | null = null
237
- let severity: string | null = null
238
- let problem: string | null = null
239
- let wrong: string | undefined
240
- let correct: string | undefined
241
- let why: string | undefined
242
- let customizationsDir: string | null = null
243
-
244
- for (let i = 0; i < args.length; i++) {
245
- const a = args[i]
246
- switch (a) {
247
- case '--title':
248
- if (i + 1 >= args.length) { console.error(' \u2717 --title requires a value'); process.exit(1) }
249
- title = args[++i]
250
- if (!title.trim()) { console.error(' \u2717 --title cannot be empty'); process.exit(1) }
251
- break
252
- case '--category':
253
- if (i + 1 >= args.length) { console.error(' \u2717 --category requires a value'); process.exit(1) }
254
- category = args[++i]
255
- if (!category.trim()) { console.error(' \u2717 --category cannot be empty'); process.exit(1) }
256
- break
257
- case '--severity':
258
- if (i + 1 >= args.length) { console.error(' \u2717 --severity requires a value'); process.exit(1) }
259
- severity = args[++i]
260
- if (!severity.trim()) { console.error(' \u2717 --severity cannot be empty'); process.exit(1) }
261
- break
262
- case '--problem':
263
- if (i + 1 >= args.length) { console.error(' \u2717 --problem requires a value'); process.exit(1) }
264
- problem = args[++i]
265
- if (!problem.trim()) { console.error(' \u2717 --problem cannot be empty'); process.exit(1) }
266
- break
267
- case '--wrong':
268
- if (i + 1 >= args.length) { console.error(' \u2717 --wrong requires a value'); process.exit(1) }
269
- wrong = args[++i]
270
- if (!wrong.trim()) { console.error(' \u2717 --wrong cannot be empty'); process.exit(1) }
271
- break
272
- case '--correct':
273
- if (i + 1 >= args.length) { console.error(' \u2717 --correct requires a value'); process.exit(1) }
274
- correct = args[++i]
275
- if (!correct.trim()) { console.error(' \u2717 --correct cannot be empty'); process.exit(1) }
276
- break
277
- case '--why':
278
- if (i + 1 >= args.length) { console.error(' \u2717 --why requires a value'); process.exit(1) }
279
- why = args[++i]
280
- if (!why.trim()) { console.error(' \u2717 --why cannot be empty'); process.exit(1) }
281
- break
282
- case '--customizations-dir':
283
- if (i + 1 >= args.length) { console.error(' \u2717 --customizations-dir requires a path'); process.exit(1) }
284
- customizationsDir = args[++i]
285
- if (!customizationsDir.trim()) { console.error(' \u2717 --customizations-dir cannot be empty'); process.exit(1) }
286
- break
287
- }
165
+ /** Rewrite the index, after moving anything still in the old single file. */
166
+ function reindex(dir: string): void {
167
+ const outcome = syncLessons(dir)
168
+ if (outcome.migrated > 0) {
169
+ console.log(
170
+ ` Moved ${outcome.migrated} lesson(s) from ${LESSONS_INDEX} into .opencastle/${LESSONS_DIR}/` +
171
+ (outcome.backup ? ` (the old file is kept as ${outcome.backup})` : ''),
172
+ )
288
173
  }
174
+ }
289
175
 
290
- const missing: string[] = []
291
- if (!title) missing.push('--title')
292
- if (!category) missing.push('--category')
293
- if (!severity) missing.push('--severity')
294
- if (!problem) missing.push('--problem')
295
-
296
- if (missing.length > 0) {
297
- console.error(` \u2717 Missing required flags: ${missing.join(', ')}`)
298
- console.error(' Run "opencastle lesson --help" for usage.')
299
- process.exit(1)
176
+ async function add(dir: string, projectRoot: string, p: Parsed): Promise<void> {
177
+ const title = p.values.get('--title')
178
+ const category = p.values.get('--category')
179
+ const severity = p.values.get('--severity')
180
+ const problem = p.values.get('--problem')
181
+ const missing = [
182
+ !title && '--title',
183
+ !category && '--category',
184
+ !severity && '--severity',
185
+ !problem && '--problem',
186
+ ].filter(Boolean)
187
+ if (missing.length > 0) fail(`Missing required flags: ${missing.join(', ')}\n Run "opencastle lesson --help" for usage.`)
188
+ if (!isLessonCategory(category!)) fail(`Invalid --category "${category}". Must be one of: ${LESSON_CATEGORIES.join(', ')}`)
189
+ if (!isLessonSeverity(severity!)) fail(`Invalid --severity "${severity}". Must be one of: ${LESSON_SEVERITIES.join(', ')}`)
190
+ checkCitations(projectRoot, p.cites)
191
+
192
+ // Lessons still in the old file keep their numbers, so they are counted
193
+ // among the taken ids before this one is named.
194
+ if (!p.dryRun) reindex(dir)
195
+ const { lessons } = readLessons(dir)
196
+ const date = today()
197
+ const id = newLessonId(title!, date, new Set(lessons.map((l) => l.id)))
198
+ const lesson: Omit<Lesson, 'file'> = {
199
+ id,
200
+ title: title!.replace(/[\r\n]+/g, ' ').trim(),
201
+ category: category!,
202
+ severity: severity!,
203
+ added: date,
204
+ citations: p.cites,
205
+ ...(p.cites.length > 0 && { verified: date, fingerprints: fingerprintsOf(projectRoot, p.cites) }),
206
+ status: 'active',
207
+ body: lessonBody({
208
+ problem: problem!,
209
+ wrong: p.values.get('--wrong'),
210
+ correct: p.values.get('--correct'),
211
+ why: p.values.get('--why'),
212
+ }),
300
213
  }
214
+ await writeLessonFile(dir, lesson, `${id}.md`, p.dryRun)
215
+ if (p.dryRun) return
216
+ reindex(dir)
217
+ console.log(`${id}: ${lesson.title}`)
218
+ }
301
219
 
302
- if (!isCategory(category!)) {
303
- console.error(` \u2717 Invalid --category "${category}". Must be one of: ${CATEGORIES.join(', ')}`)
304
- process.exit(1)
220
+ async function verify(dir: string, projectRoot: string, p: Parsed): Promise<void> {
221
+ const [ref] = p.positional
222
+ if (!ref) fail('verify needs the id of a lesson, e.g. opencastle lesson verify LES-004')
223
+ checkCitations(projectRoot, p.cites)
224
+ if (!p.dryRun) reindex(dir)
225
+ const { lessons } = readLessons(dir)
226
+ const lesson = findLesson(lessons, ref)
227
+ if (!lesson) fail(`no lesson ${ref} in .opencastle/${LESSONS_DIR}/`)
228
+ const citations = p.cites.length > 0 ? p.cites : lesson.citations
229
+ for (const cite of citations) {
230
+ const problem = citationProblem(projectRoot, cite)
231
+ if (problem) fail(`${lesson.id} cites ${cite}: ${problem} — pass --cite with where it is now`)
305
232
  }
233
+ const updated: Lesson = { ...lesson, citations, verified: today(), fingerprints: fingerprintsOf(projectRoot, citations) }
234
+ await writeLessonFile(dir, updated, lesson.file, p.dryRun)
235
+ if (p.dryRun) return
236
+ reindex(dir)
237
+ console.log(`${lesson.id}: verified ${updated.verified}`)
238
+ }
306
239
 
307
- if (!isSeverity(severity!)) {
308
- console.error(` \u2717 Invalid --severity "${severity}". Must be one of: ${SEVERITIES.join(', ')}`)
309
- process.exit(1)
310
- }
240
+ async function archive(dir: string, projectRoot: string, p: Parsed): Promise<void> {
241
+ const [ref] = p.positional
242
+ const into = p.values.get('--into')
243
+ if (!ref) fail('archive needs the id of a lesson, e.g. opencastle lesson archive LES-004 --into <file>')
244
+ if (!into) fail('archive needs --into <file>: the skill or instruction file the lesson was merged into')
245
+ const problem = citationProblem(projectRoot, into)
246
+ if (problem) fail(`--into: ${problem}`)
247
+ if (!p.dryRun) reindex(dir)
248
+ const { lessons } = readLessons(dir)
249
+ const lesson = findLesson(lessons, ref)
250
+ if (!lesson) fail(`no lesson ${ref} in .opencastle/${LESSONS_DIR}/`)
251
+ await writeLessonFile(dir, { ...lesson, status: 'archived', mergedInto: into.replace(/^\.\//, '') }, lesson.file, p.dryRun)
252
+ if (p.dryRun) return
253
+ reindex(dir)
254
+ console.log(`${lesson.id}: archived, merged into ${into}`)
255
+ }
311
256
 
312
- if (dryRun) {
313
- console.log(` [dry-run] Would append lesson to LESSONS-LEARNED.md:`)
314
- console.log(` Title: ${title}`)
257
+ export default async function lesson({ args }: CliContext): Promise<void> {
258
+ if (args.includes('--help') || args.includes('-h')) {
259
+ console.log(HELP)
315
260
  return
316
261
  }
317
-
262
+ const sub = args[0] === 'add' || args[0] === 'verify' || args[0] === 'archive' ? args[0] : 'add'
263
+ const p = parse(args[0] === sub ? args.slice(1) : args)
264
+ const dir = await resolveCustomizationsDir(p.values.get('--customizations-dir') ?? null)
265
+ const projectRoot = dirname(dir)
318
266
  try {
319
- const id = await appendLesson(
320
- { title: title!, category: category!, severity: severity!, problem: problem!, wrong, correct, why },
321
- customizationsDir,
322
- )
323
- console.log(`${id}: ${title}`)
324
- } catch (err: unknown) {
325
- console.error(` \u2717 ${(err as Error).message}`)
326
- process.exit(1)
267
+ await stat(dir)
268
+ } catch {
269
+ fail(`no .opencastle/ directory at ${dir} — run opencastle init first`)
270
+ }
271
+ if (sub === 'add' && p.positional.length > 0) {
272
+ fail(`unexpected argument "${p.positional[0]}" — did you mean opencastle lesson verify or archive?`)
327
273
  }
274
+ if (sub === 'add') return add(dir, projectRoot, p)
275
+ if (sub === 'verify') return verify(dir, projectRoot, p)
276
+ return archive(dir, projectRoot, p)
328
277
  }