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,311 @@
1
+ /**
2
+ * AuditLogger - JSONL audit log persistence for plugin sandboxing
3
+ *
4
+ * Writes structured audit events to a JSONL (JSON Lines) file.
5
+ * Each line is a complete JSON object representing one audit event.
6
+ *
7
+ * Event types (from design doc section 3.5.2):
8
+ * - sandbox.create — Worker Thread created
9
+ * - sandbox.terminate — Worker Thread terminated
10
+ * - plugin.load — plugin loaded (with capability review)
11
+ * - capability.check — runtime capability check (allow/deny)
12
+ * - capability.violation — plugin attempted undeclared capability
13
+ *
14
+ * File path: ${targetRoot}/.claude/logs/audit-${YYYYMMDD}.jsonl
15
+ *
16
+ * @module audit-logger
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ var fs = require('fs');
22
+ var path = require('path');
23
+ var Logger = require('./logger');
24
+ var logger = new Logger();
25
+
26
+ /**
27
+ * @typedef {object} AuditEntry
28
+ * @property {string} timestamp - ISO 8601 timestamp
29
+ * @property {string} event - event type
30
+ * @property {string} plugin - plugin name
31
+ * @property {string} [sourceType] - plugin source type (core/npm/local)
32
+ * @property {string} [capability] - requested capability (for capability events)
33
+ * @property {string} decision - allow | deny | warn | error
34
+ * @property {string} [detail] - additional detail
35
+ * @property {string} [sessionId] - session identifier for correlation
36
+ */
37
+
38
+ /**
39
+ * AuditLogger writes structured audit events to JSONL files.
40
+ * @public
41
+ */
42
+ class AuditLogger {
43
+ /**
44
+ * @public
45
+ * @param {object} [options]
46
+ * @param {string} [options.logDir] - directory for audit log files (default: .claude/logs under cwd)
47
+ * @param {string} [options.sessionId] - session identifier for correlation
48
+ * @param {object} [options.logger] - optional Logger instance for internal logging
49
+ */
50
+ constructor(options) {
51
+ options = options || {};
52
+ this._logDir = options.logDir || path.join(process.cwd(), '.claude', 'logs');
53
+ this._sessionId = options.sessionId || '';
54
+ this._logger = options.logger || null;
55
+ this._currentDate = '';
56
+ this._buffer = [];
57
+ this._flushTimer = null;
58
+ this._flushInterval = options.flushInterval || 1000; // 1 second default
59
+ this._maxBufferSize = options.maxBufferSize || 100;
60
+ this._destroyed = false;
61
+ }
62
+
63
+ // --- Public API ---
64
+
65
+ /**
66
+ * Log an audit event.
67
+ * Events are buffered and flushed periodically or when the buffer is full.
68
+ *
69
+ * @public
70
+ * @param {string} event - event type (sandbox.create, capability.check, etc.)
71
+ * @param {string} plugin - plugin name
72
+ * @param {object} [details] - additional fields to include in the entry
73
+ * @returns {void}
74
+ */
75
+ log(event, plugin, details) {
76
+ if (this._destroyed) {
77
+ return;
78
+ }
79
+
80
+ var entry = {
81
+ timestamp: new Date().toISOString(),
82
+ event: event,
83
+ plugin: plugin,
84
+ decision: (details && details.decision) || 'allow',
85
+ };
86
+
87
+ if (details) {
88
+ if (details.sourceType) entry.sourceType = details.sourceType;
89
+ if (details.capability) entry.capability = details.capability;
90
+ if (details.detail) entry.detail = details.detail;
91
+ if (details.decision) entry.decision = details.decision;
92
+ }
93
+
94
+ if (this._sessionId) {
95
+ entry.sessionId = this._sessionId;
96
+ }
97
+
98
+ this._buffer.push(entry);
99
+
100
+ // Flush immediately if buffer is full
101
+ if (this._buffer.length >= this._maxBufferSize) {
102
+ this._flush();
103
+ } else if (!this._flushTimer) {
104
+ // Schedule a delayed flush
105
+ var self = this;
106
+ this._flushTimer = setTimeout(function () {
107
+ self._flushTimer = null;
108
+ self._flush();
109
+ }, this._flushInterval);
110
+ // Unref so the timer doesn't keep the process alive
111
+ if (this._flushTimer.unref) {
112
+ this._flushTimer.unref();
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Shorthand for logging a capability check event.
119
+ *
120
+ * @public
121
+ * @param {string} plugin - plugin name
122
+ * @param {string} capability - requested capability
123
+ * @param {string} decision - 'allow' | 'deny' | 'warn' | 'error'
124
+ * @param {string} [detail] - additional detail
125
+ * @param {string} [sourceType] - plugin source type
126
+ */
127
+ logCapabilityCheck(plugin, capability, decision, detail, sourceType) {
128
+ this.log('capability.check', plugin, {
129
+ capability: capability,
130
+ decision: decision,
131
+ detail: detail || '',
132
+ sourceType: sourceType || '',
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Shorthand for logging a sandbox lifecycle event.
138
+ *
139
+ * @public
140
+ * @param {string} event - 'sandbox.create' | 'sandbox.terminate'
141
+ * @param {string} plugin - plugin name
142
+ * @param {string} [detail] - additional detail (e.g. thread ID, termination reason)
143
+ */
144
+ logSandboxEvent(event, plugin, detail) {
145
+ this.log(event, plugin, {
146
+ decision: 'allow',
147
+ detail: detail || '',
148
+ });
149
+ }
150
+
151
+ /**
152
+ * Shorthand for logging a plugin load event.
153
+ *
154
+ * @public
155
+ * @param {string} plugin - plugin name
156
+ * @param {string} sourceType - plugin source type
157
+ * @param {string} decision - 'allow' | 'deny'
158
+ * @param {string} [detail] - capability review summary
159
+ */
160
+ logPluginLoad(plugin, sourceType, decision, detail) {
161
+ this.log('plugin.load', plugin, {
162
+ sourceType: sourceType,
163
+ decision: decision,
164
+ detail: detail || '',
165
+ });
166
+ }
167
+
168
+ /**
169
+ * Force-flush all buffered entries to disk.
170
+ * @public
171
+ */
172
+ flush() {
173
+ this._flush();
174
+ }
175
+
176
+ /**
177
+ * Destroy the audit logger, flushing any remaining entries.
178
+ * After calling destroy(), no more events can be logged.
179
+ * @public
180
+ */
181
+ destroy() {
182
+ this._destroyed = true;
183
+ if (this._flushTimer) {
184
+ clearTimeout(this._flushTimer);
185
+ this._flushTimer = null;
186
+ }
187
+ this._flush();
188
+ }
189
+
190
+ /**
191
+ * Query audit log entries from the current day's log file.
192
+ *
193
+ * @public
194
+ * @param {object} [filter]
195
+ * @param {string} [filter.event] - filter by event type
196
+ * @param {string} [filter.plugin] - filter by plugin name
197
+ * @param {string} [filter.decision] - filter by decision
198
+ * @param {number} [filter.limit] - max entries to return
199
+ * @returns {AuditEntry[]}
200
+ */
201
+ query(filter) {
202
+ filter = filter || {};
203
+ var entries = this._readLogFile();
204
+ var results = entries;
205
+
206
+ if (filter.event) {
207
+ results = results.filter(function (e) { return e.event === filter.event; });
208
+ }
209
+ if (filter.plugin) {
210
+ results = results.filter(function (e) { return e.plugin === filter.plugin; });
211
+ }
212
+ if (filter.decision) {
213
+ results = results.filter(function (e) { return e.decision === filter.decision; });
214
+ }
215
+ if (filter.limit) {
216
+ results = results.slice(-filter.limit);
217
+ }
218
+
219
+ return results;
220
+ }
221
+
222
+ /**
223
+ * Get the log file path for a given date.
224
+ *
225
+ * @public
226
+ * @param {Date} [date] - date object (default: today)
227
+ * @returns {string} absolute path to the JSONL file
228
+ */
229
+ getLogFilePath(date) {
230
+ date = date || new Date();
231
+ var dateStr = date.toISOString().slice(0, 10).replace(/-/g, '');
232
+ return path.join(this._logDir, 'audit-' + dateStr + '.jsonl');
233
+ }
234
+
235
+ // --- Internal ---
236
+
237
+ /**
238
+ * Flush buffered entries to the JSONL file.
239
+ * @private
240
+ */
241
+ _flush() {
242
+ if (this._buffer.length === 0) return;
243
+
244
+ var entries = this._buffer.splice(0, this._buffer.length);
245
+
246
+ try {
247
+ // Ensure log directory exists
248
+ if (!fs.existsSync(this._logDir)) {
249
+ fs.mkdirSync(this._logDir, { recursive: true });
250
+ }
251
+
252
+ var logPath = this.getLogFilePath();
253
+ var lines = [];
254
+
255
+ for (var i = 0; i < entries.length; i++) {
256
+ lines.push(JSON.stringify(entries[i]));
257
+ }
258
+
259
+ fs.appendFileSync(logPath, lines.join('\n') + '\n', 'utf-8');
260
+ } catch (err) {
261
+ this._internalLog('error', 'Failed to write audit log: ' + err.message);
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Read all entries from today's log file.
267
+ * @private
268
+ * @returns {AuditEntry[]}
269
+ */
270
+ _readLogFile() {
271
+ var logPath = this.getLogFilePath();
272
+
273
+ if (!fs.existsSync(logPath)) {
274
+ return [];
275
+ }
276
+
277
+ try {
278
+ var content = fs.readFileSync(logPath, 'utf-8');
279
+ var lines = content.split('\n').filter(function (line) {
280
+ return line.trim().length > 0;
281
+ });
282
+
283
+ var entries = [];
284
+ for (var i = 0; i < lines.length; i++) {
285
+ try {
286
+ entries.push(JSON.parse(lines[i]));
287
+ } catch (parseErr) {
288
+ // Skip malformed lines
289
+ }
290
+ }
291
+ return entries;
292
+ } catch (err) {
293
+ this._internalLog('error', 'Failed to read audit log: ' + err.message);
294
+ return [];
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Internal logging helper.
300
+ * @private
301
+ */
302
+ _internalLog(level, message) {
303
+ if (this._logger && typeof this._logger[level] === 'function') {
304
+ this._logger[level]('audit-logger', message);
305
+ } else {
306
+ logger[level]('audit-logger', message);
307
+ }
308
+ }
309
+ }
310
+
311
+ module.exports = AuditLogger;
@@ -0,0 +1,89 @@
1
+ /**
2
+ * build-cli - CLI entry point for HarnessBuild
3
+ *
4
+ * Provides the command-line interface for building and validating plugins.
5
+ * Separated from harness-build.js to keep CLI concerns isolated from core logic.
6
+ *
7
+ * @module build-cli
8
+ *
9
+ * Usage:
10
+ * node plugins/runtime/build-cli.js # build all plugins
11
+ * node plugins/runtime/build-cli.js --validate # validate only
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ var HarnessBuild = require('./harness-build');
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // CLI entry point
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Run the CLI.
24
+ * @public
25
+ * @param {string[]} argv - process.argv
26
+ */
27
+ function main(argv) {
28
+ var args = argv.slice(2);
29
+ var mode = 'build'; // default mode
30
+
31
+ for (var i = 0; i < args.length; i++) {
32
+ if (args[i] === '--validate') {
33
+ mode = 'validate';
34
+ } else if (args[i] === '--validate-config') {
35
+ mode = 'validate-config';
36
+ } else if (args[i] === '--help' || args[i] === '-h') {
37
+ console.log('Usage: node plugins/runtime/harness-build.js [OPTIONS]');
38
+ console.log('');
39
+ console.log('Options:');
40
+ console.log(' --validate Validate plugin.json files without building');
41
+ console.log(' --validate-config Validate harness-config.yaml file');
42
+ console.log(' --help, -h Show this help message');
43
+ process.exit(0);
44
+ }
45
+ }
46
+
47
+ var builder = new HarnessBuild();
48
+
49
+ if (mode === 'validate') {
50
+ var result = builder.validate();
51
+ console.log(result.summary);
52
+ process.exit(result.valid ? 0 : 1);
53
+ } else if (mode === 'validate-config') {
54
+ var configResult = builder.validateConfig();
55
+ console.log(configResult.summary);
56
+ if (!configResult.valid) {
57
+ console.log('');
58
+ console.log('Errors:');
59
+ for (var j = 0; j < configResult.errors.length; j++) {
60
+ console.log(' - ' + configResult.errors[j]);
61
+ }
62
+ }
63
+ if (configResult.warnings.length > 0) {
64
+ console.log('');
65
+ console.log('Warnings:');
66
+ for (var k = 0; k < configResult.warnings.length; k++) {
67
+ console.log(' - ' + configResult.warnings[k]);
68
+ }
69
+ }
70
+ process.exit(configResult.valid ? 0 : 1);
71
+ } else {
72
+ var buildResult = builder.build();
73
+ console.log(buildResult.summary);
74
+ process.exit(buildResult.success ? 0 : 1);
75
+ }
76
+ }
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Module exports
80
+ // ---------------------------------------------------------------------------
81
+
82
+ module.exports = {
83
+ main: main,
84
+ };
85
+
86
+ // Run directly if executed as main
87
+ if (require.main === module) {
88
+ main(process.argv);
89
+ }
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // CheckResult 客户端校验层(Phase D-1)
5
+ // ---------------------------------------------------------------------------
6
+ // 原信任模型:proximity/summary 全部来自 LLM 自报的 fenced block,无独立校验,
7
+ // 已出现真实谎报(reflection-evaluator B19「passed > total 钳 0」补丁)。本层在
8
+ // executor 解析链内做客户端校验,把谎报/瑕疵在进入评分前暴露:
9
+ //
10
+ // 分级处理:
11
+ // - hard(数值谎报:passed+failed≠total、passed>total、负数)→ 调用方**硬改判**
12
+ // failed(B19 类问题的系统性替代——在源头修,不靠下游钳制)
13
+ // - 非 hard(结构瑕疵:缺 categories、item 缺 id 等)→ 仅告警(_schemaErrors
14
+ // 附加到 trace,observability),不改判——避免误伤轻微不合规的可用输出
15
+ //
16
+ // ajv 为主路径(optionalDependency,缺失时走内置校验,零强制依赖)。
17
+ // ---------------------------------------------------------------------------
18
+
19
+ var fs = require('fs');
20
+ var path = require('path');
21
+
22
+ var SCHEMA_PATH = path.join(__dirname, '..', 'contracts', 'checkresult-schema.json');
23
+
24
+ var _ajv = null;
25
+ var _ajvProbed = false;
26
+ var _validateFn = null;
27
+
28
+ function loadAjvValidator() {
29
+ if (_ajvProbed) return _validateFn;
30
+ _ajvProbed = true;
31
+ try {
32
+ var Ajv = require('ajv');
33
+ var schema = JSON.parse(fs.readFileSync(SCHEMA_PATH, 'utf8'));
34
+ // json-schema draft-07;ajv 8 需要 addMetaSchema 或显式指定 —— 传 schema 即可
35
+ var ajv = new Ajv({ allErrors: true });
36
+ _validateFn = ajv.compile(schema);
37
+ } catch (_e) {
38
+ _validateFn = null; // ajv 未安装或 schema 损坏 → 内置校验
39
+ }
40
+ return _validateFn;
41
+ }
42
+
43
+ /** 测试用:重置 ajv 探测缓存 */
44
+ function _resetValidatorCache() {
45
+ _ajvProbed = false;
46
+ _validateFn = null;
47
+ }
48
+
49
+ /**
50
+ * 内置最小校验(ajv 缺失时的降级路径):必填字段 + 数值一致性。
51
+ * @param {object} raw
52
+ * @returns {string[]} 错误列表(空数组 = 合法)
53
+ */
54
+ function builtinValidate(raw) {
55
+ var errors = [];
56
+ if (!raw || typeof raw !== 'object') {
57
+ errors.push('not an object');
58
+ return errors;
59
+ }
60
+ if (typeof raw.wpId !== 'string' || !raw.wpId) errors.push('wpId: required string');
61
+ if (typeof raw.passed !== 'boolean') errors.push('passed: required boolean');
62
+ var s = raw.summary;
63
+ if (!s || typeof s !== 'object') {
64
+ errors.push('summary: required object');
65
+ } else {
66
+ var total = s.total, passed = s.passed, failed = s.failed;
67
+ if (typeof total !== 'number' || total < 0) errors.push('summary.total: non-negative integer required');
68
+ if (typeof passed !== 'number' || passed < 0) errors.push('summary.passed: non-negative integer required');
69
+ if (typeof failed !== 'number' || failed < 0) errors.push('summary.failed: non-negative integer required');
70
+ if (typeof total === 'number' && typeof passed === 'number' && typeof failed === 'number' && total >= 0) {
71
+ if (passed > total) errors.push('summary: passed > total(谎报)');
72
+ if (passed + failed !== total) errors.push('summary: passed+failed (' + (passed + failed) + ') != total (' + total + ')');
73
+ }
74
+ }
75
+ if (!Array.isArray(raw.failedItems)) errors.push('failedItems: required array');
76
+ return errors;
77
+ }
78
+
79
+ var HARD_RE = /(passed > total|passed\+failed|non-negative integer required)/;
80
+
81
+ /**
82
+ * 校验 fenced block 解析出的 raw 对象。
83
+ * @param {object|null} raw parseCheckResult 的产物
84
+ * @returns {{ valid: boolean, hard: boolean, errors: string[] }}
85
+ * hard=true 表示数值谎报(调用方应硬改判 failed)
86
+ */
87
+ function validateCheckResult(raw) {
88
+ var errors;
89
+ var ajvValidate = loadAjvValidator();
90
+ if (ajvValidate) {
91
+ var ok = ajvValidate(raw);
92
+ errors = ok ? [] : (ajvValidate.errors || []).map(function (e) {
93
+ return (e.instancePath || e.dataPath || '') + ' ' + e.message;
94
+ });
95
+ // ajv 通过(结构合法)后仍需跑数值一致性检查——schema 里 minimum 拦负数,
96
+ // 但「passed+failed != total」「passed > total」是跨字段语义,schema 表达不了
97
+ if (ok) {
98
+ var semantic = builtinSemanticOnly(raw);
99
+ if (semantic.length > 0) {
100
+ return { valid: false, hard: true, errors: semantic };
101
+ }
102
+ }
103
+ } else {
104
+ errors = builtinValidate(raw);
105
+ }
106
+
107
+ var hard = errors.some(function (e) { return HARD_RE.test(e); });
108
+ return { valid: errors.length === 0, hard: hard, errors: errors };
109
+ }
110
+
111
+ /** 仅跨字段语义检查(供 ajv 主路径补充调用) */
112
+ function builtinSemanticOnly(raw) {
113
+ var errors = [];
114
+ var s = raw && raw.summary;
115
+ if (s && typeof s === 'object' &&
116
+ typeof s.total === 'number' && typeof s.passed === 'number' && typeof s.failed === 'number') {
117
+ if (s.passed > s.total) errors.push('summary: passed > total(谎报)');
118
+ if (s.passed + s.failed !== s.total) {
119
+ errors.push('summary: passed+failed (' + (s.passed + s.failed) + ') != total (' + s.total + ')');
120
+ }
121
+ }
122
+ return errors;
123
+ }
124
+
125
+ module.exports = {
126
+ validateCheckResult: validateCheckResult,
127
+ builtinValidate: builtinValidate,
128
+ builtinSemanticOnly: builtinSemanticOnly,
129
+ _loadAjvValidator: loadAjvValidator,
130
+ _resetValidatorCache: _resetValidatorCache,
131
+ };
@@ -0,0 +1,159 @@
1
+ /**
2
+ * claude-md-injector - Inject doukui rules into CLAUDE.md
3
+ *
4
+ * Scans all skill plugins for plan_mode_required declarations and injects
5
+ * Plan Mode priority rules into the target project's CLAUDE.md file.
6
+ * Supports idempotent updates using marker-based block replacement.
7
+ *
8
+ * @module claude-md-injector
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ var fs = require('fs');
14
+ var path = require('path');
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Constants
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /**
21
+ * Block marker for doukui managed rules in CLAUDE.md.
22
+ * @type {string}
23
+ */
24
+ var CLAUDE_MD_MARKER = '<!-- doukui -->';
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Public API
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * Build the rule block content for CLAUDE.md injection.
32
+ * Scans plugin entries for plan_mode_required skills.
33
+ *
34
+ * @public
35
+ * @param {object[]} pluginEntries - enabled plugin entries from registry
36
+ * @param {Function} resolvePluginDir - function(entry) => string, resolves plugin directory
37
+ * @returns {string} rule block content (empty string if no plan_mode_required skills)
38
+ */
39
+ function buildRuleBlock(pluginEntries, resolvePluginDir) {
40
+ var planModeSkills = [];
41
+
42
+ for (var i = 0; i < pluginEntries.length; i++) {
43
+ var entry = pluginEntries[i];
44
+ var pluginDir = resolvePluginDir(entry);
45
+ var metaPath = path.join(pluginDir, 'plugin.json');
46
+
47
+ if (!fs.existsSync(metaPath)) continue;
48
+
49
+ try {
50
+ var meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
51
+ if (meta.type !== 'skill') continue;
52
+
53
+ // Check plan_mode_required in plugin.json config or in skill.md front-matter
54
+ var hasPlanMode = false;
55
+
56
+ if (meta.config && meta.config.plan_mode_required) {
57
+ hasPlanMode = true;
58
+ }
59
+
60
+ if (!hasPlanMode) {
61
+ var skillMdPath = path.join(pluginDir, 'skill.md');
62
+ if (fs.existsSync(skillMdPath)) {
63
+ var content = fs.readFileSync(skillMdPath, 'utf-8');
64
+ if (/^---[\s\S]*?plan_mode_required:\s*true[\s\S]*?---/.test(content)) {
65
+ hasPlanMode = true;
66
+ }
67
+ }
68
+ }
69
+
70
+ if (hasPlanMode) {
71
+ planModeSkills.push(meta.name || entry.name);
72
+ }
73
+ } catch (e) {
74
+ // skip unparseable plugins
75
+ }
76
+ }
77
+
78
+ if (planModeSkills.length === 0) return '';
79
+
80
+ var lines = [CLAUDE_MD_MARKER];
81
+ lines.push('');
82
+ lines.push('## Harness Plan Mode 优先级规则');
83
+ lines.push('');
84
+ lines.push('当以下 skill 被触发时,必须直接调用 `EnterPlanMode` 进入 Plan 模式,不得先执行 brainstorming 或其他分析工作:');
85
+ lines.push('');
86
+
87
+ for (var j = 0; j < planModeSkills.length; j++) {
88
+ lines.push('- `' + planModeSkills[j] + '`');
89
+ }
90
+
91
+ lines.push('');
92
+ lines.push('这些 skill 的 skill.md 中已标注 `plan_mode_required: true`,优先级高于 superpowers:brainstorming。');
93
+ lines.push('收到匹配上述 skill 的请求时,跳过 brainstorming 检查,立即进入 Plan 模式。');
94
+ lines.push('');
95
+ lines.push(CLAUDE_MD_MARKER);
96
+
97
+ return lines.join('\n');
98
+ }
99
+
100
+ /**
101
+ * Inject doukui managed rules into the target project's CLAUDE.md.
102
+ * Idempotent: replaces existing marked block if present, appends if not.
103
+ * Creates CLAUDE.md if it does not exist.
104
+ *
105
+ * @public
106
+ * @param {object} options
107
+ * @param {string} options.targetRoot - target project root directory
108
+ * @param {object[]} options.pluginEntries - enabled plugin entries
109
+ * @param {Function} options.resolvePluginDir - plugin directory resolver function
110
+ * @param {Function} [options.log] - logging function(level, message)
111
+ */
112
+ function injectClaudeMdRules(options) {
113
+ var targetRoot = options.targetRoot;
114
+ var pluginEntries = options.pluginEntries;
115
+ var resolvePluginDir = options.resolvePluginDir;
116
+ var log = options.log || function () {};
117
+
118
+ var ruleBlock = buildRuleBlock(pluginEntries, resolvePluginDir);
119
+ if (!ruleBlock) {
120
+ log('info', 'No plan_mode_required skills found, skipping CLAUDE.md injection.');
121
+ return;
122
+ }
123
+
124
+ var claudeMdPath = path.join(targetRoot, 'CLAUDE.md');
125
+ var content = '';
126
+
127
+ if (fs.existsSync(claudeMdPath)) {
128
+ content = fs.readFileSync(claudeMdPath, 'utf-8');
129
+ }
130
+
131
+ // Check if existing block is present and identical
132
+ var startIdx = content.indexOf(CLAUDE_MD_MARKER);
133
+ if (startIdx !== -1) {
134
+ var endIdx = content.indexOf(CLAUDE_MD_MARKER, startIdx + CLAUDE_MD_MARKER.length);
135
+ if (endIdx !== -1) {
136
+ var existingBlock = content.substring(startIdx, endIdx + CLAUDE_MD_MARKER.length);
137
+ if (existingBlock === ruleBlock) {
138
+ log('info', 'CLAUDE.md rules up-to-date, no changes needed.');
139
+ return;
140
+ }
141
+ // Replace existing block
142
+ content = content.substring(0, startIdx) + ruleBlock + content.substring(endIdx + CLAUDE_MD_MARKER.length);
143
+ fs.writeFileSync(claudeMdPath, content, 'utf-8');
144
+ log('info', 'CLAUDE.md rules updated.');
145
+ return;
146
+ }
147
+ }
148
+
149
+ // Append new block
150
+ var separator = content.length > 0 && !content.endsWith('\n') ? '\n\n' : '\n';
151
+ fs.writeFileSync(claudeMdPath, content + separator + ruleBlock + '\n', 'utf-8');
152
+ log('info', 'CLAUDE.md rules injected.');
153
+ }
154
+
155
+ module.exports = {
156
+ buildRuleBlock: buildRuleBlock,
157
+ injectClaudeMdRules: injectClaudeMdRules,
158
+ CLAUDE_MD_MARKER: CLAUDE_MD_MARKER,
159
+ };