doukui 0.0.0-stage → 0.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 (135) 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 +1398 -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 +1397 -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 +572 -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 +390 -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-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
@@ -0,0 +1,661 @@
1
+ /**
2
+ * Hook: Skill Gate (Unified)
3
+ *
4
+ * Merges three hook behaviors into one plugin:
5
+ * 1. PreToolUse(Edit|Write) - block file edits when state is in a blocked state (e.g. "waiting")
6
+ * 2. PostToolUse(Skill) - set state to "waiting" after a gated skill completes
7
+ * 3. Dynamic gated skill query - read gated skills from plugin-registry.json metadata
8
+ *
9
+ * Usage (CLI):
10
+ * node plugins/core/hook-skill-gate/index.js --pre-tool (invoked by PreToolUse hook)
11
+ * node plugins/core/hook-skill-gate/index.js --post-skill (invoked by PostToolUse hook)
12
+ *
13
+ * Usage (Programmatic):
14
+ * const SkillGateHook = require('./index.js');
15
+ * const hook = new SkillGateHook();
16
+ * await hook.onActivate(context);
17
+ * const result = await hook.handle({ event: 'PreToolUse', tool: 'Edit', ... });
18
+ */
19
+
20
+ 'use strict';
21
+
22
+ var fs = require('fs');
23
+ var path = require('path');
24
+ var { HookPlugin } = require('../../contracts/plugin-interface');
25
+ var { StateStore, FileSystemAdapter } = require('../../runtime/state-store');
26
+
27
+ /**
28
+ * Default configuration values.
29
+ */
30
+ var DEFAULT_CONFIG = {
31
+ gatedSkills: [],
32
+ blockedStates: ['waiting'],
33
+ stateKey: 'harness.state',
34
+ };
35
+
36
+ /**
37
+ * Resolve the package root directory from __dirname.
38
+ * Walks up from the hook's location to find the doukui package root.
39
+ * Used to locate plugin-registry.json regardless of installation mode.
40
+ *
41
+ * For global installs, resolves to the global npm package directory.
42
+ * For local installs, resolves to the project's node_modules/doukui.
43
+ *
44
+ * @returns {string}
45
+ */
46
+ function resolvePackageRoot() {
47
+ // This hook is at: plugins/core/hook-skill-gate/index.js
48
+ // Package root is three levels up from __dirname
49
+ var dir = path.resolve(__dirname, '../../..');
50
+
51
+ // Verify we're at the right location (should contain plugins/ directory)
52
+ for (var i = 0; i < 5; i++) {
53
+ if (fs.existsSync(path.join(dir, 'plugins'))) return dir;
54
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
55
+ var parent = path.dirname(dir);
56
+ if (parent === dir) break;
57
+ dir = parent;
58
+ }
59
+
60
+ // Fallback: try to find global doukui in node_modules
61
+ // Check common global npm directories
62
+ var globalPaths = [
63
+ path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'doukui'),
64
+ path.join(process.env.npm_config_prefix || '/usr/local', 'lib', 'node_modules', 'doukui'),
65
+ ];
66
+
67
+ for (var j = 0; j < globalPaths.length; j++) {
68
+ if (fs.existsSync(path.join(globalPaths[j], 'plugins'))) {
69
+ return globalPaths[j];
70
+ }
71
+ }
72
+
73
+ // Fallback to computed path
74
+ return path.resolve(__dirname, '../../..');
75
+ }
76
+
77
+ /**
78
+ * Resolve the project root directory from CWD.
79
+ * Walks up from process.cwd() to find task.md or .claude/.
80
+ * This works for both global and local hook execution.
81
+ *
82
+ * @param {string} [startDir] - directory to start from (default: process.cwd())
83
+ * @returns {string}
84
+ */
85
+ function resolveProjectRoot(startDir) {
86
+ // Always use process.cwd() to find the actual project root
87
+ // This allows hooks to work correctly regardless of installation mode
88
+ var dir = startDir || process.cwd();
89
+ for (var i = 0; i < 10; i++) {
90
+ if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
91
+ if (fs.existsSync(path.join(dir, '.claude'))) return dir;
92
+ var parent = path.dirname(dir);
93
+ if (parent === dir) break;
94
+ dir = parent;
95
+ }
96
+ return process.cwd();
97
+ }
98
+
99
+ /**
100
+ * Read plugin-registry.json and return skill names that are marked as gated.
101
+ *
102
+ * A skill is considered "gated" if:
103
+ * - Its plugin.json has metadata.gatedByCode === true, OR
104
+ * - It appears in the hook-skill-gate config.gatedSkills list
105
+ *
106
+ * Uses packageRoot to locate registry and plugin directories.
107
+ *
108
+ * @param {string} packageRoot - the doukui package root directory
109
+ * @param {object} hookConfig - the hook-skill-gate config section
110
+ * @returns {string[]} array of gated skill names
111
+ */
112
+ function discoverGatedSkills(packageRoot, hookConfig) {
113
+ var registryPath = path.join(packageRoot, 'plugins', 'plugin-registry.json');
114
+ var gatedFromMetadata = [];
115
+ var gatedFromConfig = (hookConfig && hookConfig.gatedSkills) || [];
116
+
117
+ // 1. Read registry and scan each plugin for metadata.gatedByCode
118
+ try {
119
+ var content = fs.readFileSync(registryPath, 'utf-8');
120
+ var registry = JSON.parse(content);
121
+ var plugins = registry.plugins || [];
122
+
123
+ for (var i = 0; i < plugins.length; i++) {
124
+ var entry = plugins[i];
125
+ if (!entry.source) continue;
126
+
127
+ // Attempt to read the plugin's plugin.json for metadata
128
+ // Path: plugins/core/{source}/plugin.json
129
+ // BUGFIX: Use entry.source directly (already includes 'hook-' prefix if needed)
130
+ var pluginJsonPath = path.join(
131
+ packageRoot,
132
+ 'plugins',
133
+ 'core',
134
+ entry.source,
135
+ 'plugin.json'
136
+ );
137
+ try {
138
+ var pluginJson = JSON.parse(fs.readFileSync(pluginJsonPath, 'utf-8'));
139
+ if (
140
+ pluginJson.metadata &&
141
+ (pluginJson.metadata.gatedByCode === true ||
142
+ pluginJson.metadata.gatedByHuman === true)
143
+ ) {
144
+ gatedFromMetadata.push(pluginJson.name || entry.name);
145
+ }
146
+ } catch (e) {
147
+ // plugin.json may not exist or be unreadable - skip
148
+ }
149
+ }
150
+ } catch (e) {
151
+ // Registry may not exist - continue with config-only list
152
+ }
153
+
154
+ // 2. Merge and deduplicate
155
+ var all = gatedFromMetadata.concat(gatedFromConfig);
156
+ var seen = {};
157
+ var result = [];
158
+ for (var j = 0; j < all.length; j++) {
159
+ if (!seen[all[j]]) {
160
+ seen[all[j]] = true;
161
+ result.push(all[j]);
162
+ }
163
+ }
164
+
165
+ return result;
166
+ }
167
+
168
+ /**
169
+ * SkillGateHook - Unified skill gate hook plugin.
170
+ *
171
+ * Extends HookPlugin from the plugin interface contract.
172
+ */
173
+ class SkillGateHook extends HookPlugin {
174
+ constructor() {
175
+ super();
176
+ this.name = 'hook-skill-gate';
177
+ this.version = '1.0.0';
178
+ this.description = '统一技能门控 Hook';
179
+ this.dependencies = { providers: ['provider:state-store'] };
180
+ this.trigger = {
181
+ event: 'PreToolUse',
182
+ tools: ['Edit', 'Write'],
183
+ skills: [],
184
+ };
185
+ this.priority = 10;
186
+
187
+ /** @type {StateStore|null} */
188
+ this._store = null;
189
+ /** @type {object} */
190
+ this._config = Object.assign({}, DEFAULT_CONFIG);
191
+ /** @type {string} */
192
+ this._projectRoot = '';
193
+ /** @type {string} */
194
+ this._packageRoot = '';
195
+ /** @type {string[]|null} cached gated skills */
196
+ this._gatedSkillsCache = null;
197
+ }
198
+
199
+ /**
200
+ * Called during plugin activation.
201
+ * Initializes state store and reads config.
202
+ *
203
+ * @param {PluginContext} context
204
+ */
205
+ async onActivate(context) {
206
+ this._projectRoot = resolveProjectRoot();
207
+ this._packageRoot = resolvePackageRoot();
208
+ var stateFilePath = path.join(this._projectRoot, '.claude-state');
209
+ this._store = new StateStore({ filePath: stateFilePath });
210
+
211
+ // Load project-level config from harness-config.yaml
212
+ this._loadProjectConfig();
213
+
214
+ // Merge context config if available
215
+ if (context && context.config) {
216
+ var pluginConfig = context.config.getPluginConfig
217
+ ? context.config.getPluginConfig(this.name)
218
+ : null;
219
+ if (pluginConfig) {
220
+ for (var key in pluginConfig) {
221
+ if (pluginConfig.hasOwnProperty(key)) {
222
+ this._config[key] = pluginConfig[key];
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ // Initial discovery of gated skills
229
+ this._gatedSkillsCache = discoverGatedSkills(this._packageRoot, this._config);
230
+ }
231
+
232
+ /**
233
+ * Main hook handler.
234
+ * Dispatches to the appropriate sub-handler based on the event type.
235
+ *
236
+ * @param {object} context - hook context
237
+ * @param {string} context.event - 'PreToolUse' or 'PostToolUse'
238
+ * @param {string} [context.tool] - tool name (for PreToolUse)
239
+ * @param {string} [context.skill] - skill name (for PostToolUse)
240
+ * @returns {Promise<{ allowed: boolean, reason?: string, stateChanges?: object[] }>}
241
+ */
242
+ async handle(context) {
243
+ if (!context || !context.event) {
244
+ return { allowed: true };
245
+ }
246
+
247
+ if (context.event === 'PreToolUse') {
248
+ return this._handlePreToolUse(context);
249
+ }
250
+
251
+ if (context.event === 'PostToolUse') {
252
+ return this._handlePostToolUse(context);
253
+ }
254
+
255
+ return { allowed: true };
256
+ }
257
+
258
+ /**
259
+ * PreToolUse handler - block Edit/Write when state is in a blocked state.
260
+ *
261
+ * @param {object} context
262
+ * @param {string} context.tool - the tool being used ('Edit', 'Write', etc.)
263
+ * @returns {Promise<{ allowed: boolean, reason?: string }>}
264
+ */
265
+ async _handlePreToolUse(context) {
266
+ var tool = context.tool || '';
267
+ var restrictedTools = ['Edit', 'Write'];
268
+
269
+ // Only gate Edit and Write operations
270
+ var isRestricted = false;
271
+ for (var i = 0; i < restrictedTools.length; i++) {
272
+ if (tool === restrictedTools[i]) {
273
+ isRestricted = true;
274
+ break;
275
+ }
276
+ }
277
+
278
+ if (!isRestricted) {
279
+ return { allowed: true };
280
+ }
281
+
282
+ // Read current state from store
283
+ var currentState = await this._getState();
284
+ var blockedStates = this._config.blockedStates || ['waiting'];
285
+
286
+ for (var j = 0; j < blockedStates.length; j++) {
287
+ if (currentState === blockedStates[j]) {
288
+ return {
289
+ allowed: false,
290
+ reason:
291
+ 'Blocked: current state is "' +
292
+ currentState +
293
+ '". ' +
294
+ 'Edit/Write operations are not allowed while waiting for human confirmation.',
295
+ };
296
+ }
297
+ }
298
+
299
+ return { allowed: true };
300
+ }
301
+
302
+ /**
303
+ * PostToolUse handler - after a gated skill executes, set state to "waiting".
304
+ *
305
+ * @param {object} context
306
+ * @param {string} context.tool - tool name (should be 'Skill')
307
+ * @param {string} [context.skill] - the skill that was executed
308
+ * @param {string} [context.skillName] - alternative field for skill name
309
+ * @returns {Promise<{ allowed: boolean, handled: boolean, newState?: string, stateChanges?: object[] }>}
310
+ */
311
+ async _handlePostToolUse(context) {
312
+ var tool = context.tool || '';
313
+ if (tool !== 'Skill') {
314
+ return { allowed: true, handled: false };
315
+ }
316
+
317
+ // Get the skill name from context
318
+ var skillName = context.skill || context.skillName || '';
319
+ if (!skillName) {
320
+ return { allowed: true, handled: false };
321
+ }
322
+
323
+ // Refresh gated skills list (dynamic query)
324
+ var gatedSkills = this._getGatedSkills();
325
+
326
+ // Check if the skill that just ran is gated
327
+ var isGated = false;
328
+ for (var i = 0; i < gatedSkills.length; i++) {
329
+ if (gatedSkills[i] === skillName) {
330
+ isGated = true;
331
+ break;
332
+ }
333
+ }
334
+
335
+ if (!isGated) {
336
+ return { allowed: true, handled: false };
337
+ }
338
+
339
+ // WP-S3 风险分级人审豁免:环境显式授权(DOUKUI_LOW_RISK_GATE=1)+ 当前 plan
340
+ // 声明 low(driver/skill 解析后写 harness.planRisk=low)→ 跳过 waiting 强制暂停。
341
+ // 双条件缺一不可:仅 env 开而 plan 未声明 low → 照常拦;plan low 但未授权 → 照常拦。
342
+ if (process.env.DOUKUI_LOW_RISK_GATE === '1') {
343
+ try {
344
+ var planRisk = this._store ? await this._store.get('harness.planRisk') : undefined;
345
+ if (planRisk === 'low') {
346
+ return {
347
+ allowed: true,
348
+ handled: true,
349
+ newState: (await this._getState()) || 'idle',
350
+ stateChanges: [],
351
+ skipReason: 'low_risk_plan_authorized',
352
+ };
353
+ }
354
+ } catch (_e) { /* 状态读取失败 → 不豁免,走正常门控 */ }
355
+ }
356
+
357
+ // Set state to "waiting" to pause for human confirmation
358
+ var waitingState = 'waiting';
359
+ await this._setState(waitingState);
360
+
361
+ return {
362
+ allowed: true,
363
+ handled: true,
364
+ newState: waitingState,
365
+ stateChanges: [
366
+ {
367
+ key: this._config.stateKey,
368
+ oldValue: await this._getState(),
369
+ newValue: waitingState,
370
+ },
371
+ ],
372
+ };
373
+ }
374
+
375
+ /**
376
+ * Get the current list of gated skills.
377
+ * Refreshes from registry on each call for dynamic discovery.
378
+ *
379
+ * @returns {string[]}
380
+ */
381
+ _getGatedSkills() {
382
+ this._gatedSkillsCache = discoverGatedSkills(
383
+ this._packageRoot,
384
+ this._config
385
+ );
386
+ return this._gatedSkillsCache;
387
+ }
388
+
389
+ /**
390
+ * Read the current state from the store.
391
+ * @returns {Promise<string|undefined>}
392
+ */
393
+ async _getState() {
394
+ if (!this._store) return undefined;
395
+ return await this._store.get(this._config.stateKey);
396
+ }
397
+
398
+ /**
399
+ * Write a new state to the store.
400
+ * @param {string} value
401
+ * @returns {Promise<void>}
402
+ */
403
+ async _setState(value) {
404
+ if (!this._store) return;
405
+ await this._store.set(this._config.stateKey, value);
406
+ }
407
+
408
+ /**
409
+ * Load project-level config from harness-config.yaml.
410
+ * Reads CWD/.claude/config/harness-config.yaml and merges hook-skill-gate section.
411
+ */
412
+ _loadProjectConfig() {
413
+ var configPath = path.join(this._projectRoot, '.claude', 'config', 'harness-config.yaml');
414
+ try {
415
+ if (fs.existsSync(configPath)) {
416
+ var content = fs.readFileSync(configPath, 'utf-8');
417
+ var yamlConfig = this._parseSimpleYaml(content);
418
+
419
+ // Extract hook-skill-gate specific config
420
+ if (yamlConfig['hook-skill-gate']) {
421
+ var hookConfig = yamlConfig['hook-skill-gate'];
422
+ for (var key in hookConfig) {
423
+ if (hookConfig.hasOwnProperty(key)) {
424
+ this._config[key] = hookConfig[key];
425
+ }
426
+ }
427
+ }
428
+ }
429
+ } catch (e) {
430
+ // Config file doesn't exist or is invalid - use defaults
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Minimal YAML-like parser — S8/A3 consolidated.
436
+ *
437
+ * Delegates to the shared `yaml-parser.parseSimpleYaml`. Previously this
438
+ * hook had its own divergent copy (which silently dropped list items and
439
+ * lacked size/depth guards). The shared parser also fixes B4 (top-level
440
+ * scalar arrays now parse correctly).
441
+ * @param {string} content
442
+ * @returns {object}
443
+ */
444
+ _parseSimpleYaml(content) {
445
+ var sharedParser = require('../../runtime/yaml-parser');
446
+ try {
447
+ return sharedParser.parseSimpleYaml(content);
448
+ } catch (_e) {
449
+ // Oversize / over-depth → treat as empty config (preserve old behavior
450
+ // of never throwing from the config-read path)
451
+ return {};
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Check if this hook execution should be skipped to prevent double-triggering.
457
+ *
458
+ * Double-triggering can occur when:
459
+ * 1. A hook is registered globally (via global npm install)
460
+ * 2. The same hook is also registered at project level (via local build)
461
+ *
462
+ * We detect this by checking:
463
+ * - Whether HOOK_EXECUTION_ID env var is set (set by first execution)
464
+ * - Whether a marker file exists in the project
465
+ *
466
+ * @returns {boolean} true if this execution should be skipped
467
+ */
468
+ _shouldSkipForDoubleTrigger() {
469
+ var markerPath = path.join(this._projectRoot, '.claude', '.hook-execution-marker');
470
+
471
+ // If another hook process is marked as active, skip
472
+ if (fs.existsSync(markerPath)) {
473
+ try {
474
+ var marker = fs.readFileSync(markerPath, 'utf-8');
475
+ var markerData = JSON.parse(marker);
476
+
477
+ // If marker is recent (< 5 seconds), skip to prevent double execution
478
+ var now = Date.now();
479
+ if (markerData.timestamp && (now - markerData.timestamp) < 5000) {
480
+ return true;
481
+ }
482
+ // Stale marker — clean it up
483
+ try { fs.unlinkSync(markerPath); } catch (e) { /* ignore */ }
484
+ } catch (e) {
485
+ // Invalid marker, clean up
486
+ try { fs.unlinkSync(markerPath); } catch (e2) { /* ignore */ }
487
+ }
488
+ }
489
+
490
+ // Mark this hook as active
491
+ try {
492
+ fs.writeFileSync(
493
+ markerPath,
494
+ JSON.stringify({ timestamp: Date.now(), pid: process.pid }),
495
+ 'utf-8'
496
+ );
497
+ } catch (e) {
498
+ // Failed to write marker, continue anyway
499
+ }
500
+
501
+ return false;
502
+ }
503
+ }
504
+
505
+ // --- CLI Entry Point ---
506
+ //
507
+ // When invoked via `node index.js --pre-tool` or `node index.js --post-skill`,
508
+ // reads stdin for the hook context JSON and outputs a JSON result.
509
+
510
+ /**
511
+ * Read all data from stdin and parse as JSON.
512
+ * Sanitizes input to prevent prototype pollution and limits size.
513
+ * @param {function} callback - callback(error, data)
514
+ */
515
+ function readStdin(callback) {
516
+ var chunks = [];
517
+ var totalSize = 0;
518
+ var MAX_SIZE = 1024 * 1024; // 1MB limit
519
+
520
+ process.stdin.setEncoding('utf-8');
521
+ process.stdin.on('data', function (chunk) {
522
+ totalSize += chunk.length;
523
+ if (totalSize > MAX_SIZE) {
524
+ process.stdin.destroy();
525
+ callback(new Error('Input exceeds maximum size limit'));
526
+ return;
527
+ }
528
+ chunks.push(chunk);
529
+ });
530
+ process.stdin.on('end', function () {
531
+ var raw = chunks.join('');
532
+ if (!raw.trim()) {
533
+ return callback(null, {});
534
+ }
535
+ try {
536
+ var parsed = JSON.parse(raw);
537
+
538
+ // Prevent prototype pollution: strip dangerous keys
539
+ var sanitized = sanitizeObject(parsed);
540
+ callback(null, sanitized);
541
+ } catch (e) {
542
+ callback(new Error('Invalid JSON input'));
543
+ }
544
+ });
545
+ process.stdin.on('error', function (err) {
546
+ callback(new Error('Failed to read stdin'));
547
+ });
548
+ }
549
+
550
+ /**
551
+ * Sanitize an object to prevent prototype pollution attacks.
552
+ * Removes __proto__, constructor, and prototype properties.
553
+ * @param {*} obj - object to sanitize
554
+ * @returns {*} sanitized object
555
+ */
556
+ function sanitizeObject(obj) {
557
+ if (obj === null || typeof obj !== 'object') {
558
+ return obj;
559
+ }
560
+
561
+ if (Array.isArray(obj)) {
562
+ return obj.map(sanitizeObject);
563
+ }
564
+
565
+ var result = {};
566
+ var keys = Object.keys(obj); // Object.keys ignores prototype chain
567
+ for (var i = 0; i < keys.length; i++) {
568
+ var key = keys[i];
569
+
570
+ // Block dangerous property names that could cause prototype pollution
571
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
572
+ continue;
573
+ }
574
+
575
+ // Recursively sanitize nested objects
576
+ try {
577
+ result[key] = sanitizeObject(obj[key]);
578
+ } catch (e) {
579
+ // Skip values that cause errors during sanitization
580
+ }
581
+ }
582
+ return result;
583
+ }
584
+
585
+ /**
586
+ * Main CLI function.
587
+ */
588
+ function main() {
589
+ var args = process.argv.slice(2);
590
+
591
+ if (args.length === 0) {
592
+ console.error(
593
+ 'Usage: node index.js --pre-tool | --post-skill\n' +
594
+ ' --pre-tool Run PreToolUse check (reads context from stdin)\n' +
595
+ ' --post-skill Run PostToolUse handler (reads context from stdin)'
596
+ );
597
+ process.exit(1);
598
+ }
599
+
600
+ var mode = args[0];
601
+ if (mode !== '--pre-tool' && mode !== '--post-skill') {
602
+ console.error('Unknown mode: ' + mode);
603
+ console.error('Valid modes: --pre-tool, --post-skill');
604
+ process.exit(1);
605
+ }
606
+
607
+ readStdin(function (err, context) {
608
+ if (err) {
609
+ console.error('Failed to read stdin: ' + err.message);
610
+ process.exit(1);
611
+ }
612
+
613
+ var hook = new SkillGateHook();
614
+
615
+ // Activate the hook (initialize state store, etc.)
616
+ hook
617
+ .onActivate(null)
618
+ .then(function () {
619
+ // Check for double-triggering prevention
620
+ if (hook._shouldSkipForDoubleTrigger()) {
621
+ // Skip execution to prevent double-triggering
622
+ process.stdout.write(JSON.stringify({ allowed: true, skipped: true, reason: 'Double-trigger prevention' }) + '\n');
623
+ process.exit(0);
624
+ }
625
+
626
+ // Set the event type based on CLI mode
627
+ if (mode === '--pre-tool') {
628
+ context.event = 'PreToolUse';
629
+ } else if (mode === '--post-skill') {
630
+ context.event = 'PostToolUse';
631
+ // Normalize: if tool is not set, default to 'Skill' for post-skill mode
632
+ if (!context.tool) {
633
+ context.tool = 'Skill';
634
+ }
635
+ }
636
+
637
+ return hook.handle(context);
638
+ })
639
+ .then(function (result) {
640
+ // Output the result as JSON
641
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
642
+
643
+ // Exit with code 0 if allowed, 2 if blocked (Claude Code hook convention)
644
+ if (result.allowed === false) {
645
+ process.exit(2);
646
+ }
647
+ process.exit(0);
648
+ })
649
+ .catch(function (error) {
650
+ console.error('Hook execution failed: ' + error.message);
651
+ process.exit(1);
652
+ });
653
+ });
654
+ }
655
+
656
+ // Run CLI if executed directly (not required as a module)
657
+ if (require.main === module) {
658
+ main();
659
+ }
660
+
661
+ module.exports = SkillGateHook;
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "hook-skill-gate",
3
+ "version": "1.0.0",
4
+ "type": "hook",
5
+ "description": "统一技能门控 Hook - 合并 check-state + post-skill + skill-gate 三合一,动态查询 gated skills",
6
+ "dependencies": ["provider:state-store"],
7
+ "provides": ["hook:skill-gate"],
8
+ "config": {
9
+ "gatedSkills": [],
10
+ "blockedStates": ["waiting"]
11
+ }
12
+ }