hivemind-context-governance 1.3.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 (139) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/LICENSE +21 -0
  3. package/README.md +218 -0
  4. package/dist/cli/init.d.ts +23 -0
  5. package/dist/cli/init.d.ts.map +1 -0
  6. package/dist/cli/init.js +175 -0
  7. package/dist/cli/init.js.map +1 -0
  8. package/dist/cli.d.ts +14 -0
  9. package/dist/cli.d.ts.map +1 -0
  10. package/dist/cli.js +162 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/dashboard/i18n/en.d.ts +43 -0
  13. package/dist/dashboard/i18n/en.d.ts.map +1 -0
  14. package/dist/dashboard/i18n/en.js +43 -0
  15. package/dist/dashboard/i18n/en.js.map +1 -0
  16. package/dist/dashboard/i18n/index.d.ts +10 -0
  17. package/dist/dashboard/i18n/index.d.ts.map +1 -0
  18. package/dist/dashboard/i18n/index.js +14 -0
  19. package/dist/dashboard/i18n/index.js.map +1 -0
  20. package/dist/dashboard/i18n/vi.d.ts +43 -0
  21. package/dist/dashboard/i18n/vi.d.ts.map +1 -0
  22. package/dist/dashboard/i18n/vi.js +43 -0
  23. package/dist/dashboard/i18n/vi.js.map +1 -0
  24. package/dist/dashboard/server.d.ts +23 -0
  25. package/dist/dashboard/server.d.ts.map +1 -0
  26. package/dist/dashboard/server.js +282 -0
  27. package/dist/dashboard/server.js.map +1 -0
  28. package/dist/hooks/compaction.d.ts +21 -0
  29. package/dist/hooks/compaction.d.ts.map +1 -0
  30. package/dist/hooks/compaction.js +79 -0
  31. package/dist/hooks/compaction.js.map +1 -0
  32. package/dist/hooks/index.d.ts +8 -0
  33. package/dist/hooks/index.d.ts.map +1 -0
  34. package/dist/hooks/index.js +7 -0
  35. package/dist/hooks/index.js.map +1 -0
  36. package/dist/hooks/session-lifecycle.d.ts +28 -0
  37. package/dist/hooks/session-lifecycle.d.ts.map +1 -0
  38. package/dist/hooks/session-lifecycle.js +94 -0
  39. package/dist/hooks/session-lifecycle.js.map +1 -0
  40. package/dist/hooks/tool-gate.d.ts +28 -0
  41. package/dist/hooks/tool-gate.d.ts.map +1 -0
  42. package/dist/hooks/tool-gate.js +152 -0
  43. package/dist/hooks/tool-gate.js.map +1 -0
  44. package/dist/index.d.ts +19 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +159 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/lib/complexity.d.ts +41 -0
  49. package/dist/lib/complexity.d.ts.map +1 -0
  50. package/dist/lib/complexity.js +67 -0
  51. package/dist/lib/complexity.js.map +1 -0
  52. package/dist/lib/context-refresh.d.ts +46 -0
  53. package/dist/lib/context-refresh.d.ts.map +1 -0
  54. package/dist/lib/context-refresh.js +77 -0
  55. package/dist/lib/context-refresh.js.map +1 -0
  56. package/dist/lib/index.d.ts +10 -0
  57. package/dist/lib/index.d.ts.map +1 -0
  58. package/dist/lib/index.js +10 -0
  59. package/dist/lib/index.js.map +1 -0
  60. package/dist/lib/logging.d.ts +13 -0
  61. package/dist/lib/logging.d.ts.map +1 -0
  62. package/dist/lib/logging.js +40 -0
  63. package/dist/lib/logging.js.map +1 -0
  64. package/dist/lib/persistence.d.ts +15 -0
  65. package/dist/lib/persistence.d.ts.map +1 -0
  66. package/dist/lib/persistence.js +62 -0
  67. package/dist/lib/persistence.js.map +1 -0
  68. package/dist/lib/planning-fs.d.ts +34 -0
  69. package/dist/lib/planning-fs.d.ts.map +1 -0
  70. package/dist/lib/planning-fs.js +134 -0
  71. package/dist/lib/planning-fs.js.map +1 -0
  72. package/dist/lib/sentiment.d.ts +31 -0
  73. package/dist/lib/sentiment.d.ts.map +1 -0
  74. package/dist/lib/sentiment.js +158 -0
  75. package/dist/lib/sentiment.js.map +1 -0
  76. package/dist/schemas/brain-state.d.ts +60 -0
  77. package/dist/schemas/brain-state.d.ts.map +1 -0
  78. package/dist/schemas/brain-state.js +176 -0
  79. package/dist/schemas/brain-state.js.map +1 -0
  80. package/dist/schemas/config.d.ts +51 -0
  81. package/dist/schemas/config.d.ts.map +1 -0
  82. package/dist/schemas/config.js +128 -0
  83. package/dist/schemas/config.js.map +1 -0
  84. package/dist/schemas/hierarchy.d.ts +22 -0
  85. package/dist/schemas/hierarchy.d.ts.map +1 -0
  86. package/dist/schemas/hierarchy.js +27 -0
  87. package/dist/schemas/hierarchy.js.map +1 -0
  88. package/dist/schemas/index.d.ts +7 -0
  89. package/dist/schemas/index.d.ts.map +1 -0
  90. package/dist/schemas/index.js +7 -0
  91. package/dist/schemas/index.js.map +1 -0
  92. package/dist/tools/compact-session.d.ts +15 -0
  93. package/dist/tools/compact-session.d.ts.map +1 -0
  94. package/dist/tools/compact-session.js +76 -0
  95. package/dist/tools/compact-session.js.map +1 -0
  96. package/dist/tools/declare-intent.d.ts +15 -0
  97. package/dist/tools/declare-intent.d.ts.map +1 -0
  98. package/dist/tools/declare-intent.js +83 -0
  99. package/dist/tools/declare-intent.js.map +1 -0
  100. package/dist/tools/index.d.ts +14 -0
  101. package/dist/tools/index.d.ts.map +1 -0
  102. package/dist/tools/index.js +14 -0
  103. package/dist/tools/index.js.map +1 -0
  104. package/dist/tools/map-context.d.ts +15 -0
  105. package/dist/tools/map-context.d.ts.map +1 -0
  106. package/dist/tools/map-context.js +85 -0
  107. package/dist/tools/map-context.js.map +1 -0
  108. package/dist/tools/self-rate.d.ts +15 -0
  109. package/dist/tools/self-rate.d.ts.map +1 -0
  110. package/dist/tools/self-rate.js +76 -0
  111. package/dist/tools/self-rate.js.map +1 -0
  112. package/package.json +71 -0
  113. package/src/cli/init.ts +214 -0
  114. package/src/cli.ts +178 -0
  115. package/src/dashboard/i18n/en.ts +43 -0
  116. package/src/dashboard/i18n/index.ts +20 -0
  117. package/src/dashboard/i18n/vi.ts +43 -0
  118. package/src/dashboard/server.ts +372 -0
  119. package/src/hooks/compaction.ts +104 -0
  120. package/src/hooks/index.ts +8 -0
  121. package/src/hooks/session-lifecycle.ts +133 -0
  122. package/src/hooks/tool-gate.ts +205 -0
  123. package/src/index.ts +206 -0
  124. package/src/lib/complexity.ts +96 -0
  125. package/src/lib/context-refresh.ts +107 -0
  126. package/src/lib/index.ts +10 -0
  127. package/src/lib/logging.ts +53 -0
  128. package/src/lib/persistence.ts +83 -0
  129. package/src/lib/planning-fs.ts +187 -0
  130. package/src/lib/sentiment.ts +183 -0
  131. package/src/schemas/brain-state.ts +257 -0
  132. package/src/schemas/config.ts +184 -0
  133. package/src/schemas/hierarchy.ts +58 -0
  134. package/src/schemas/index.ts +7 -0
  135. package/src/tools/compact-session.ts +97 -0
  136. package/src/tools/declare-intent.ts +104 -0
  137. package/src/tools/index.ts +14 -0
  138. package/src/tools/map-context.ts +105 -0
  139. package/src/tools/self-rate.ts +86 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,95 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.3.0] - 2026-02-11
9
+
10
+ ### Added
11
+ - **One-command install** — `npx hivemind-context-governance` sets up everything in one step
12
+ - **Auto-registration** — Plugin automatically registers itself in `opencode.json` during init (creates file if needed)
13
+ - Dual bin entries: both `npx hivemind-context-governance` and `npx hivemind` work
14
+ - `#!/usr/bin/env node` shebang for cross-platform npx compatibility
15
+ - `example-opencode.json` for SDK publishing checklist
16
+
17
+ ### Changed
18
+ - CLI default command changed from `help` to `init` — bare `npx` invocation runs setup
19
+ - Dashboard import changed to lazy `await import()` — prevents crash when dashboard deps unavailable
20
+ - Moved sentiment detection from `experimental.chat.system.transform` to `chat.message` hook (SDK compatibility)
21
+ - Removed explicit hook type annotations — let TypeScript infer from SDK
22
+ - Removed manual "add to opencode.json" instructions — it's automatic now
23
+ - peerDependencies `@opencode-ai/plugin` changed from `^0.x` to `*` (any version)
24
+
25
+ ### Fixed
26
+ - Config key corrected from `"plugins"` (plural) to `"plugin"` (singular) per OpenCode spec
27
+ - Removed dead peer deps (`@opentui/react`, `@opentui/core`, `react`)
28
+ - Added `@opencode-ai/plugin` to devDependencies (was only in peerDependencies)
29
+
30
+ ## [1.2.1] - 2026-02-11
31
+
32
+ ### Fixed
33
+ - **Plugin install broken** — `dist/` was gitignored so clones had no `main` entry. Fixed by including `src/` in npm package and documenting `file://` path for TypeScript-direct loading.
34
+ - **@opencode-ai/plugin SDK compatibility** — Updated hook signatures for latest SDK: `experimental.chat.system.transform` now accepts `{ sessionID?: string; model: Model }`, removed deprecated `message` field.
35
+ - **Sentiment detection moved** — From `experimental.chat.system.transform` (which lost `message` param) to new `chat.message` hook, where user message content is actually available.
36
+ - **Dead peer dependencies** — Removed `@opentui/react`, `@opentui/core`, `react` from peer deps (never used).
37
+
38
+ ### Changed
39
+ - **Config key** — README and init output now correctly show `"plugin"` (singular) instead of `"plugins"` (plural) per OpenCode spec.
40
+ - **Installation docs** — Rewrote README Quick Start with `file://` path (works now) and npm path (after publish).
41
+ - Added `example-opencode.json` for copy-paste setup.
42
+ - Added `clean` and `prepublishOnly` scripts.
43
+ - Version bump to 1.2.1.
44
+
45
+ ## [1.2.0] - 2026-02-11
46
+
47
+ ### Fixed
48
+ - **initProject() guard** — Now checks `brain.json` existence instead of just directory, preventing false "already initialized" when logger creates directory as side-effect (fixed 7 test failures)
49
+ - **self_rate score threshold** — Score 7 now correctly shows drift hint (💡) instead of positive feedback (✅) (fixed 1 test failure)
50
+ - **Sentiment false positives** — Negative keyword detection now uses word-boundary regex with negative-lookahead for benign phrases ("no issues", "error handling", etc.)
51
+
52
+ ### Changed
53
+ - **Removed process.cwd() backward-compat exports** — All 4 tool files no longer export landmine constants that captured directory at import-time instead of runtime
54
+ - **Package metadata** — Repository URLs now point to `shynlee04/hivemind-plugin`, `@opencode-ai/plugin` moved from dependency to peerDependency (required, not optional)
55
+ - **Tool barrel exports** — Updated to export only factory functions (`createXxxTool`)
56
+
57
+ ## [1.1.0] - 2026-02-10
58
+
59
+ ### Added
60
+ - **self_rate tool** - Agents can now rate their own performance (1-10 scale) with optional context
61
+ - **Auto-rating system** - Automatic health score tracking based on tool success rates
62
+ - **Sentiment detection** - Detects negative signals ("stop", "wrong", "confused") and agent failure phrases
63
+ - **Context refresh trigger** - Automatically suggests compaction when drift is detected (2 negative signals within 5 turns)
64
+ - **Complexity detection** - Tracks files touched and turn count since last intent declaration
65
+ - **Complexity nudges** - Gentle console reminders when complexity thresholds are exceeded
66
+ - **GitHub Actions CI** - Automated testing on Node 18 and 20
67
+
68
+ ### Changed
69
+ - Updated package.json with proper npm publishing configuration
70
+ - Added LICENSE file (MIT)
71
+ - Added this CHANGELOG.md
72
+
73
+ ## [1.0.0] - 2026-02-08
74
+
75
+ ### Added
76
+ - **3 lifecycle tools**: declare_intent, map_context, compact_session
77
+ - **3 governance hooks**: tool.execute.before, chat.system.transform, session.compacting
78
+ - **3 governance modes**: strict, assisted, permissive
79
+ - **3-level hierarchy**: Trajectory → Tactic → Action
80
+ - **State management**: brain.json, active.md, index.md
81
+ - **Session archiving**: Automatic compaction and history tracking
82
+ - **Configuration system**: HiveMindConfig with agent behavior settings
83
+ - **TUI-safe logging**: File-based logging, no console.log
84
+ - **Test suite**: 76 assertions across schema, init, and tool-gate tests
85
+
86
+ ### Features
87
+ - Soft governance with configurable enforcement levels
88
+ - Agent behavior configuration (language, expert level, output style)
89
+ - Drift detection and warnings
90
+ - Session lifecycle management
91
+ - Planning directory structure (.opencode/planning/)
92
+
93
+ [1.2.0]: https://github.com/shynlee04/hivemind-plugin/compare/v1.1.0...v1.2.0
94
+ [1.1.0]: https://github.com/shynlee04/hivemind-plugin/compare/v1.0.0...v1.1.0
95
+ [1.0.0]: https://github.com/shynlee04/hivemind-plugin/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HiveMind Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # HiveMind Context Governance
2
+
3
+ A lightweight context-aware governance layer for OpenCode that prevents drift and manages session state across lifecycles.
4
+
5
+ ## What is HiveMind?
6
+
7
+ HiveMind provides **soft governance** for AI-assisted development — it tracks context, warns about drift, and maintains session state without hard-blocking your workflow.
8
+
9
+ ### Key Features
10
+
11
+ - **3-Level Hierarchy**: Trajectory → Tactic → Action
12
+ - **3 Governance Modes**: Strict, Assisted, Permissive
13
+ - **4 Lifecycle Tools**: declare_intent, map_context, compact_session, self_rate
14
+ - **Session Archiving**: Automatic compaction and history tracking
15
+ - **Drift Detection**: Warnings when context goes stale
16
+ - **Sentiment Detection**: Automatic detection of negative signals and confusion
17
+ - **Complexity Nudges**: Gentle warnings when sessions get complex (3+ files or 5+ turns)
18
+ - **Self-Rating**: Agent self-assessment for drift tracking (1-10 scale)
19
+
20
+ ## Installation
21
+
22
+ One command. That's it.
23
+
24
+ ```bash
25
+ npx hivemind-context-governance
26
+ ```
27
+
28
+ This does everything:
29
+ 1. Creates `.opencode/planning/` with session state files
30
+ 2. Registers HiveMind in your `opencode.json` automatically
31
+ 3. Next time you open OpenCode, HiveMind is active
32
+
33
+ > **No cloning. No manual JSON editing. No `npm install`.** OpenCode auto-installs npm plugins at runtime.
34
+
35
+ ### Options
36
+
37
+ ```bash
38
+ npx hivemind-context-governance --mode strict --lang en
39
+ ```
40
+
41
+ | Option | Values | Default |
42
+ |--------|--------|---------|
43
+ | `--mode` | `strict`, `assisted`, `permissive` | `assisted` |
44
+ | `--lang` | `en`, `vi` | `en` |
45
+
46
+ ### Other CLI Commands
47
+
48
+ ```bash
49
+ npx hivemind-context-governance status # Show current state
50
+ npx hivemind-context-governance compact # Manual compaction info
51
+ npx hivemind-context-governance help # Show help
52
+ ```
53
+
54
+ ## Using the Tools
55
+
56
+ Within OpenCode, use the 4 lifecycle tools:
57
+
58
+ ```typescript
59
+ // Start a session
60
+ declare_intent({
61
+ mode: "plan_driven",
62
+ focus: "Implement user authentication"
63
+ })
64
+
65
+ // Update context
66
+ map_context({
67
+ level: "tactic",
68
+ content: "Set up JWT middleware",
69
+ status: "active"
70
+ })
71
+
72
+ // Rate your performance (self-assessment)
73
+ self_rate({
74
+ score: 8,
75
+ reason: "Making good progress on auth flow",
76
+ turn_context: "Currently testing JWT validation"
77
+ })
78
+
79
+ // Archive and reset
80
+ compact_session({
81
+ summary: "Auth system foundation complete"
82
+ })
83
+ ```
84
+
85
+ ## Governance Modes
86
+
87
+ | Mode | Behavior | Use Case |
88
+ |------|----------|----------|
89
+ | **strict** | Session starts LOCKED. Must call `declare_intent` before writes. | High-compliance projects |
90
+ | **assisted** | Session starts OPEN. Warnings logged but not blocking. | Balanced guidance |
91
+ | **permissive** | Session always OPEN. Silent tracking only. | Maximum autonomy |
92
+
93
+ ## Project Structure
94
+
95
+ After initialization:
96
+
97
+ ```
98
+ .opencode/planning/
99
+ ├── index.md # Project trajectory
100
+ ├── active.md # Current session
101
+ ├── brain.json # Machine state
102
+ ├── config.json # Settings
103
+ └── archive/ # Session history
104
+ └── session_2026-02-10_xxx.md
105
+ ```
106
+
107
+ ## Sentiment Detection
108
+
109
+ HiveMind automatically detects negative signals in user messages and agent responses:
110
+
111
+ **Detected Patterns:**
112
+ - **Negative keywords**: stop, wrong, no, bad, incorrect, confused, mistake, error
113
+ - **Agent failure phrases**: "I apologize", "you are right", "I was wrong", "my mistake"
114
+ - **Cancellation patterns**: cancel, abort, start over, scratch that, never mind
115
+ - **Confusion indicators**: "I'm confused", "doesn't make sense", "unclear"
116
+
117
+ **Trigger Threshold:**
118
+ - 2 negative signals within 5 turns triggers a drift warning
119
+ - Warning logged to TUI: `[ContextRefresh] Drift detected. Consider compact_session.`
120
+ - Warning added to `active.md` for visibility
121
+
122
+ ## Complexity Nudges
123
+
124
+ When sessions get complex, HiveMind provides gentle nudges:
125
+
126
+ **Thresholds (configurable):**
127
+ - 3+ unique files touched, OR
128
+ - 5+ turns since last `declare_intent`
129
+
130
+ **Behavior:**
131
+ - One nudge per session (deduplicated)
132
+ - Resets when new intent is declared
133
+ - Logs: `[Nudge] Complexity rising (X files, Y turns). Consider declare_intent.`
134
+
135
+ ## Architecture
136
+
137
+ ```
138
+ ┌─────────────────────────────────────────┐
139
+ │ OpenCode Agent │
140
+ └─────────────┬───────────────────────────┘
141
+
142
+ ┌─────────────▼───────────────────────────┐
143
+ │ HiveMind Plugin (3 hooks) │
144
+ │ ├─ tool.execute.before (governance) │
145
+ │ ├─ chat.message (sentiment detection) │
146
+ │ └─ experimental.session.compacting │
147
+ └─────────────┬───────────────────────────┘
148
+
149
+ ┌─────────────▼───────────────────────────┐
150
+ │ 4 Lifecycle Tools │
151
+ │ ├─ declare_intent │
152
+ │ ├─ map_context │
153
+ │ ├─ compact_session │
154
+ │ └─ self_rate │
155
+ └─────────────┬───────────────────────────┘
156
+
157
+ ┌─────────────▼───────────────────────────┐
158
+ │ State Management │
159
+ │ ├─ brain.json (runtime state) │
160
+ │ ├─ active.md (session focus) │
161
+ │ └─ index.md (project trajectory) │
162
+ └─────────────────────────────────────────┘
163
+ ```
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ # Install dependencies
169
+ npm install
170
+
171
+ # Run tests
172
+ npm test
173
+
174
+ # Type check
175
+ npm run typecheck
176
+
177
+ # Build
178
+ npm run build
179
+
180
+ # Watch mode
181
+ npm run dev
182
+ ```
183
+
184
+ ## Test Coverage
185
+
186
+ | Component | Assertions | Status |
187
+ |-----------|-----------|--------|
188
+ | Schema (BrainState, Hierarchy) | 35 | ✅ Pass |
189
+ | Init + Planning FS | 29 | ✅ Pass |
190
+ | Tool Gate (governance) | 12 | ✅ Pass |
191
+ | Self-Rate Tool | 28 | ✅ Pass |
192
+ | Integration Tests | 27 | ✅ Pass |
193
+ | **Total** | **131** | ✅ **All Pass** |
194
+
195
+ ## Requirements
196
+
197
+ - Node.js 18+
198
+ - OpenCode with plugin support
199
+
200
+ ## Design Philosophy
201
+
202
+ | Principle | Description |
203
+ |-----------|-------------|
204
+ | **Lightweight** | 4 tools, 3 hooks — minimal surface area |
205
+ | **User-driven** | No agent hierarchy — you control the workflow |
206
+ | **Soft enforcement** | Warns and logs, never hard-blocks |
207
+ | **Session brain** | Every session is archived and traceable |
208
+ | **Drift-aware** | Automatic detection via sentiment + complexity |
209
+ | **Self-assessment** | Built-in 1-10 scale rating for agent self-awareness |
210
+
211
+ ## Documentation
212
+
213
+ - [AGENTS.md](./AGENTS.md) — Complete guide for agents using the tools
214
+ - [CHANGELOG.md](./CHANGELOG.md) — Release history
215
+
216
+ ## License
217
+
218
+ MIT
@@ -0,0 +1,23 @@
1
+ /**
2
+ * HiveMind Init — One-command project initialization.
3
+ *
4
+ * Creates:
5
+ * - .opencode/planning/ directory structure
6
+ * - index.md with template
7
+ * - active.md with LOCKED status
8
+ * - brain.json with initial state
9
+ * - config.json with governance preferences
10
+ * - Auto-registers plugin in opencode.json
11
+ */
12
+ import type { GovernanceMode, Language, ExpertLevel, OutputStyle } from "../schemas/config.js";
13
+ export interface InitOptions {
14
+ language?: Language;
15
+ governanceMode?: GovernanceMode;
16
+ expertLevel?: ExpertLevel;
17
+ outputStyle?: OutputStyle;
18
+ requireCodeReview?: boolean;
19
+ enforceTdd?: boolean;
20
+ silent?: boolean;
21
+ }
22
+ export declare function initProject(directory: string, options?: InitOptions): Promise<void>;
23
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/cli/init.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAM9F,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,QAAQ,CAAA;IACnB,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAyDD,wBAAsB,WAAW,CAC/B,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,IAAI,CAAC,CA6Hf"}
@@ -0,0 +1,175 @@
1
+ /**
2
+ * HiveMind Init — One-command project initialization.
3
+ *
4
+ * Creates:
5
+ * - .opencode/planning/ directory structure
6
+ * - index.md with template
7
+ * - active.md with LOCKED status
8
+ * - brain.json with initial state
9
+ * - config.json with governance preferences
10
+ * - Auto-registers plugin in opencode.json
11
+ */
12
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { createConfig, isValidGovernanceMode, isValidLanguage, isValidExpertLevel, isValidOutputStyle } from "../schemas/config.js";
15
+ import { createBrainState, generateSessionId } from "../schemas/brain-state.js";
16
+ import { createStateManager, saveConfig } from "../lib/persistence.js";
17
+ import { initializePlanningDirectory } from "../lib/planning-fs.js";
18
+ // eslint-disable-next-line no-console
19
+ const log = (msg) => console.log(msg);
20
+ const PLUGIN_NAME = "hivemind-context-governance";
21
+ /**
22
+ * Auto-register the HiveMind plugin in opencode.json.
23
+ * Creates the file if it doesn't exist.
24
+ * Adds the plugin if not already registered.
25
+ */
26
+ function registerPluginInConfig(directory, silent) {
27
+ const configPath = join(directory, "opencode.json");
28
+ let config = {};
29
+ if (existsSync(configPath)) {
30
+ try {
31
+ const raw = readFileSync(configPath, "utf-8");
32
+ config = JSON.parse(raw);
33
+ }
34
+ catch {
35
+ // Malformed JSON — overwrite
36
+ config = {};
37
+ }
38
+ }
39
+ // Ensure plugin array exists
40
+ if (!Array.isArray(config.plugin)) {
41
+ config.plugin = [];
42
+ }
43
+ const plugins = config.plugin;
44
+ // Check if already registered (exact match or versioned match)
45
+ const alreadyRegistered = plugins.some((p) => p === PLUGIN_NAME || p.startsWith(PLUGIN_NAME + "@"));
46
+ if (alreadyRegistered) {
47
+ if (!silent) {
48
+ log(` ✓ Plugin already registered in opencode.json`);
49
+ }
50
+ return;
51
+ }
52
+ plugins.push(PLUGIN_NAME);
53
+ config.plugin = plugins;
54
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
55
+ if (!silent) {
56
+ log(` ✓ Plugin registered in opencode.json`);
57
+ log(` → OpenCode will auto-install on next launch`);
58
+ }
59
+ }
60
+ export async function initProject(directory, options = {}) {
61
+ const planningDir = join(directory, ".opencode", "planning");
62
+ const brainPath = join(planningDir, "brain.json");
63
+ // Guard: Check brain.json existence, not just directory.
64
+ // The directory may exist from logger side-effects without full initialization.
65
+ if (existsSync(brainPath)) {
66
+ if (!options.silent) {
67
+ log("⚠ HiveMind already initialized in this project.");
68
+ log(` Directory: ${planningDir}`);
69
+ log(" Use 'npx hivemind-context-governance status' to see current state.");
70
+ }
71
+ return;
72
+ }
73
+ if (!options.silent) {
74
+ log("");
75
+ log("🐝 HiveMind Context Governance — Initialization");
76
+ log("─".repeat(48));
77
+ }
78
+ // Validate and set governance mode
79
+ const governanceMode = options.governanceMode ?? "assisted";
80
+ if (!isValidGovernanceMode(governanceMode)) {
81
+ log(`✗ Invalid governance mode: ${governanceMode}`);
82
+ log(" Valid: permissive, assisted, strict");
83
+ return;
84
+ }
85
+ // Validate and set language
86
+ const language = options.language ?? "en";
87
+ if (!isValidLanguage(language)) {
88
+ log(`✗ Invalid language: ${language}`);
89
+ log(" Valid: en, vi");
90
+ return;
91
+ }
92
+ // Validate and set expert level
93
+ const expertLevel = options.expertLevel ?? "intermediate";
94
+ if (!isValidExpertLevel(expertLevel)) {
95
+ log(`✗ Invalid expert level: ${expertLevel}`);
96
+ log(" Valid: beginner, intermediate, advanced, expert");
97
+ return;
98
+ }
99
+ // Validate and set output style
100
+ const outputStyle = options.outputStyle ?? "explanatory";
101
+ if (!isValidOutputStyle(outputStyle)) {
102
+ log(`✗ Invalid output style: ${outputStyle}`);
103
+ log(" Valid: explanatory, outline, skeptical, architecture, minimal");
104
+ return;
105
+ }
106
+ // Create config with agent behavior
107
+ const config = createConfig({
108
+ governance_mode: governanceMode,
109
+ language,
110
+ agent_behavior: {
111
+ language,
112
+ expert_level: expertLevel,
113
+ output_style: outputStyle,
114
+ constraints: {
115
+ require_code_review: options.requireCodeReview ?? false,
116
+ enforce_tdd: options.enforceTdd ?? false,
117
+ max_response_tokens: 2000,
118
+ explain_reasoning: true,
119
+ be_skeptical: outputStyle === "skeptical",
120
+ },
121
+ },
122
+ });
123
+ if (!options.silent) {
124
+ log(` Governance: ${governanceMode}`);
125
+ log(` Language: ${language}`);
126
+ log(` Expert Level: ${expertLevel}`);
127
+ log(` Output Style: ${outputStyle}`);
128
+ if (options.requireCodeReview)
129
+ log(" ✓ Code review required");
130
+ if (options.enforceTdd)
131
+ log(" ✓ TDD enforced");
132
+ log("");
133
+ }
134
+ // Create planning directory structure
135
+ if (!options.silent) {
136
+ log("Creating planning directory...");
137
+ }
138
+ await initializePlanningDirectory(directory);
139
+ // Save config
140
+ await saveConfig(directory, config);
141
+ // Initialize brain state
142
+ const stateManager = createStateManager(directory);
143
+ const sessionId = generateSessionId();
144
+ const state = createBrainState(sessionId, config);
145
+ await stateManager.save(state);
146
+ // Auto-register plugin in opencode.json
147
+ registerPluginInConfig(directory, options.silent ?? false);
148
+ if (!options.silent) {
149
+ log("");
150
+ log("✓ Planning directory created:");
151
+ log(` ${planningDir}/`);
152
+ log(" ├── index.md (project trajectory)");
153
+ log(" ├── active.md (current session)");
154
+ log(" ├── brain.json (machine state)");
155
+ log(" ├── config.json (governance settings)");
156
+ log(" └── archive/ (completed sessions)");
157
+ log("");
158
+ log(`Session ${sessionId} initialized.`);
159
+ log(`Status: ${state.session.governance_status}`);
160
+ log("");
161
+ if (governanceMode === "strict") {
162
+ log("🔒 STRICT MODE — agents must call declare_intent before writing.");
163
+ }
164
+ else if (governanceMode === "assisted") {
165
+ log("🔔 ASSISTED MODE — agents get warnings but can proceed.");
166
+ }
167
+ else {
168
+ log("🟢 PERMISSIVE MODE — agents work freely, activity tracked.");
169
+ }
170
+ log("");
171
+ log("✅ Done! Open OpenCode in this project — HiveMind is active.");
172
+ log("");
173
+ }
174
+ }
175
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../../src/cli/init.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,eAAe,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AACnI,OAAO,EAAE,gBAAgB,EAA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C/C,GAAG,CAAC,uCAAuC,CAAC,CAAA;QAC5C,GAAG,CAAC,qCAAqC,CAAC,CAAA;QAC1C,GAAG,CAAC,2CAA2C,CAAC,CAAA;QAChD,GAAG,CAAC,0CAA0C,CAAC,CAAA;QAC/C,GAAG,CAAC,EAAE,CAAC,CAAA;QACP,GAAG,CAAC,WAAW,SAAS,eAAe,CAAC,CAAA;QACxC,GAAG,CAAC,WAAW,KAAK,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAA;QACjD,GAAG,CAAC,EAAE,CAAC,CAAA;QAEP,IAAI,cAAc,KAAK,QAAQ,EAAE,CAAC;YAChC,GAAG,CAAC,kEAAkE,CAAC,CAAA;QACzE,CAAC;aAAM,IAAI,cAAc,KAAK,UAAU,EAAE,CAAC;YACzC,GAAG,CAAC,yDAAyD,CAAC,CAAA;QAChE,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,4DAA4D,CAAC,CAAA;QACnE,CAAC;QAED,GAAG,CAAC,EAAE,CAAC,CAAA;QACP,GAAG,CAAC,6DAA6D,CAAC,CAAA;QAClE,GAAG,CAAC,EAAE,CAAC,CAAA;IACT,CAAC;AACH,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * HiveMind CLI — One-command initialization and management.
4
+ *
5
+ * Usage:
6
+ * npx hivemind-context-governance — Initialize (default)
7
+ * npx hivemind-context-governance init — Same as above
8
+ * npx hivemind-context-governance status — Show current brain state
9
+ *
10
+ * CRITICAL: NO console.log in library code. CLI is the ONLY
11
+ * place where console output is allowed (it IS the user interface).
12
+ */
13
+ export {};
14
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;GAUG"}