bmad-plus 0.12.0 → 0.12.2

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 (160) hide show
  1. package/CHANGELOG.md +612 -554
  2. package/README.md +557 -577
  3. package/osint-agent-package/agents/osint-investigator.md +12 -0
  4. package/osint-agent-package/skills/bmad-osint-investigate/osint/SKILL.md +491 -482
  5. package/osint-agent-package/skills/bmad-osint-investigate/osint/assets/dossier-template.md +126 -126
  6. package/osint-agent-package/skills/bmad-osint-investigate/osint/assets/lawful-basis-record.md +48 -48
  7. package/osint-agent-package/skills/bmad-osint-investigate/osint/references/content-extraction.md +100 -100
  8. package/osint-agent-package/skills/bmad-osint-investigate/osint/references/gdpr-osint.md +48 -48
  9. package/osint-agent-package/skills/bmad-osint-investigate/osint/references/platforms.md +130 -130
  10. package/osint-agent-package/skills/bmad-osint-investigate/osint/references/psychoprofile.md +69 -69
  11. package/osint-agent-package/skills/bmad-osint-investigate/osint/references/tools.md +281 -281
  12. package/osint-agent-package/skills/bmad-osint-investigate/osint/scripts/mcp-client.py +136 -136
  13. package/package.json +104 -91
  14. package/readme-international/README.de.md +596 -589
  15. package/readme-international/README.es.md +613 -606
  16. package/readme-international/README.fr.md +611 -604
  17. package/src/bmad-plus/agents/agent-shadow/SKILL.md +18 -0
  18. package/src/bmad-plus/data/role-triggers.yaml +52 -0
  19. package/src/bmad-plus/module.yaml +283 -283
  20. package/src/bmad-plus/packs/pack-animated/animated-website-agent.md +325 -325
  21. package/src/bmad-plus/packs/pack-animated/templates/animated-website-workflow.md +55 -55
  22. package/src/bmad-plus/packs/pack-backup/backup-agent.md +71 -71
  23. package/src/bmad-plus/packs/pack-backup/templates/backup-workflow.md +51 -51
  24. package/src/bmad-plus/packs/pack-dev-studio/README.md +162 -162
  25. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/analyst-agent.md +73 -73
  26. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/document-project.md +61 -61
  27. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/domain-research.md +95 -95
  28. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/market-research.md +95 -95
  29. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/prfaq.md +134 -134
  30. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/product-brief.md +80 -80
  31. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/tech-writer-agent.md +73 -73
  32. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/technical-research.md +95 -95
  33. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/architect-agent.md +73 -73
  34. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/create-architecture.md +73 -73
  35. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/create-epics-stories.md +92 -92
  36. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/generate-project-context.md +80 -80
  37. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/implementation-readiness.md +90 -90
  38. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-01-init.md +153 -153
  39. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-01b-continue.md +173 -173
  40. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-02-context.md +224 -224
  41. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-03-starter.md +329 -329
  42. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-04-decisions.md +318 -318
  43. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-05-patterns.md +359 -359
  44. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-06-structure.md +379 -379
  45. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-07-validation.md +361 -361
  46. package/src/bmad-plus/packs/pack-dev-studio/categories/architecture/steps/step-08-complete.md +81 -81
  47. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/checkpoint-preview.md +67 -67
  48. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/code-review-steps/step-01-gather-context.md +85 -85
  49. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/code-review-steps/step-02-review.md +35 -35
  50. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/code-review-steps/step-03-triage.md +49 -49
  51. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/code-review-steps/step-04-present.md +131 -131
  52. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/code-review.md +89 -89
  53. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/correct-course.md +300 -300
  54. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/create-story.md +428 -428
  55. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/dev-agent.md +73 -73
  56. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/dev-story-checklist.md +80 -80
  57. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/dev-story.md +484 -484
  58. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/investigate.md +193 -193
  59. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/qa-e2e-tests.md +175 -175
  60. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/quick-dev.md +110 -110
  61. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/retrospective.md +1511 -1511
  62. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/sprint-planning.md +298 -298
  63. package/src/bmad-plus/packs/pack-dev-studio/categories/implementation/sprint-status.md +296 -296
  64. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/create-prd.md +29 -29
  65. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/create-ux-design.md +74 -74
  66. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/edit-prd.md +29 -29
  67. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/pm-agent.md +73 -73
  68. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/prd.md +89 -89
  69. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/ux-designer-agent.md +73 -73
  70. package/src/bmad-plus/packs/pack-dev-studio/categories/planning/validate-prd.md +29 -29
  71. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/advanced-elicitation.md +141 -141
  72. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/adversarial-review.md +37 -37
  73. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/bmad-help.md +75 -75
  74. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/brainstorming.md +6 -6
  75. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/customize.md +110 -110
  76. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/distillator.md +176 -176
  77. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/edge-case-hunter.md +67 -67
  78. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/editorial-review-prose.md +86 -86
  79. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/editorial-review-structure.md +179 -179
  80. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/index-docs.md +66 -66
  81. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/party-mode.md +127 -127
  82. package/src/bmad-plus/packs/pack-dev-studio/categories/utilities/shard-doc.md +105 -105
  83. package/src/bmad-plus/packs/pack-dev-studio/dev-studio-orchestrator.md +120 -120
  84. package/src/bmad-plus/packs/pack-dev-studio/shared/architecture-decision-template.md +12 -12
  85. package/src/bmad-plus/packs/pack-dev-studio/shared/bwml-spec.md +328 -328
  86. package/src/bmad-plus/packs/pack-dev-studio/shared/module-help.csv +32 -32
  87. package/src/bmad-plus/packs/pack-dev-studio/upstream-sync.yaml +81 -81
  88. package/src/bmad-plus/packs/pack-memory/shared/memory-protocol.md +14 -0
  89. package/src/bmad-plus/packs/pack-seo/SKILL.md +171 -171
  90. package/src/bmad-plus/packs/pack-seo/checklist.md +140 -140
  91. package/src/bmad-plus/packs/pack-seo/pagespeed-playbook.md +320 -320
  92. package/src/bmad-plus/packs/pack-seo/ref/audit-schema.json +187 -187
  93. package/src/bmad-plus/packs/pack-seo/ref/cwv-thresholds.md +87 -87
  94. package/src/bmad-plus/packs/pack-seo/ref/eeat-criteria.md +123 -123
  95. package/src/bmad-plus/packs/pack-seo/ref/geo-signals.md +167 -167
  96. package/src/bmad-plus/packs/pack-seo/ref/hreflang-rules.md +153 -153
  97. package/src/bmad-plus/packs/pack-seo/ref/quality-gates.md +133 -133
  98. package/src/bmad-plus/packs/pack-seo/ref/schema-catalog.md +91 -91
  99. package/src/bmad-plus/packs/pack-seo/ref/schema-templates.json +356 -356
  100. package/src/bmad-plus/packs/pack-seo/requirements.txt +17 -0
  101. package/src/bmad-plus/packs/pack-seo/scripts/seo_apis.py +456 -0
  102. package/src/bmad-plus/packs/pack-seo/scripts/seo_crawl.py +359 -0
  103. package/src/bmad-plus/packs/pack-seo/scripts/seo_fetch.py +304 -0
  104. package/src/bmad-plus/packs/pack-seo/scripts/seo_parse.py +255 -0
  105. package/src/bmad-plus/packs/pack-seo/scripts/seo_report.py +410 -0
  106. package/src/bmad-plus/packs/pack-seo/scripts/seo_screenshot.py +202 -0
  107. package/src/bmad-plus/packs/pack-seo/seo-chief.md +294 -294
  108. package/src/bmad-plus/packs/pack-seo/seo-judge.md +241 -241
  109. package/src/bmad-plus/packs/pack-seo/seo-scout.md +171 -171
  110. package/src/bmad-plus/packs/pack-seo/templates/seo-audit-workflow.md +241 -241
  111. package/src/bmad-plus/packs/pack-shield/README.md +6 -6
  112. package/src/bmad-plus/packs/pack-shield/SKILL.md +2 -2
  113. package/src/bmad-plus/packs/pack-shield/categories/accessibility-esg/csrd-agent.md +11 -11
  114. package/src/bmad-plus/packs/pack-shield/categories/accessibility-esg/section508-agent.md +11 -11
  115. package/src/bmad-plus/packs/pack-shield/categories/accessibility-esg/wcag-agent.md +11 -11
  116. package/src/bmad-plus/packs/pack-shield/categories/ai-governance/eu-ai-act-agent.md +11 -11
  117. package/src/bmad-plus/packs/pack-shield/categories/ai-governance/iso42001-agent.md +11 -11
  118. package/src/bmad-plus/packs/pack-shield/categories/ai-governance/nist-ai-rmf-agent.md +11 -11
  119. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/cis-controls-agent.md +11 -11
  120. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/ism-agent.md +11 -11
  121. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/iso27001-agent.md +11 -11
  122. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/nis2-agent.md +11 -11
  123. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/nist-800-53-agent.md +11 -11
  124. package/src/bmad-plus/packs/pack-shield/categories/cybersecurity/nist-csf-agent.md +11 -11
  125. package/src/bmad-plus/packs/pack-shield/categories/defense-export/cmmc-agent.md +11 -11
  126. package/src/bmad-plus/packs/pack-shield/categories/defense-export/ear-agent.md +11 -11
  127. package/src/bmad-plus/packs/pack-shield/categories/defense-export/itar-agent.md +11 -11
  128. package/src/bmad-plus/packs/pack-shield/categories/defense-export/tsa-agent.md +11 -11
  129. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/dora-agent.md +11 -11
  130. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/fedramp-agent.md +11 -11
  131. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/hipaa-agent.md +11 -11
  132. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/pci-dss-agent.md +11 -11
  133. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/soc2-agent.md +11 -11
  134. package/src/bmad-plus/packs/pack-shield/categories/industry-compliance/swift-csp-agent.md +11 -11
  135. package/src/bmad-plus/packs/pack-shield/shield-orchestrator.md +1 -1
  136. package/tools/build/check-counts.js +628 -0
  137. package/tools/build/generated-adapters/.codex/AGENTS.md +1 -1
  138. package/tools/build/generated-adapters/.cursor/rules/bmad-plus.mdc +1 -1
  139. package/tools/build/generated-adapters/.opencode/AGENTS.md +1 -1
  140. package/tools/build/generated-adapters/AGENTS.md +1 -1
  141. package/tools/build/generated-adapters/CLAUDE.md +1 -1
  142. package/tools/build/generated-adapters/CONVENTIONS.md +1 -1
  143. package/tools/build/generated-adapters/GEMINI.md +1 -1
  144. package/tools/cli/commands/autoconfig.js +470 -472
  145. package/tools/cli/commands/doctor.js +233 -233
  146. package/tools/cli/commands/install.js +598 -495
  147. package/tools/cli/commands/memory-journal-cmd.js +311 -311
  148. package/tools/cli/commands/memory.js +195 -195
  149. package/tools/cli/commands/scan.js +348 -364
  150. package/tools/cli/commands/uninstall.js +101 -101
  151. package/tools/cli/commands/update.js +134 -134
  152. package/tools/cli/i18n.js +845 -845
  153. package/tools/cli/lib/README-memory-journal.md +125 -125
  154. package/tools/cli/lib/ide-config.js +267 -259
  155. package/tools/cli/lib/memory-init.js +204 -113
  156. package/tools/cli/lib/packs.js +209 -209
  157. package/tools/cli/lib/path-hash.js +39 -0
  158. package/tools/cli/lib/python-provision.js +508 -508
  159. package/tools/cli/lib/stack-detect.js +102 -102
  160. package/tools/cli/lib/validate.js +50 -50
@@ -1,311 +1,311 @@
1
- /**
2
- * BMAD+ `mem` Command — portable Karpathy memory loop (Pillar 3)
3
- *
4
- * Exposes tools/cli/lib/memory-journal.js through the CLI so recall / write /
5
- * reinforce behave IDENTICALLY no matter which agent CLI is driving
6
- * (claude-code, gemini-cli, codex-cli, cursor, opencode, aider, antigravity):
7
- *
8
- * bmad-plus mem recall <query...> — ranked retrieval over journal + memory files
9
- * bmad-plus mem write — append a structured event (--agent --cli --model --task --outcome)
10
- * bmad-plus mem reinforce — apply a reward to a pattern score; any resulting
11
- * promotion is persisted as PROPOSED, never applied
12
- *
13
- * NOTE: registered as `mem` (not `memory`) — `memory` is already taken by the
14
- * brain scanner in tools/cli/commands/memory.js and must not be disturbed.
15
- *
16
- * Design rules (mirroring memory-journal.js):
17
- * - The clock is read ONCE inside the action (new Date().toISOString()) and
18
- * injected into every library call. Nothing reads the clock at import time.
19
- * - The run* handlers take an injected `now` + `log`, so tests drive them
20
- * deterministically against a tmp dir (tests/unit/memory-journal-cmd.test.js).
21
- * - Output goes through plain log lines (+ --json for machine consumption) so
22
- * ANY driving CLI can parse results — no interactive prompts, no TTY needs.
23
- * - Governance guard: reinforce may PROPOSE a pattern promotion when the
24
- * posterior mean crosses the threshold, but the record is always written
25
- * with status PROPOSED (memory-journal.appendPromotion forces it anyway).
26
- *
27
- * Author: Laurent Rochetta
28
- */
29
-
30
- 'use strict';
31
-
32
- const path = require('node:path');
33
- const fs = require('node:fs');
34
- const mj = require('../lib/memory-journal');
35
-
36
- // ── Pattern score store ──────────────────────────────────────────────────────
37
- // Lives next to the journal in the north-star scope (.bmad/memory/). Keyed by
38
- // patternId (the `### heading` in patterns.md). This file is CLI-owned state;
39
- // memory-journal.js stays a pure library and never touches it.
40
-
41
- const SCORES_RELPATH = path.join('.bmad', 'memory', 'pattern-scores.json');
42
-
43
- // Promotion proposal thresholds (candidate → validated). Tuned conservatively:
44
- // the posterior mean is decayed-Bayesian (memory-journal.updatePatternScore),
45
- // so 0.7 over >= 3 updates means a genuinely recent, repeated success signal.
46
- const PROMOTION_MEAN_THRESHOLD = 0.7;
47
- const PROMOTION_MIN_UPDATES = 3;
48
-
49
- function scoresPath(baseDir) {
50
- return path.join(baseDir, SCORES_RELPATH);
51
- }
52
-
53
- function readScores(baseDir) {
54
- const file = scoresPath(baseDir);
55
- if (!fs.existsSync(file)) return {};
56
- try {
57
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
58
- return parsed && typeof parsed === 'object' ? parsed : {};
59
- } catch {
60
- // Corrupt store never blocks the loop — reinforcement restarts from priors.
61
- return {};
62
- }
63
- }
64
-
65
- function writeScores(baseDir, scores) {
66
- const file = scoresPath(baseDir);
67
- fs.mkdirSync(path.dirname(file), { recursive: true });
68
- fs.writeFileSync(file, JSON.stringify(scores, null, 2) + '\n', 'utf8');
69
- }
70
-
71
- // ── Flag parsing helpers ─────────────────────────────────────────────────────
72
-
73
- /** Map CLI flags to the memory-journal signals shape { evalScore, acceptance, ci }. */
74
- function parseSignals(opts) {
75
- const signals = {};
76
- if (opts.eval !== undefined && opts.eval !== null) {
77
- signals.evalScore = Number(opts.eval);
78
- }
79
- if (opts.accept !== undefined && opts.accept !== null) {
80
- const raw = String(opts.accept).toLowerCase();
81
- if (raw === 'true' || raw === 'yes') signals.acceptance = true;
82
- else if (raw === 'false' || raw === 'no') signals.acceptance = false;
83
- else signals.acceptance = Number(opts.accept);
84
- }
85
- if (opts.ci !== undefined && opts.ci !== null) {
86
- signals.ci = opts.ci === 'pass' || opts.ci === 'fail' ? opts.ci : Number(opts.ci);
87
- }
88
- return signals;
89
- }
90
-
91
- function truncate(text, max = 120) {
92
- const oneLine = String(text).replace(/\s+/g, ' ').trim();
93
- return oneLine.length > max ? oneLine.slice(0, max - 1) + '…' : oneLine;
94
- }
95
-
96
- // ── Action handlers (dependency-injected, unit-testable) ─────────────────────
97
-
98
- /**
99
- * `mem recall <query...>` — ranked retrieval over journal events + memory notes.
100
- *
101
- * @param {string} query
102
- * @param {object} opts - { baseDir, scope, portfolioDir, limit, now, json, log }
103
- * `now` is the INJECTED clock (enables recency decay).
104
- * @returns {object[]} ranked entries (same shape as memory-journal.recall)
105
- */
106
- function runRecall(query, opts = {}) {
107
- const { baseDir = process.cwd(), scope = 'project', portfolioDir = null, limit = 8, now = null, json = false, log = console.log } = opts;
108
-
109
- const results = mj.recall(query, { baseDir, scope, portfolioDir, limit, now });
110
-
111
- if (json) {
112
- log(JSON.stringify({ query, scope, count: results.length, results }, null, 2));
113
- return results;
114
- }
115
-
116
- if (results.length === 0) {
117
- log(`mem recall: no matches for "${query}" (scope: ${scope})`);
118
- return results;
119
- }
120
- log(`mem recall: ${results.length} match(es) for "${query}" (scope: ${scope})`);
121
- results.forEach((r, i) => {
122
- const origin = r.kind === 'event' ? `event ${r.source}#${r.ref}` : `note ${r.source} § ${r.ref}`;
123
- log(` ${i + 1}. [${r.score.toFixed(3)}] ${origin}`);
124
- log(` ${truncate(r.text)}`);
125
- });
126
- return results;
127
- }
128
-
129
- /**
130
- * `mem write` — append a structured event to the journal.
131
- *
132
- * @param {object} opts - { baseDir, agent, cli, model, task, outcome, signals, now, json, log }
133
- * `now` is the INJECTED clock used as the event ts.
134
- * @returns {object} the persisted event
135
- */
136
- function runWrite(opts = {}) {
137
- const { baseDir = process.cwd(), agent, cli = null, model = null, task = '', outcome = undefined, signals = {}, now, json = false, log = console.log } = opts;
138
-
139
- const event = mj.appendEvent(baseDir, {
140
- ts: now,
141
- agent,
142
- cli,
143
- model,
144
- task,
145
- outcome,
146
- signals,
147
- });
148
-
149
- if (json) {
150
- log(JSON.stringify({ written: event }, null, 2));
151
- } else {
152
- log(`mem write: event ${event.id} appended (${event.ts})`);
153
- log(` agent=${event.agent} cli=${event.cli || '-'} model=${event.model || '-'} outcome=${event.outcome || '-'}`);
154
- if (event.task) log(` task: ${truncate(event.task)}`);
155
- }
156
- return event;
157
- }
158
-
159
- /**
160
- * `mem reinforce` — fold reward signals into a pattern's score.
161
- *
162
- * Updates the CLI-owned pattern-scores.json (Elo for ranking, decayed-Bayesian
163
- * mean for promotion). When the mean crosses PROMOTION_MEAN_THRESHOLD with
164
- * enough updates, a promotion is PROPOSED via memory-journal's governance
165
- * guard — persisted as PROPOSED, applied only after human/Shield approval.
166
- *
167
- * @param {object} opts - { baseDir, patternId, signals, evidence, now, json, log }
168
- * @returns {{patternId:string, reward:number, previous:object, next:object, promotion:object|null}}
169
- */
170
- function runReinforce(opts = {}) {
171
- const { baseDir = process.cwd(), patternId, signals = {}, evidence = [], now, json = false, log = console.log } = opts;
172
-
173
- if (typeof patternId !== 'string' || patternId.trim().length === 0) {
174
- throw new TypeError('mem reinforce: --pattern <id> is required (the pattern heading in patterns.md)');
175
- }
176
-
177
- const reward = mj.computeReward(signals);
178
- const scores = readScores(baseDir);
179
- const previous = scores[patternId] || null;
180
- const next = mj.updatePatternScore(previous, reward, { ts: now });
181
- scores[patternId] = next;
182
- writeScores(baseDir, scores);
183
-
184
- // Governance: promotion is only ever PROPOSED here. appendPromotion() forces
185
- // status PROPOSED on disk regardless, and applying requires
186
- // assertPromotionApplicable() to pass with a human/Shield approval.
187
- let promotion = null;
188
- if (next.mean >= PROMOTION_MEAN_THRESHOLD && next.updates >= PROMOTION_MIN_UPDATES) {
189
- promotion = mj.appendPromotion(
190
- baseDir,
191
- mj.proposePromotion({
192
- patternId,
193
- ts: now,
194
- reason: `posterior mean ${next.mean.toFixed(3)} >= ${PROMOTION_MEAN_THRESHOLD} over ${next.updates} update(s)`,
195
- evidence,
196
- score: next,
197
- })
198
- );
199
- }
200
-
201
- const result = { patternId, reward, previous, next, promotion };
202
-
203
- if (json) {
204
- log(JSON.stringify(result, null, 2));
205
- return result;
206
- }
207
-
208
- const prevElo = previous ? previous.elo : mj.INITIAL_PATTERN_SCORE.elo;
209
- log(`mem reinforce: pattern "${patternId}"`);
210
- log(` reward ${reward.toFixed(3)} (from ${JSON.stringify(signals)})`);
211
- log(` elo ${prevElo.toFixed(1)} -> ${next.elo.toFixed(1)}`);
212
- log(` mean ${next.mean.toFixed(3)} (alpha=${next.alpha.toFixed(2)}, beta=${next.beta.toFixed(2)}, updates=${next.updates})`);
213
- if (promotion) {
214
- log(` promotion PROPOSED (${promotion.id}): ${promotion.fromStatus} -> ${promotion.toStatus}`);
215
- log(` awaiting human/Shield approval — never auto-applied (governance guard)`);
216
- } else {
217
- log(` promotion: none proposed (needs mean >= ${PROMOTION_MEAN_THRESHOLD} and >= ${PROMOTION_MIN_UPDATES} updates)`);
218
- }
219
- return result;
220
- }
221
-
222
- // ── Commander wiring ─────────────────────────────────────────────────────────
223
-
224
- module.exports = {
225
- command: 'mem <action> [query...]',
226
- description: 'Karpathy memory loop — recall | write | reinforce (portable across agent CLIs)',
227
- options: [
228
- ['-d, --directory <path>', 'Project directory (default: current directory)'],
229
- ['--scope <scope>', 'Recall scope: project | portfolio', 'project'],
230
- ['--portfolio <path>', 'Portfolio brain directory (used with --scope portfolio)'],
231
- ['--limit <n>', 'Max recall results', '8'],
232
- ['--agent <name>', 'Agent that produced the event (write)'],
233
- ['--cli <name>', 'Driving CLI: claude-code, gemini-cli, codex-cli, cursor, opencode, aider, antigravity'],
234
- ['--model <id>', 'Model id used (model-agnostic: claude/gpt/gemini/local)'],
235
- ['--task <text>', 'What was attempted (write)'],
236
- ['--outcome <outcome>', 'success | failure | partial | abandoned (write)'],
237
- ['--pattern <id>', 'Pattern id to reinforce (its heading in patterns.md)'],
238
- ['--eval <score>', 'Eval suite score in [0,1] (write/reinforce signal)'],
239
- ['--accept <bool>', 'User acceptance: true | false | [0,1] (write/reinforce signal)'],
240
- ['--ci <result>', 'CI outcome: pass | fail | [0,1] (write/reinforce signal)'],
241
- ['--evidence <ids>', 'Comma-separated journal event ids backing a reinforcement'],
242
- ['--json', 'Machine-readable JSON output'],
243
- ],
244
- subcommands: {
245
- recall: 'Ranked retrieval over the journal + memory files',
246
- write: 'Append a structured event to .bmad/memory/journal.ndjson',
247
- reinforce: 'Apply a reward to a pattern score (promotions PROPOSED only)',
248
- },
249
-
250
- action: async (action, query, options = {}) => {
251
- // Clock is read HERE, at call time, then injected everywhere below —
252
- // memory-journal.js never reads it (see its determinism contract).
253
- const now = new Date().toISOString();
254
- const baseDir = path.resolve(options.directory || process.cwd());
255
- const json = Boolean(options.json);
256
- const queryText = Array.isArray(query) ? query.join(' ') : query || '';
257
-
258
- try {
259
- if (action === 'recall') {
260
- runRecall(queryText, {
261
- baseDir,
262
- scope: options.scope || 'project',
263
- portfolioDir: options.portfolio || null,
264
- limit: Number(options.limit || 8),
265
- now,
266
- json,
267
- });
268
- } else if (action === 'write') {
269
- runWrite({
270
- baseDir,
271
- agent: options.agent,
272
- cli: options.cli || null,
273
- model: options.model || null,
274
- task: options.task || '',
275
- outcome: options.outcome,
276
- signals: parseSignals(options),
277
- now,
278
- json,
279
- });
280
- } else if (action === 'reinforce') {
281
- runReinforce({
282
- baseDir,
283
- patternId: options.pattern,
284
- signals: parseSignals(options),
285
- evidence: options.evidence ? String(options.evidence).split(',').map(s => s.trim()).filter(Boolean) : [],
286
- now,
287
- json,
288
- });
289
- } else {
290
- console.error(`mem: unknown action '${action}' — expected recall | write | reinforce`);
291
- process.exitCode = 1;
292
- }
293
- } catch (err) {
294
- console.error(`mem ${action}: ${err.message}`);
295
- process.exitCode = 1;
296
- }
297
- },
298
-
299
- // Exported for tests + future MCP wrapper (memory.recall / memory.write tools)
300
- _internal: {
301
- runRecall,
302
- runWrite,
303
- runReinforce,
304
- parseSignals,
305
- readScores,
306
- writeScores,
307
- SCORES_RELPATH,
308
- PROMOTION_MEAN_THRESHOLD,
309
- PROMOTION_MIN_UPDATES,
310
- },
311
- };
1
+ /**
2
+ * BMAD+ `mem` Command — portable Karpathy memory loop (Pillar 3)
3
+ *
4
+ * Exposes tools/cli/lib/memory-journal.js through the CLI so recall / write /
5
+ * reinforce behave IDENTICALLY no matter which agent CLI is driving
6
+ * (claude-code, gemini-cli, codex-cli, cursor, opencode, aider, antigravity):
7
+ *
8
+ * bmad-plus mem recall <query...> — ranked retrieval over journal + memory files
9
+ * bmad-plus mem write — append a structured event (--agent --cli --model --task --outcome)
10
+ * bmad-plus mem reinforce — apply a reward to a pattern score; any resulting
11
+ * promotion is persisted as PROPOSED, never applied
12
+ *
13
+ * NOTE: registered as `mem` (not `memory`) — `memory` is already taken by the
14
+ * brain scanner in tools/cli/commands/memory.js and must not be disturbed.
15
+ *
16
+ * Design rules (mirroring memory-journal.js):
17
+ * - The clock is read ONCE inside the action (new Date().toISOString()) and
18
+ * injected into every library call. Nothing reads the clock at import time.
19
+ * - The run* handlers take an injected `now` + `log`, so tests drive them
20
+ * deterministically against a tmp dir (tests/unit/memory-journal-cmd.test.js).
21
+ * - Output goes through plain log lines (+ --json for machine consumption) so
22
+ * ANY driving CLI can parse results — no interactive prompts, no TTY needs.
23
+ * - Governance guard: reinforce may PROPOSE a pattern promotion when the
24
+ * posterior mean crosses the threshold, but the record is always written
25
+ * with status PROPOSED (memory-journal.appendPromotion forces it anyway).
26
+ *
27
+ * Author: Laurent Rochetta
28
+ */
29
+
30
+ 'use strict';
31
+
32
+ const path = require('node:path');
33
+ const fs = require('node:fs');
34
+ const mj = require('../lib/memory-journal');
35
+
36
+ // ── Pattern score store ──────────────────────────────────────────────────────
37
+ // Lives next to the journal in the north-star scope (.bmad/memory/). Keyed by
38
+ // patternId (the `### heading` in patterns.md). This file is CLI-owned state;
39
+ // memory-journal.js stays a pure library and never touches it.
40
+
41
+ const SCORES_RELPATH = path.join('.bmad', 'memory', 'pattern-scores.json');
42
+
43
+ // Promotion proposal thresholds (candidate → validated). Tuned conservatively:
44
+ // the posterior mean is decayed-Bayesian (memory-journal.updatePatternScore),
45
+ // so 0.7 over >= 3 updates means a genuinely recent, repeated success signal.
46
+ const PROMOTION_MEAN_THRESHOLD = 0.7;
47
+ const PROMOTION_MIN_UPDATES = 3;
48
+
49
+ function scoresPath(baseDir) {
50
+ return path.join(baseDir, SCORES_RELPATH);
51
+ }
52
+
53
+ function readScores(baseDir) {
54
+ const file = scoresPath(baseDir);
55
+ if (!fs.existsSync(file)) return {};
56
+ try {
57
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
58
+ return parsed && typeof parsed === 'object' ? parsed : {};
59
+ } catch {
60
+ // Corrupt store never blocks the loop — reinforcement restarts from priors.
61
+ return {};
62
+ }
63
+ }
64
+
65
+ function writeScores(baseDir, scores) {
66
+ const file = scoresPath(baseDir);
67
+ fs.mkdirSync(path.dirname(file), { recursive: true });
68
+ fs.writeFileSync(file, JSON.stringify(scores, null, 2) + '\n', 'utf8');
69
+ }
70
+
71
+ // ── Flag parsing helpers ─────────────────────────────────────────────────────
72
+
73
+ /** Map CLI flags to the memory-journal signals shape { evalScore, acceptance, ci }. */
74
+ function parseSignals(opts) {
75
+ const signals = {};
76
+ if (opts.eval !== undefined && opts.eval !== null) {
77
+ signals.evalScore = Number(opts.eval);
78
+ }
79
+ if (opts.accept !== undefined && opts.accept !== null) {
80
+ const raw = String(opts.accept).toLowerCase();
81
+ if (raw === 'true' || raw === 'yes') signals.acceptance = true;
82
+ else if (raw === 'false' || raw === 'no') signals.acceptance = false;
83
+ else signals.acceptance = Number(opts.accept);
84
+ }
85
+ if (opts.ci !== undefined && opts.ci !== null) {
86
+ signals.ci = opts.ci === 'pass' || opts.ci === 'fail' ? opts.ci : Number(opts.ci);
87
+ }
88
+ return signals;
89
+ }
90
+
91
+ function truncate(text, max = 120) {
92
+ const oneLine = String(text).replace(/\s+/g, ' ').trim();
93
+ return oneLine.length > max ? oneLine.slice(0, max - 1) + '…' : oneLine;
94
+ }
95
+
96
+ // ── Action handlers (dependency-injected, unit-testable) ─────────────────────
97
+
98
+ /**
99
+ * `mem recall <query...>` — ranked retrieval over journal events + memory notes.
100
+ *
101
+ * @param {string} query
102
+ * @param {object} opts - { baseDir, scope, portfolioDir, limit, now, json, log }
103
+ * `now` is the INJECTED clock (enables recency decay).
104
+ * @returns {object[]} ranked entries (same shape as memory-journal.recall)
105
+ */
106
+ function runRecall(query, opts = {}) {
107
+ const { baseDir = process.cwd(), scope = 'project', portfolioDir = null, limit = 8, now = null, json = false, log = console.log } = opts;
108
+
109
+ const results = mj.recall(query, { baseDir, scope, portfolioDir, limit, now });
110
+
111
+ if (json) {
112
+ log(JSON.stringify({ query, scope, count: results.length, results }, null, 2));
113
+ return results;
114
+ }
115
+
116
+ if (results.length === 0) {
117
+ log(`mem recall: no matches for "${query}" (scope: ${scope})`);
118
+ return results;
119
+ }
120
+ log(`mem recall: ${results.length} match(es) for "${query}" (scope: ${scope})`);
121
+ results.forEach((r, i) => {
122
+ const origin = r.kind === 'event' ? `event ${r.source}#${r.ref}` : `note ${r.source} § ${r.ref}`;
123
+ log(` ${i + 1}. [${r.score.toFixed(3)}] ${origin}`);
124
+ log(` ${truncate(r.text)}`);
125
+ });
126
+ return results;
127
+ }
128
+
129
+ /**
130
+ * `mem write` — append a structured event to the journal.
131
+ *
132
+ * @param {object} opts - { baseDir, agent, cli, model, task, outcome, signals, now, json, log }
133
+ * `now` is the INJECTED clock used as the event ts.
134
+ * @returns {object} the persisted event
135
+ */
136
+ function runWrite(opts = {}) {
137
+ const { baseDir = process.cwd(), agent, cli = null, model = null, task = '', outcome = undefined, signals = {}, now, json = false, log = console.log } = opts;
138
+
139
+ const event = mj.appendEvent(baseDir, {
140
+ ts: now,
141
+ agent,
142
+ cli,
143
+ model,
144
+ task,
145
+ outcome,
146
+ signals,
147
+ });
148
+
149
+ if (json) {
150
+ log(JSON.stringify({ written: event }, null, 2));
151
+ } else {
152
+ log(`mem write: event ${event.id} appended (${event.ts})`);
153
+ log(` agent=${event.agent} cli=${event.cli || '-'} model=${event.model || '-'} outcome=${event.outcome || '-'}`);
154
+ if (event.task) log(` task: ${truncate(event.task)}`);
155
+ }
156
+ return event;
157
+ }
158
+
159
+ /**
160
+ * `mem reinforce` — fold reward signals into a pattern's score.
161
+ *
162
+ * Updates the CLI-owned pattern-scores.json (Elo for ranking, decayed-Bayesian
163
+ * mean for promotion). When the mean crosses PROMOTION_MEAN_THRESHOLD with
164
+ * enough updates, a promotion is PROPOSED via memory-journal's governance
165
+ * guard — persisted as PROPOSED, applied only after human/Shield approval.
166
+ *
167
+ * @param {object} opts - { baseDir, patternId, signals, evidence, now, json, log }
168
+ * @returns {{patternId:string, reward:number, previous:object, next:object, promotion:object|null}}
169
+ */
170
+ function runReinforce(opts = {}) {
171
+ const { baseDir = process.cwd(), patternId, signals = {}, evidence = [], now, json = false, log = console.log } = opts;
172
+
173
+ if (typeof patternId !== 'string' || patternId.trim().length === 0) {
174
+ throw new TypeError('mem reinforce: --pattern <id> is required (the pattern heading in patterns.md)');
175
+ }
176
+
177
+ const reward = mj.computeReward(signals);
178
+ const scores = readScores(baseDir);
179
+ const previous = scores[patternId] || null;
180
+ const next = mj.updatePatternScore(previous, reward, { ts: now });
181
+ scores[patternId] = next;
182
+ writeScores(baseDir, scores);
183
+
184
+ // Governance: promotion is only ever PROPOSED here. appendPromotion() forces
185
+ // status PROPOSED on disk regardless, and applying requires
186
+ // assertPromotionApplicable() to pass with a human/Shield approval.
187
+ let promotion = null;
188
+ if (next.mean >= PROMOTION_MEAN_THRESHOLD && next.updates >= PROMOTION_MIN_UPDATES) {
189
+ promotion = mj.appendPromotion(
190
+ baseDir,
191
+ mj.proposePromotion({
192
+ patternId,
193
+ ts: now,
194
+ reason: `posterior mean ${next.mean.toFixed(3)} >= ${PROMOTION_MEAN_THRESHOLD} over ${next.updates} update(s)`,
195
+ evidence,
196
+ score: next,
197
+ })
198
+ );
199
+ }
200
+
201
+ const result = { patternId, reward, previous, next, promotion };
202
+
203
+ if (json) {
204
+ log(JSON.stringify(result, null, 2));
205
+ return result;
206
+ }
207
+
208
+ const prevElo = previous ? previous.elo : mj.INITIAL_PATTERN_SCORE.elo;
209
+ log(`mem reinforce: pattern "${patternId}"`);
210
+ log(` reward ${reward.toFixed(3)} (from ${JSON.stringify(signals)})`);
211
+ log(` elo ${prevElo.toFixed(1)} -> ${next.elo.toFixed(1)}`);
212
+ log(` mean ${next.mean.toFixed(3)} (alpha=${next.alpha.toFixed(2)}, beta=${next.beta.toFixed(2)}, updates=${next.updates})`);
213
+ if (promotion) {
214
+ log(` promotion PROPOSED (${promotion.id}): ${promotion.fromStatus} -> ${promotion.toStatus}`);
215
+ log(` awaiting human/Shield approval — never auto-applied (governance guard)`);
216
+ } else {
217
+ log(` promotion: none proposed (needs mean >= ${PROMOTION_MEAN_THRESHOLD} and >= ${PROMOTION_MIN_UPDATES} updates)`);
218
+ }
219
+ return result;
220
+ }
221
+
222
+ // ── Commander wiring ─────────────────────────────────────────────────────────
223
+
224
+ module.exports = {
225
+ command: 'mem <action> [query...]',
226
+ description: 'Karpathy memory loop — recall | write | reinforce (portable across agent CLIs)',
227
+ options: [
228
+ ['-d, --directory <path>', 'Project directory (default: current directory)'],
229
+ ['--scope <scope>', 'Recall scope: project | portfolio', 'project'],
230
+ ['--portfolio <path>', 'Portfolio brain directory (used with --scope portfolio)'],
231
+ ['--limit <n>', 'Max recall results', '8'],
232
+ ['--agent <name>', 'Agent that produced the event (write)'],
233
+ ['--cli <name>', 'Driving CLI: claude-code, gemini-cli, codex-cli, cursor, opencode, aider, antigravity'],
234
+ ['--model <id>', 'Model id used (model-agnostic: claude/gpt/gemini/local)'],
235
+ ['--task <text>', 'What was attempted (write)'],
236
+ ['--outcome <outcome>', 'success | failure | partial | abandoned (write)'],
237
+ ['--pattern <id>', 'Pattern id to reinforce (its heading in patterns.md)'],
238
+ ['--eval <score>', 'Eval suite score in [0,1] (write/reinforce signal)'],
239
+ ['--accept <bool>', 'User acceptance: true | false | [0,1] (write/reinforce signal)'],
240
+ ['--ci <result>', 'CI outcome: pass | fail | [0,1] (write/reinforce signal)'],
241
+ ['--evidence <ids>', 'Comma-separated journal event ids backing a reinforcement'],
242
+ ['--json', 'Machine-readable JSON output'],
243
+ ],
244
+ subcommands: {
245
+ recall: 'Ranked retrieval over the journal + memory files',
246
+ write: 'Append a structured event to .bmad/memory/journal.ndjson',
247
+ reinforce: 'Apply a reward to a pattern score (promotions PROPOSED only)',
248
+ },
249
+
250
+ action: async (action, query, options = {}) => {
251
+ // Clock is read HERE, at call time, then injected everywhere below —
252
+ // memory-journal.js never reads it (see its determinism contract).
253
+ const now = new Date().toISOString();
254
+ const baseDir = path.resolve(options.directory || process.cwd());
255
+ const json = Boolean(options.json);
256
+ const queryText = Array.isArray(query) ? query.join(' ') : query || '';
257
+
258
+ try {
259
+ if (action === 'recall') {
260
+ runRecall(queryText, {
261
+ baseDir,
262
+ scope: options.scope || 'project',
263
+ portfolioDir: options.portfolio || null,
264
+ limit: Number(options.limit || 8),
265
+ now,
266
+ json,
267
+ });
268
+ } else if (action === 'write') {
269
+ runWrite({
270
+ baseDir,
271
+ agent: options.agent,
272
+ cli: options.cli || null,
273
+ model: options.model || null,
274
+ task: options.task || '',
275
+ outcome: options.outcome,
276
+ signals: parseSignals(options),
277
+ now,
278
+ json,
279
+ });
280
+ } else if (action === 'reinforce') {
281
+ runReinforce({
282
+ baseDir,
283
+ patternId: options.pattern,
284
+ signals: parseSignals(options),
285
+ evidence: options.evidence ? String(options.evidence).split(',').map(s => s.trim()).filter(Boolean) : [],
286
+ now,
287
+ json,
288
+ });
289
+ } else {
290
+ console.error(`mem: unknown action '${action}' — expected recall | write | reinforce`);
291
+ process.exitCode = 1;
292
+ }
293
+ } catch (err) {
294
+ console.error(`mem ${action}: ${err.message}`);
295
+ process.exitCode = 1;
296
+ }
297
+ },
298
+
299
+ // Exported for tests + future MCP wrapper (memory.recall / memory.write tools)
300
+ _internal: {
301
+ runRecall,
302
+ runWrite,
303
+ runReinforce,
304
+ parseSignals,
305
+ readScores,
306
+ writeScores,
307
+ SCORES_RELPATH,
308
+ PROMOTION_MEAN_THRESHOLD,
309
+ PROMOTION_MIN_UPDATES,
310
+ },
311
+ };