doukui 0.0.0-stage → 0.3.1

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1443 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1411 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +588 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +415 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-lint.js +100 -0
  118. package/plugins/runtime/plan-reader.js +763 -0
  119. package/plugins/runtime/plugin-loader.js +798 -0
  120. package/plugins/runtime/plugin-trust.js +182 -0
  121. package/plugins/runtime/plugin-validator.js +491 -0
  122. package/plugins/runtime/provider-failover.js +114 -0
  123. package/plugins/runtime/provider-resolver.js +342 -0
  124. package/plugins/runtime/reflection-evaluator.js +545 -0
  125. package/plugins/runtime/resolve-plugin-path.js +297 -0
  126. package/plugins/runtime/safe-path.js +119 -0
  127. package/plugins/runtime/sandbox-context.js +235 -0
  128. package/plugins/runtime/sandbox-manager.js +609 -0
  129. package/plugins/runtime/sandbox-worker.js +215 -0
  130. package/plugins/runtime/self-rescue-ladder.js +38 -0
  131. package/plugins/runtime/settings-merger.js +172 -0
  132. package/plugins/runtime/state-store.js +527 -0
  133. package/plugins/runtime/team-cleanup.js +497 -0
  134. package/plugins/runtime/text-tokenize.js +25 -0
  135. package/plugins/runtime/validator-pipeline.js +475 -0
  136. package/plugins/runtime/yaml-parser.js +692 -0
  137. package/templates/harness-config.yaml +394 -0
@@ -0,0 +1,293 @@
1
+ /**
2
+ * cleanup-utils - Shared cleanup utility functions
3
+ *
4
+ * Extracted from commands/init.js and commands/migrate.js to eliminate
5
+ * ~125 lines of duplicated cleanup logic. Provides functions for
6
+ * detecting and removing legacy project-level hooks, skills, and
7
+ * empty directories.
8
+ *
9
+ * Hook names are derived dynamically from plugin-registry.json
10
+ * instead of being hardcoded.
11
+ *
12
+ * @module cleanup-utils
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ var path = require('path');
18
+ var fs = require('fs');
19
+ var safePath = require('./safe-path');
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Hook name derivation from registry
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /**
26
+ * Get hook plugin names from the plugin registry.
27
+ * Reads plugin-registry.json and filters plugins with type 'hook'.
28
+ *
29
+ * @public
30
+ * @param {string} registryPath - Path to plugin-registry.json
31
+ * @param {string} packageRoot - Root directory of doukui package
32
+ * @returns {string[]} Array of hook plugin names (e.g. ['hook-skill-gate', 'hook-session-start'])
33
+ */
34
+ function getHookNamesFromRegistry(registryPath, packageRoot) {
35
+ var hookNames = [];
36
+ var registry;
37
+ try {
38
+ registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
39
+ } catch (e) {
40
+ return hookNames;
41
+ }
42
+
43
+ var plugins = registry.plugins || [];
44
+ for (var i = 0; i < plugins.length; i++) {
45
+ var p = plugins[i];
46
+ var metaPath = path.join(packageRoot, 'plugins', 'core', p.source || p.name, 'plugin.json');
47
+ if (fs.existsSync(metaPath)) {
48
+ try {
49
+ var meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
50
+ if (meta.type === 'hook') {
51
+ hookNames.push(meta.name || p.name);
52
+ }
53
+ } catch (e) {
54
+ // skip unparseable plugin metadata
55
+ }
56
+ }
57
+ }
58
+
59
+ return hookNames;
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Legacy detection helpers
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * Check if a hook command uses a relative path (legacy local install).
68
+ * Includes WP-168 fix: excludes absolute Unix paths (node "/...").
69
+ *
70
+ * @public
71
+ * @param {string} command - The hook command string to check
72
+ * @returns {boolean} true if the command appears to be a legacy local hook
73
+ */
74
+ function isLegacyLocalHook(command) {
75
+ if (!command) return false;
76
+ return command.indexOf('../') !== -1 || command.indexOf('..\\') !== -1 ||
77
+ (command.indexOf('node "') === 0 && !/[a-zA-Z]:/.test(command) && command.indexOf('./') === -1 && command.indexOf('node "/') !== 0);
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Settings hook cleanup
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /**
85
+ * Clean up legacy project-level hooks from settings.json.
86
+ * Removes hook entries that reference legacy local install paths.
87
+ *
88
+ * @public
89
+ * @param {object} settings - Parsed settings.json object (mutated in place)
90
+ * @returns {{ settings: object, hadProjectHooks: boolean }}
91
+ */
92
+ function cleanupSettingsHooks(settings) {
93
+ var hadProjectHooks = false;
94
+
95
+ // Check for PreToolUse hooks (Edit|Write gate)
96
+ if (settings.hooks && settings.hooks.PreToolUse && settings.hooks.PreToolUse.length > 0) {
97
+ var preMatcher = 'Edit|Write';
98
+ for (var i = 0; i < settings.hooks.PreToolUse.length; i++) {
99
+ if (settings.hooks.PreToolUse[i].matcher === preMatcher) {
100
+ var hookCmd = settings.hooks.PreToolUse[i].hooks && settings.hooks.PreToolUse[i].hooks[0] && settings.hooks.PreToolUse[i].hooks[0].command;
101
+ if (isLegacyLocalHook(hookCmd)) {
102
+ settings.hooks.PreToolUse.splice(i, 1);
103
+ i--;
104
+ hadProjectHooks = true;
105
+ }
106
+ }
107
+ }
108
+ }
109
+
110
+ // Check for PostToolUse hooks (Skill gate)
111
+ if (settings.hooks && settings.hooks.PostToolUse && settings.hooks.PostToolUse.length > 0) {
112
+ var postMatcher = 'Skill';
113
+ for (var j = 0; j < settings.hooks.PostToolUse.length; j++) {
114
+ if (settings.hooks.PostToolUse[j].matcher === postMatcher) {
115
+ var hookCmd = settings.hooks.PostToolUse[j].hooks && settings.hooks.PostToolUse[j].hooks[0] && settings.hooks.PostToolUse[j].hooks[0].command;
116
+ if (isLegacyLocalHook(hookCmd)) {
117
+ settings.hooks.PostToolUse.splice(j, 1);
118
+ j--;
119
+ hadProjectHooks = true;
120
+ }
121
+ }
122
+ }
123
+ }
124
+
125
+ // Check for SessionStart hooks (plan-mode rules)
126
+ if (settings.hooks && settings.hooks.SessionStart && settings.hooks.SessionStart.length > 0) {
127
+ var sessionMatcher = 'startup|clear|compact';
128
+ for (var k = 0; k < settings.hooks.SessionStart.length; k++) {
129
+ if (settings.hooks.SessionStart[k].matcher === sessionMatcher) {
130
+ var hookCmd = settings.hooks.SessionStart[k].hooks && settings.hooks.SessionStart[k].hooks[0] && settings.hooks.SessionStart[k].hooks[0].command;
131
+ if (isLegacyLocalHook(hookCmd)) {
132
+ settings.hooks.SessionStart.splice(k, 1);
133
+ k--;
134
+ hadProjectHooks = true;
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ return { settings: settings, hadProjectHooks: hadProjectHooks };
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // Project skills cleanup
145
+ // ---------------------------------------------------------------------------
146
+
147
+ /**
148
+ * Clean up legacy project-level skills directory.
149
+ * Removes skills that are now available globally (registered in plugin-registry.json).
150
+ *
151
+ * @public
152
+ * @param {string} projectSkillsDir - Path to .claude/skills/
153
+ * @param {string} registryPath - Path to plugin-registry.json
154
+ * @param {string} packageRoot - Root directory of doukui package
155
+ * @returns {string[]} Array of removed skill names
156
+ */
157
+ function cleanupProjectSkills(projectSkillsDir, registryPath, packageRoot) {
158
+ var removedSkills = [];
159
+
160
+ if (!fs.existsSync(projectSkillsDir)) {
161
+ return removedSkills;
162
+ }
163
+
164
+ try {
165
+ var registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
166
+ var globalSkillNames = {};
167
+
168
+ for (var m = 0; m < registry.plugins.length; m++) {
169
+ var p = registry.plugins[m];
170
+ var metaPath = path.join(packageRoot, 'plugins', 'core', p.source || p.name, 'plugin.json');
171
+ if (fs.existsSync(metaPath)) {
172
+ try {
173
+ var meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
174
+ if (meta.type === 'skill') {
175
+ var fullName = meta.name || p.name;
176
+ globalSkillNames[fullName] = true;
177
+ if (fullName.indexOf('skill-') === 0) {
178
+ var shortName = fullName.substring(6);
179
+ globalSkillNames[shortName] = true;
180
+ }
181
+ }
182
+ } catch (e) {
183
+ // skip unparseable plugins
184
+ }
185
+ }
186
+ }
187
+
188
+ var projectSkills = fs.readdirSync(projectSkillsDir);
189
+
190
+ for (var n = 0; n < projectSkills.length; n++) {
191
+ var skillName = projectSkills[n];
192
+ var skillPath = path.join(projectSkillsDir, skillName);
193
+
194
+ if (globalSkillNames[skillName]) {
195
+ // S5:拒绝符号链接/junction,避免 rmSync(recursive) 顺着链接递归删除目标。
196
+ // .claude/skills/ 下的合法 skill 都是普通目录,不应为 symlink。
197
+ if (safePath.isSymlink(skillPath)) {
198
+ continue;
199
+ }
200
+ fs.rmSync(skillPath, { recursive: true, force: true });
201
+ removedSkills.push(skillName);
202
+ }
203
+ }
204
+ } catch (err) {
205
+ // Return whatever was removed so far
206
+ }
207
+
208
+ return removedSkills;
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // Project hooks cleanup
213
+ // ---------------------------------------------------------------------------
214
+
215
+ /**
216
+ * Clean up legacy project-level hooks directory.
217
+ * Removes hook directories that are now available globally.
218
+ * Uses getHookNamesFromRegistry to derive hook names dynamically.
219
+ *
220
+ * @public
221
+ * @param {string} projectHooksDir - Path to .claude/hooks/
222
+ * @param {string} registryPath - Path to plugin-registry.json
223
+ * @param {string} packageRoot - Root directory of doukui package
224
+ * @returns {string[]} Array of removed hook names
225
+ */
226
+ function cleanupProjectHooks(projectHooksDir, registryPath, packageRoot) {
227
+ var removedHooks = [];
228
+
229
+ if (!fs.existsSync(projectHooksDir)) {
230
+ return removedHooks;
231
+ }
232
+
233
+ try {
234
+ var doukuiHooks = getHookNamesFromRegistry(registryPath, packageRoot);
235
+
236
+ // Directly remove known hook paths instead of readdirSync+statSync loop
237
+ for (var i = 0; i < doukuiHooks.length; i++) {
238
+ var hookPath = path.join(projectHooksDir, doukuiHooks[i]);
239
+ if (fs.existsSync(hookPath)) {
240
+ // S5:拒绝符号链接/junction,避免 rmSync(recursive) 删除链接目标
241
+ if (safePath.isSymlink(hookPath)) {
242
+ continue;
243
+ }
244
+ fs.rmSync(hookPath, { recursive: true, force: true });
245
+ removedHooks.push(doukuiHooks[i]);
246
+ }
247
+ }
248
+ } catch (err) {
249
+ // Return whatever was removed so far
250
+ }
251
+
252
+ return removedHooks;
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Empty directory removal
257
+ // ---------------------------------------------------------------------------
258
+
259
+ /**
260
+ * Remove a directory if it is empty.
261
+ * No-op if the directory does not exist or is not empty.
262
+ *
263
+ * @public
264
+ * @param {string} dirPath - Path to the directory to potentially remove
265
+ * @returns {boolean} true if the directory was removed, false otherwise
266
+ */
267
+ function removeEmptyDir(dirPath) {
268
+ try {
269
+ if (fs.existsSync(dirPath)) {
270
+ var entries = fs.readdirSync(dirPath);
271
+ if (entries.length === 0) {
272
+ fs.rmdirSync(dirPath);
273
+ return true;
274
+ }
275
+ }
276
+ } catch (e) {
277
+ // directory not empty or other error, leave it
278
+ }
279
+ return false;
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // Module exports
284
+ // ---------------------------------------------------------------------------
285
+
286
+ module.exports = {
287
+ isLegacyLocalHook: isLegacyLocalHook,
288
+ cleanupSettingsHooks: cleanupSettingsHooks,
289
+ cleanupProjectSkills: cleanupProjectSkills,
290
+ cleanupProjectHooks: cleanupProjectHooks,
291
+ removeEmptyDir: removeEmptyDir,
292
+ getHookNamesFromRegistry: getHookNamesFromRegistry
293
+ };
@@ -0,0 +1,317 @@
1
+ /**
2
+ * ConfigManager - Three-layer configuration management for AI Agent Harness
3
+ *
4
+ * @module config-manager
5
+ *
6
+ * Layer precedence (highest wins):
7
+ * 1. Environment variables (HARNESS_<KEY>)
8
+ * 2. harness-config.yaml (user/project-level)
9
+ * 3. plugin defaults (built into each plugin)
10
+ *
11
+ * Supports:
12
+ * - get(key) with dot-notation
13
+ * - getForPlugin(pluginName, key) with per-plugin override
14
+ * - setOverride(key, value) runtime override
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ var fs = require('fs');
20
+ var path = require('path');
21
+
22
+ /**
23
+ * Minimal YAML-like parser for simple key-value YAML files.
24
+ *
25
+ * S8/A3: this delegates to the shared `yaml-parser.parseSimpleYaml`, which
26
+ * consolidates the 5 divergent YAML parsers that previously existed in the
27
+ * codebase (config-manager, config-validator, hook-skill-gate,
28
+ * provider-role-registry, and yaml-parser). The shared parser:
29
+ * - enforces MAX_YAML_SIZE / MAX_DEPTH (DoS guard the old copies lacked)
30
+ * - correctly parses top-level scalar arrays (B4 fix: `triggers:\n - foo`
31
+ * previously parsed to `{}` empty object, losing data)
32
+ * - handles list-of-objects, nested objects, quoted strings, comments
33
+ * The local `parseValue` is kept only for the env-var resolution path in
34
+ * get(); YAML parsing now goes through the shared helper.
35
+ * @internal
36
+ */
37
+ function parseSimpleYaml(content) {
38
+ // Re-require lazily to avoid a circular import at module-load time
39
+ // (yaml-parser does not require config-manager, but keep it lazy for safety).
40
+ var sharedParser = require('./yaml-parser');
41
+ try {
42
+ return sharedParser.parseSimpleYaml(content);
43
+ } catch (_e) {
44
+ // Oversize / over-depth → treat as empty config (do not crash callers)
45
+ return {};
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Parse a YAML scalar value.
51
+ * B12: require length >= 2 before stripping quotes so a lone quote char is
52
+ * not truncated to '' and an unbalanced leading quote is returned verbatim.
53
+ * @internal
54
+ */
55
+ function parseValue(val) {
56
+ if (val === 'true') return true;
57
+ if (val === 'false') return false;
58
+ if (val === 'null' || val === '~') return null;
59
+
60
+ // Remove surrounding quotes (only when the value is fully wrapped)
61
+ if (val.length >= 2 &&
62
+ ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') ||
63
+ (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'"))) {
64
+ return val.substring(1, val.length - 1);
65
+ }
66
+
67
+ // Try number
68
+ var num = Number(val);
69
+ if (!isNaN(num) && val !== '') return num;
70
+
71
+ return val;
72
+ }
73
+
74
+ /**
75
+ * ConfigManager class.
76
+ * @public
77
+ */
78
+ class ConfigManager {
79
+ /**
80
+ * @public
81
+ * @param {object} [options]
82
+ * @param {string} [options.configPath] - path to harness-config.yaml
83
+ * @param {object} [options.defaults] - plugin default configs { pluginName: { key: value } }
84
+ */
85
+ constructor(options) {
86
+ options = options || {};
87
+ /** @type {string} */
88
+ this._configPath = options.configPath || path.join(this._findProjectRoot(), '.claude', 'config', 'harness-config.yaml');
89
+ /** @type {object} plugin defaults */
90
+ this._defaults = options.defaults || {};
91
+ /** @type {object|null} parsed YAML config */
92
+ this._yamlConfig = null;
93
+ /** @type {object} runtime overrides */
94
+ this._overrides = {};
95
+ }
96
+
97
+ // --- public API ---
98
+
99
+ /**
100
+ * Get a config value with three-layer resolution:
101
+ * runtime override > harness-config.yaml > plugin defaults
102
+ *
103
+ * @public
104
+ * @param {string} key - dot-notation key
105
+ * @param {*} [defaultValue] - fallback if key not found in any layer
106
+ * @returns {*}
107
+ */
108
+ get(key, defaultValue) {
109
+ // Layer 1: runtime overrides
110
+ var overrideVal = this._getNested(this._overrides, key);
111
+ if (overrideVal !== undefined) {
112
+ return overrideVal;
113
+ }
114
+
115
+ // Layer 2: environment variables (HARNESS_ prefix, double underscore for nesting)
116
+ var envKey = 'HARNESS_' + key.toUpperCase().replace(/\./g, '__');
117
+ if (process.env[envKey] !== undefined) {
118
+ return parseValue(process.env[envKey]);
119
+ }
120
+
121
+ // Layer 3: harness-config.yaml
122
+ var yamlVal = this._getNested(this._getYamlConfig(), key);
123
+ if (yamlVal !== undefined) {
124
+ return yamlVal;
125
+ }
126
+
127
+ return defaultValue;
128
+ }
129
+
130
+ /**
131
+ * Get a config value for a specific plugin.
132
+ * Resolution order:
133
+ * runtime override > env var > harness-config overrides section > harness-config root > plugin defaults
134
+ *
135
+ * @public
136
+ * @param {string} pluginName
137
+ * @param {string} key
138
+ * @param {*} [defaultValue]
139
+ * @returns {*}
140
+ */
141
+ getForPlugin(pluginName, key, defaultValue) {
142
+ // Try plugin-specific override first
143
+ var pluginOverride = this.get('overrides.' + pluginName + '.' + key);
144
+ if (pluginOverride !== undefined) {
145
+ return pluginOverride;
146
+ }
147
+
148
+ // Try general get
149
+ var generalVal = this.get(key);
150
+ if (generalVal !== undefined) {
151
+ return generalVal;
152
+ }
153
+
154
+ // Try plugin defaults
155
+ var defaultVal = this._getNested(this._defaults, pluginName + '.' + key);
156
+ if (defaultVal !== undefined) {
157
+ return defaultVal;
158
+ }
159
+
160
+ return defaultValue;
161
+ }
162
+
163
+ /**
164
+ * Set a runtime override. Takes highest priority.
165
+ * @public
166
+ * @param {string} key
167
+ * @param {*} value
168
+ */
169
+ setOverride(key, value) {
170
+ this._setNested(this._overrides, key, value);
171
+ }
172
+
173
+ /**
174
+ * Clear a runtime override.
175
+ * @public
176
+ * @param {string} key
177
+ */
178
+ clearOverride(key) {
179
+ this._deleteNested(this._overrides, key);
180
+ }
181
+
182
+ /**
183
+ * Get the full parsed YAML config (for advanced usage).
184
+ * @public
185
+ * @returns {object}
186
+ */
187
+ getAll() {
188
+ return this._getYamlConfig();
189
+ }
190
+
191
+ /**
192
+ * Create a scoped config getter for a specific plugin.
193
+ * @public
194
+ * @param {string} pluginName
195
+ * @returns {{ get: Function }}
196
+ */
197
+ forPlugin(pluginName) {
198
+ var self = this;
199
+ return {
200
+ get: function (key, defaultValue) {
201
+ return self.getForPlugin(pluginName, key, defaultValue);
202
+ },
203
+ };
204
+ }
205
+
206
+ // --- internal ---
207
+
208
+ /**
209
+ * Load and cache the YAML config.
210
+ * @internal
211
+ * @returns {object}
212
+ */
213
+ _getYamlConfig() {
214
+ if (this._yamlConfig !== null) {
215
+ return this._yamlConfig;
216
+ }
217
+
218
+ try {
219
+ var content = fs.readFileSync(this._configPath, 'utf-8');
220
+ this._yamlConfig = parseSimpleYaml(content);
221
+ } catch (err) {
222
+ // Config file not found or unreadable - use empty config
223
+ this._yamlConfig = {};
224
+ }
225
+
226
+ return this._yamlConfig;
227
+ }
228
+
229
+ /**
230
+ * Get nested value by dot-notation key.
231
+ * @internal
232
+ */
233
+ _getNested(obj, key) {
234
+ var parts = key.split('.');
235
+ var current = obj;
236
+ for (var i = 0; i < parts.length; i++) {
237
+ // S7:拒绝原型污染段
238
+ if (parts[i] === '__proto__' || parts[i] === 'constructor' || parts[i] === 'prototype') {
239
+ return undefined;
240
+ }
241
+ if (current === null || current === undefined || typeof current !== 'object') {
242
+ return undefined;
243
+ }
244
+ current = current[parts[i]];
245
+ }
246
+ return current;
247
+ }
248
+
249
+ /**
250
+ * Set nested value by dot-notation key.
251
+ * @internal
252
+ */
253
+ _setNested(obj, key, value) {
254
+ var parts = key.split('.');
255
+ var current = obj;
256
+ for (var i = 0; i < parts.length - 1; i++) {
257
+ // S7:拒绝原型污染段,写入 __proto__/constructor/prototype 视为 no-op
258
+ if (parts[i] === '__proto__' || parts[i] === 'constructor' || parts[i] === 'prototype') {
259
+ return;
260
+ }
261
+ if (typeof current[parts[i]] !== 'object' || current[parts[i]] === null) {
262
+ current[parts[i]] = {};
263
+ }
264
+ current = current[parts[i]];
265
+ }
266
+ var last = parts[parts.length - 1];
267
+ if (last === '__proto__' || last === 'constructor' || last === 'prototype') {
268
+ return;
269
+ }
270
+ current[last] = value;
271
+ }
272
+
273
+ /**
274
+ * Delete nested value by dot-notation key.
275
+ * @internal
276
+ */
277
+ _deleteNested(obj, key) {
278
+ var parts = key.split('.');
279
+ var current = obj;
280
+ for (var i = 0; i < parts.length - 1; i++) {
281
+ // S7:拒绝原型污染段
282
+ if (parts[i] === '__proto__' || parts[i] === 'constructor' || parts[i] === 'prototype') {
283
+ return;
284
+ }
285
+ if (typeof current[parts[i]] !== 'object' || current[parts[i]] === null) {
286
+ return;
287
+ }
288
+ current = current[parts[i]];
289
+ }
290
+ var last = parts[parts.length - 1];
291
+ if (last === '__proto__' || last === 'constructor' || last === 'prototype') {
292
+ return;
293
+ }
294
+ delete current[last];
295
+ }
296
+
297
+ /**
298
+ * Walk up from cwd to find the project root (directory containing task.md or CLAUDE.md).
299
+ * Falls back to cwd if not found.
300
+ * @internal
301
+ * @returns {string}
302
+ */
303
+ _findProjectRoot() {
304
+ var dir = process.cwd();
305
+ for (var i = 0; i < 10; i++) {
306
+ if (fs.existsSync(path.join(dir, 'task.md')) || fs.existsSync(path.join(dir, 'CLAUDE.md'))) {
307
+ return dir;
308
+ }
309
+ var parent = path.dirname(dir);
310
+ if (parent === dir) break; // filesystem root
311
+ dir = parent;
312
+ }
313
+ return process.cwd();
314
+ }
315
+ }
316
+
317
+ module.exports = ConfigManager;