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,182 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Plugin Trust(WP-D8 sandbox 轻量强制化)
5
+ // ---------------------------------------------------------------------------
6
+ // 背景见 docs/design/sandbox-threat-model.md:真隔离不存在(main-process
7
+ // require 全权限),capabilities 声明此前是纯装饰。本模块把「声明」升级为
8
+ // 「可检查声明」+「知情记录」,不提供假隔离:
9
+ //
10
+ // 1. capabilities 扫描:加载前 grep 插件 index.js 的危险 require
11
+ // (child_process / fs / net / http / worker_threads),与 plugin.json
12
+ // capabilities 声明比对——声明 forbidden 却出现对应 require → violation
13
+ // (高亮警告;无法真正阻止 require,但把「声明与行为不符」显式化)
14
+ // 2. 信任记录:首次加载的第三方插件记入 {stateDir}/trusted-plugins.json
15
+ // (name + sha1(index.js)),重复加载降为一行提示(不刷屏)
16
+ // 3. 严格模式:DOUKUI_STRICT_PLUGINS=1 时,未在信任记录中的第三方插件
17
+ // 直接拒绝加载(显式 opt-in 的强约束,供安全敏感环境使用)
18
+ //
19
+ // 边界(诚实声明):源码扫描可被动态 require / 混淆绕过——它是「知情辅助」
20
+ // 而非安全边界。真正的隔离仍不可行(见 threat model)。
21
+ // ---------------------------------------------------------------------------
22
+
23
+ var fs = require('fs');
24
+ var path = require('path');
25
+ var crypto = require('crypto');
26
+
27
+ // 危险模块 → capabilities 键映射(声明 forbidden/deny 却 require → violation)
28
+ var DANGEROUS_REQUIRES = [
29
+ { re: /require\s*\(\s*['"]child_process['"]\s*\)/g, cap: 'child_process', label: 'child_process' },
30
+ { re: /require\s*\(\s*['"]fs['"]\s*\)/g, cap: 'filesystem', label: 'fs' },
31
+ { re: /require\s*\(\s*['"](net|dgram|tls)['"]\s*\)/g, cap: 'network', label: 'net/tls/dgram' },
32
+ { re: /require\s*\(\s*['"](http|https|http2)['"]\s*\)/g, cap: 'network', label: 'http/https' },
33
+ { re: /require\s*\(\s*['"]worker_threads['"]\s*\)/g, cap: 'worker_threads', label: 'worker_threads' },
34
+ { re: /require\s*\(\s*['"]process['"]\s*\)|global\.process(?!\w)/g, cap: 'process_env', label: 'process' },
35
+ ];
36
+
37
+ /**
38
+ * 扫描插件入口源码的危险 require,与 capabilities 声明比对。
39
+ * @param {string} indexJsPath 插件 index.js 绝对路径
40
+ * @param {object|null} pluginJson 插件清单(capabilities 段可省略)
41
+ * @returns {{ violations: Array<{module:string,cap:string,declared:string}>, hash: string }}
42
+ * violations 空 = 声明与行为一致(或无声明,只报 hash)
43
+ */
44
+ function scanCapabilities(indexJsPath, pluginJson) {
45
+ var src = '';
46
+ try {
47
+ src = fs.readFileSync(indexJsPath, 'utf8');
48
+ } catch (_e) {
49
+ return { violations: [], hash: '' };
50
+ }
51
+ var hash = crypto.createHash('sha1').update(src, 'utf8').digest('hex');
52
+ var caps = (pluginJson && pluginJson.capabilities) || {};
53
+ var violations = [];
54
+ for (var i = 0; i < DANGEROUS_REQUIRES.length; i++) {
55
+ var d = DANGEROUS_REQUIRES[i];
56
+ var re = new RegExp(d.re.source, 'g'); // 重置 lastIndex
57
+ var hits = 0;
58
+ var m;
59
+ while ((m = re.exec(src)) !== null) { hits++; if (hits > 0) break; }
60
+ if (hits === 0) continue;
61
+ var declared = caps[d.cap];
62
+ var declaredStr = (declared === undefined || declared === null) ? '(未声明)' : String(declared);
63
+ // declared 为 forbidden/deny/never/false 之一 → 声明与行为不符
64
+ var forbiddenLike = ['forbidden', 'deny', 'denied', 'never', 'false'].indexOf(
65
+ String(declared).toLowerCase()) !== -1;
66
+ if (forbiddenLike) {
67
+ violations.push({ module: d.label, cap: d.cap, declared: declaredStr });
68
+ }
69
+ }
70
+ return { violations: violations, hash: hash };
71
+ }
72
+
73
+ function trustFilePath(stateDir) {
74
+ return path.join(stateDir, 'trusted-plugins.json');
75
+ }
76
+
77
+ /**
78
+ * 读取信任记录。
79
+ * @param {string} stateDir 项目 state 目录(.doukui-state 或 .doukui)
80
+ * @returns {Object<string, { hash: string, trustedAt: string }>}
81
+ */
82
+ function readTrust(stateDir) {
83
+ try {
84
+ var raw = JSON.parse(fs.readFileSync(trustFilePath(stateDir), 'utf8'));
85
+ return (raw && typeof raw.plugins === 'object' && raw.plugins) || {};
86
+ } catch (_e) {
87
+ return {};
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 记录信任(首次知情加载后写入;幂等)。
93
+ * @param {string} stateDir
94
+ * @param {string} pluginName
95
+ * @param {string} indexHash scanCapabilities 的 hash
96
+ * @returns {boolean} 是否实际写入
97
+ */
98
+ function recordTrust(stateDir, pluginName, indexHash) {
99
+ var file = trustFilePath(stateDir);
100
+ var data;
101
+ try {
102
+ data = JSON.parse(fs.readFileSync(file, 'utf8'));
103
+ if (!data || typeof data.plugins !== 'object') data = { plugins: {} };
104
+ } catch (_e) {
105
+ data = { plugins: {} };
106
+ }
107
+ if (data.plugins[pluginName] && data.plugins[pluginName].hash === indexHash) {
108
+ return false; // 已记录且内容未变
109
+ }
110
+ data.plugins[pluginName] = { hash: indexHash, trustedAt: new Date().toISOString() };
111
+ try {
112
+ fs.mkdirSync(path.dirname(file), { recursive: true });
113
+ fs.writeFileSync(file, JSON.stringify(data, null, 2), 'utf8');
114
+ return true;
115
+ } catch (_e) {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * 加载门禁综合评估。
122
+ *
123
+ * 语义(WP-D8 双跑验证后的裁决):**信任记录只服务两件事——strict 模式的
124
+ * 放行/拒绝判定 + 审计痕迹**。非 strict(常规)模式下,第三方插件每次加载
125
+ * 都必须发 warn(S3 精神:外部代码跑在主进程,这一事实本身就该始终可见,
126
+ * 不能被「曾经信任过」静默掉——信任记录降噪会让披露吞没)。
127
+ *
128
+ * @param {object} opts
129
+ * @param {string} opts.pluginName
130
+ * @param {{violations:Array,hash:string}} opts.scan scanCapabilities 产物
131
+ * @param {string} opts.stateDir
132
+ * @param {boolean} [opts.strict] DOUKUI_STRICT_PLUGINS=1
133
+ * @returns {{ allowed: boolean, firstTime: boolean, messages: string[] }}
134
+ */
135
+ function evaluateLoad(opts) {
136
+ opts = opts || {};
137
+ var messages = [];
138
+ var trust = readTrust(opts.stateDir);
139
+ var known = trust[opts.pluginName];
140
+ var hashUnchanged = !!(known && known.hash === opts.scan.hash);
141
+ var firstTime = !known;
142
+
143
+ if (opts.scan.violations.length > 0) {
144
+ for (var i = 0; i < opts.scan.violations.length; i++) {
145
+ var v = opts.scan.violations[i];
146
+ messages.push('⚠ CAPABILITY VIOLATION: plugin "' + opts.pluginName +
147
+ '" declares ' + v.cap + '=' + v.declared + ' but requires ' + v.module);
148
+ }
149
+ }
150
+ if (!hashUnchanged) {
151
+ // 首次加载 或 代码较上次信任记录已变化 → 完整披露
152
+ messages.push('Loading third-party plugin "' + opts.pluginName +
153
+ '" — the sandbox is decorative and is NOT enforced; this plugin runs with full ' +
154
+ 'main-process privileges.' + (firstTime
155
+ ? ' Recorded to ' + trustFilePath(opts.stateDir) + '.'
156
+ : ' Code changed since last trust record.') +
157
+ ' (see docs/design/sandbox-threat-model.md)');
158
+ } else {
159
+ // 已信任且未变:常规模式保持一行披露(不静默——S3 精神)
160
+ messages.push('Loading trusted third-party plugin "' + opts.pluginName +
161
+ '" (hash unchanged) — the sandbox is decorative and is NOT enforced; full main-process privileges');
162
+ }
163
+
164
+ var strict = opts.strict === true;
165
+ var allowed = true;
166
+ if (strict && (firstTime || !hashUnchanged)) {
167
+ allowed = false;
168
+ messages.push('STRICT MODE: plugin "' + opts.pluginName +
169
+ '" is not (or no longer) in the trust record. Load it once with strict mode off ' +
170
+ '(or remove DOUKUI_STRICT_PLUGINS=1) to record trust.');
171
+ }
172
+ return { allowed: allowed, firstTime: firstTime, messages: messages };
173
+ }
174
+
175
+ module.exports = {
176
+ scanCapabilities: scanCapabilities,
177
+ readTrust: readTrust,
178
+ recordTrust: recordTrust,
179
+ evaluateLoad: evaluateLoad,
180
+ trustFilePath: trustFilePath,
181
+ _DANGEROUS_REQUIRES: DANGEROUS_REQUIRES,
182
+ };
@@ -0,0 +1,491 @@
1
+ /**
2
+ * plugin-validator - Plugin format validation
3
+ *
4
+ * Validates plugin.json format, required fields, type compliance, and
5
+ * companion file existence. Also validates capabilities schema introduced
6
+ * in v0.2.0 and JSON Schema formal validation (WP-115).
7
+ *
8
+ * Usage:
9
+ * const pluginValidator = require('./plugin-validator');
10
+ * const result = pluginValidator.validatePlugin(entry, pluginDir);
11
+ * const capWarnings = pluginValidator.validateCapabilities(meta.capabilities);
12
+ * const schemaResult = pluginValidator.validateWithSchema(meta);
13
+ *
14
+ * @module plugin-validator
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ var fs = require('fs');
20
+ var path = require('path');
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Constants
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /**
27
+ * Required fields in every plugin.json.
28
+ * @public
29
+ * @type {string[]}
30
+ */
31
+ var PLUGIN_REQUIRED_FIELDS = ['name', 'version', 'type', 'description'];
32
+
33
+ /**
34
+ * Valid plugin type values.
35
+ * @public
36
+ * @type {string[]}
37
+ */
38
+ var VALID_PLUGIN_TYPES = ['skill', 'hook', 'validator', 'provider'];
39
+
40
+ /**
41
+ * Known capability names recognized by doukui.
42
+ * Unknown capability names will generate warnings (non-blocking).
43
+ * @internal Use getKnownCapabilities() for public access
44
+ * @type {string[]}
45
+ */
46
+ var KNOWN_CAPABILITIES = ['filesystem', 'network', 'child_process', 'env', 'plugin_access'];
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Plugin validation
50
+ // ---------------------------------------------------------------------------
51
+
52
+ /**
53
+ * Validate a single plugin entry.
54
+ *
55
+ * Checks:
56
+ * 1. Plugin directory exists
57
+ * 2. plugin.json exists and is valid JSON
58
+ * 3. Required fields (name, version, type, description)
59
+ * 4. Plugin type is valid
60
+ * 5. Type-specific companion files (skill.md for skills, index.js for hooks)
61
+ * 6. Version follows semver format (warning only)
62
+ *
63
+ * @public
64
+ * @param {object} entry - registry entry with at least a name field
65
+ * @param {string} pluginDir - resolved plugin directory path
66
+ * @returns {{ errors: object[], warnings: object[] }}
67
+ */
68
+ function validatePlugin(entry, pluginDir) {
69
+ var errors = [];
70
+ var warnings = [];
71
+ var pluginName = entry.name || entry.source || 'unknown';
72
+
73
+ // 1. Check plugin directory exists
74
+ if (!fs.existsSync(pluginDir)) {
75
+ errors.push({
76
+ plugin: pluginName,
77
+ field: 'directory',
78
+ message: 'Plugin directory not found: ' + pluginDir,
79
+ });
80
+ return { errors: errors, warnings: warnings }; // can't validate further
81
+ }
82
+
83
+ // 2. Check plugin.json exists
84
+ var metaPath = path.join(pluginDir, 'plugin.json');
85
+ if (!fs.existsSync(metaPath)) {
86
+ errors.push({
87
+ plugin: pluginName,
88
+ field: 'plugin.json',
89
+ message: 'plugin.json not found in ' + pluginDir,
90
+ });
91
+ return { errors: errors, warnings: warnings };
92
+ }
93
+
94
+ // 3. Parse and validate plugin.json
95
+ var meta;
96
+ try {
97
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
98
+ } catch (err) {
99
+ errors.push({
100
+ plugin: pluginName,
101
+ field: 'plugin.json',
102
+ message: 'Invalid JSON in plugin.json: ' + err.message,
103
+ });
104
+ return { errors: errors, warnings: warnings };
105
+ }
106
+
107
+ // 4. Check required fields
108
+ for (var i = 0; i < PLUGIN_REQUIRED_FIELDS.length; i++) {
109
+ var field = PLUGIN_REQUIRED_FIELDS[i];
110
+ if (!meta[field]) {
111
+ errors.push({
112
+ plugin: pluginName,
113
+ field: field,
114
+ message: 'Missing required field: ' + field,
115
+ });
116
+ }
117
+ }
118
+
119
+ // 5. Check plugin type is valid
120
+ if (meta.type && VALID_PLUGIN_TYPES.indexOf(meta.type) === -1) {
121
+ errors.push({
122
+ plugin: pluginName,
123
+ field: 'type',
124
+ message: 'Invalid plugin type: "' + meta.type + '". Must be one of: ' + VALID_PLUGIN_TYPES.join(', '),
125
+ });
126
+ }
127
+
128
+ // 5.5 JSON Schema formal validation (WP-115)
129
+ var schemaResult = validateWithSchema(meta);
130
+ if (!schemaResult.valid) {
131
+ for (var si = 0; si < schemaResult.errors.length; si++) {
132
+ var schemaErr = schemaResult.errors[si];
133
+ // Skip duplicate required-field errors already reported in step 4
134
+ if (schemaErr.message && schemaErr.message.indexOf('Missing required') === 0) {
135
+ continue;
136
+ }
137
+ errors.push({
138
+ plugin: pluginName,
139
+ field: schemaErr.field,
140
+ message: '[schema] ' + schemaErr.message,
141
+ });
142
+ }
143
+ }
144
+
145
+ // 6. Type-specific file checks
146
+ if (meta.type === 'skill') {
147
+ var skillMdPath = path.join(pluginDir, 'skill.md');
148
+ if (!fs.existsSync(skillMdPath)) {
149
+ errors.push({
150
+ plugin: pluginName,
151
+ field: 'skill.md',
152
+ message: 'Skill plugin is missing skill.md file',
153
+ });
154
+ }
155
+ }
156
+
157
+ if (meta.type === 'hook') {
158
+ var indexPath = path.join(pluginDir, 'index.js');
159
+ if (!fs.existsSync(indexPath)) {
160
+ warnings.push({
161
+ plugin: pluginName,
162
+ field: 'index.js',
163
+ message: 'Hook plugin is missing index.js file (build will generate stub)',
164
+ });
165
+ }
166
+ }
167
+
168
+ // 7. Version format check (basic semver)
169
+ if (meta.version && !/^\d+\.\d+\.\d+/.test(meta.version)) {
170
+ warnings.push({
171
+ plugin: pluginName,
172
+ field: 'version',
173
+ message: 'Version "' + meta.version + '" does not follow semver format (x.y.z)',
174
+ });
175
+ }
176
+
177
+ return { errors: errors, warnings: warnings };
178
+ }
179
+
180
+ /**
181
+ * Format validation results into a human-readable summary.
182
+ *
183
+ * @public
184
+ * @param {object} options
185
+ * @param {number} options.totalPlugins - total plugins checked
186
+ * @param {object[]} options.errors - validation errors
187
+ * @param {object[]} options.warnings - validation warnings
188
+ * @returns {string} formatted summary string
189
+ */
190
+ function formatValidationSummary(options) {
191
+ var totalPlugins = options.totalPlugins;
192
+ var errors = options.errors;
193
+ var warnings = options.warnings;
194
+
195
+ var lines = [];
196
+ lines.push('');
197
+ lines.push('=== Validation Report ===');
198
+ lines.push('Plugins checked: ' + totalPlugins);
199
+ lines.push('Errors: ' + errors.length);
200
+ lines.push('Warnings: ' + warnings.length);
201
+
202
+ if (errors.length > 0) {
203
+ lines.push('');
204
+ lines.push('--- Errors ---');
205
+ for (var i = 0; i < errors.length; i++) {
206
+ var e = errors[i];
207
+ lines.push(' [' + e.plugin + '] ' + e.message);
208
+ }
209
+ }
210
+
211
+ if (warnings.length > 0) {
212
+ lines.push('');
213
+ lines.push('--- Warnings ---');
214
+ for (var j = 0; j < warnings.length; j++) {
215
+ var w = warnings[j];
216
+ lines.push(' [' + w.plugin + '] ' + w.message);
217
+ }
218
+ }
219
+
220
+ lines.push('');
221
+ lines.push(errors.length === 0 ? 'Validation PASSED' : 'Validation FAILED');
222
+ lines.push('');
223
+
224
+ return lines.join('\n');
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Capabilities validation (v0.2.0)
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /**
232
+ * Validate the capabilities field of a plugin.json.
233
+ *
234
+ * Checks that each declared capability key is a known capability name.
235
+ * Unknown names produce warnings but do not block the build.
236
+ *
237
+ * @public
238
+ * @param {object|null|undefined} capabilities - The capabilities field from plugin.json
239
+ * @returns {object[]} Array of warning objects: { field: string, message: string }
240
+ */
241
+ function validateCapabilities(capabilities) {
242
+ var warnings = [];
243
+
244
+ if (!capabilities) {
245
+ return warnings;
246
+ }
247
+
248
+ // Capabilities must be an object
249
+ if (typeof capabilities !== 'object' || Array.isArray(capabilities)) {
250
+ warnings.push({
251
+ field: 'capabilities',
252
+ message: 'capabilities must be an object, got ' + (Array.isArray(capabilities) ? 'array' : typeof capabilities),
253
+ });
254
+ return warnings;
255
+ }
256
+
257
+ var keys = Object.keys(capabilities);
258
+ for (var i = 0; i < keys.length; i++) {
259
+ var key = keys[i];
260
+ if (KNOWN_CAPABILITIES.indexOf(key) === -1) {
261
+ warnings.push({
262
+ field: 'capabilities.' + key,
263
+ message: 'Unknown capability: "' + key + '". Known capabilities: ' + KNOWN_CAPABILITIES.join(', '),
264
+ });
265
+ }
266
+ }
267
+
268
+ return warnings;
269
+ }
270
+
271
+ /**
272
+ * Get the list of known capability names.
273
+ * Useful for tests and external consumers.
274
+ *
275
+ * @public
276
+ * @returns {string[]}
277
+ */
278
+ function getKnownCapabilities() {
279
+ return KNOWN_CAPABILITIES.slice();
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // JSON Schema validation (WP-115)
284
+ // ---------------------------------------------------------------------------
285
+
286
+ /**
287
+ * Cached JSON Schema object, loaded lazily on first use.
288
+ * @type {object|null|undefined}
289
+ */
290
+ var _cachedSchema = undefined;
291
+
292
+ /**
293
+ * Load the plugin.json JSON Schema definition.
294
+ * Cached after first load.
295
+ *
296
+ * @internal
297
+ * @returns {object|null} The parsed schema object, or null if not found.
298
+ */
299
+ function loadPluginSchema() {
300
+ if (_cachedSchema !== undefined) {
301
+ return _cachedSchema;
302
+ }
303
+ var schemaPath = path.join(
304
+ __dirname, '..', 'contracts', 'plugin-schema.json'
305
+ );
306
+ try {
307
+ var content = fs.readFileSync(schemaPath, 'utf-8');
308
+ _cachedSchema = JSON.parse(content);
309
+ } catch (err) {
310
+ _cachedSchema = null;
311
+ }
312
+ return _cachedSchema;
313
+ }
314
+
315
+ /**
316
+ * Try to require the ajv module (optional dependency).
317
+ * Returns null if ajv is not available.
318
+ *
319
+ * @internal
320
+ * @returns {object|null} The Ajv constructor, or null.
321
+ */
322
+ function _tryLoadAjv() {
323
+ try {
324
+ // eslint-disable-next-line no-redeclare
325
+ var Ajv = require('ajv');
326
+ return Ajv;
327
+ } catch (err) {
328
+ return null;
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Validate a plugin.json object against the formal JSON Schema.
334
+ *
335
+ * Attempts to use ajv if available (optionalDependencies), otherwise
336
+ * falls back to inline validation covering required fields, type checks,
337
+ * and enum constraints defined in the schema.
338
+ *
339
+ * @public
340
+ * @param {object} pluginJson - The parsed plugin.json object.
341
+ * @returns {{ valid: boolean, errors: object[] }} Validation result.
342
+ */
343
+ function validateWithSchema(pluginJson) {
344
+ var schema = loadPluginSchema();
345
+ if (!schema) {
346
+ return { valid: true, errors: [] };
347
+ }
348
+
349
+ // Try ajv-based validation first
350
+ var Ajv = _tryLoadAjv();
351
+ if (Ajv) {
352
+ var ajv = new Ajv({ allErrors: true });
353
+ var validate = ajv.compile(schema);
354
+ var valid = validate(pluginJson);
355
+ if (valid) {
356
+ return { valid: true, errors: [] };
357
+ }
358
+ var errors = (validate.errors || []).map(function (e) {
359
+ return {
360
+ field: e.instancePath ? e.instancePath.slice(1) : (e.params || {}).missingProperty || '',
361
+ message: e.message || 'Schema validation error',
362
+ schemaError: true,
363
+ };
364
+ });
365
+ return { valid: false, errors: errors };
366
+ }
367
+
368
+ // Fallback: inline validation matching schema constraints
369
+ return _inlineSchemaValidate(pluginJson, schema);
370
+ }
371
+
372
+ /**
373
+ * Inline schema validation fallback.
374
+ * Covers required fields, type checks, patterns, and enums.
375
+ *
376
+ * @param {object} pluginJson - The parsed plugin.json object.
377
+ * @param {object} schema - The loaded JSON Schema.
378
+ * @returns {{ valid: boolean, errors: object[] }}
379
+ * @private
380
+ */
381
+ function _inlineSchemaValidate(pluginJson, schema) {
382
+ var errors = [];
383
+
384
+ // Required fields
385
+ var required = schema.required || [];
386
+ for (var i = 0; i < required.length; i++) {
387
+ if (!pluginJson[required[i]]) {
388
+ errors.push({
389
+ field: required[i],
390
+ message: 'Missing required property: ' + required[i],
391
+ schemaError: true,
392
+ });
393
+ }
394
+ }
395
+
396
+ // Check each property against schema definition
397
+ var props = schema.properties || {};
398
+ var propNames = Object.keys(props);
399
+ for (var j = 0; j < propNames.length; j++) {
400
+ var propName = propNames[j];
401
+ var propVal = pluginJson[propName];
402
+ var propSchema = props[propName];
403
+
404
+ if (propVal === undefined || propVal === null) {
405
+ continue; // optional field not present
406
+ }
407
+
408
+ // Type check
409
+ if (propSchema.type) {
410
+ var actualType = Array.isArray(propVal) ? 'array' : typeof propVal;
411
+ if (actualType !== propSchema.type) {
412
+ errors.push({
413
+ field: propName,
414
+ message: 'Property "' + propName + '" must be ' + propSchema.type + ', got ' + actualType,
415
+ schemaError: true,
416
+ });
417
+ continue;
418
+ }
419
+ }
420
+
421
+ // Enum check
422
+ if (propSchema.enum) {
423
+ if (propSchema.enum.indexOf(propVal) === -1) {
424
+ errors.push({
425
+ field: propName,
426
+ message: 'Property "' + propName + '" must be one of: ' + propSchema.enum.join(', '),
427
+ schemaError: true,
428
+ });
429
+ }
430
+ }
431
+
432
+ // Pattern check (for strings)
433
+ if (propSchema.pattern && typeof propVal === 'string') {
434
+ var regex = new RegExp(propSchema.pattern);
435
+ if (!regex.test(propVal)) {
436
+ errors.push({
437
+ field: propName,
438
+ message: 'Property "' + propName + '" does not match pattern: ' + propSchema.pattern,
439
+ schemaError: true,
440
+ });
441
+ }
442
+ }
443
+
444
+ // minLength check (for strings)
445
+ if (propSchema.minLength !== undefined && typeof propVal === 'string') {
446
+ if (propVal.length < propSchema.minLength) {
447
+ errors.push({
448
+ field: propName,
449
+ message: 'Property "' + propName + '" must have minLength ' + propSchema.minLength,
450
+ schemaError: true,
451
+ });
452
+ }
453
+ }
454
+
455
+ // additionalProperties check for objects
456
+ if (propSchema.additionalProperties === false && typeof propVal === 'object' && !Array.isArray(propVal)) {
457
+ var allowedKeys = Object.keys(propSchema.properties || {});
458
+ var actualKeys = Object.keys(propVal);
459
+ for (var k = 0; k < actualKeys.length; k++) {
460
+ if (allowedKeys.indexOf(actualKeys[k]) === -1) {
461
+ errors.push({
462
+ field: propName + '.' + actualKeys[k],
463
+ message: 'Additional property "' + actualKeys[k] + '" is not allowed in "' + propName + '"',
464
+ schemaError: true,
465
+ });
466
+ }
467
+ }
468
+ }
469
+ }
470
+
471
+ return {
472
+ valid: errors.length === 0,
473
+ errors: errors,
474
+ };
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // Module exports
479
+ // ---------------------------------------------------------------------------
480
+
481
+ module.exports = {
482
+ validatePlugin: validatePlugin,
483
+ formatValidationSummary: formatValidationSummary,
484
+ PLUGIN_REQUIRED_FIELDS: PLUGIN_REQUIRED_FIELDS,
485
+ VALID_PLUGIN_TYPES: VALID_PLUGIN_TYPES,
486
+ validateCapabilities: validateCapabilities,
487
+ getKnownCapabilities: getKnownCapabilities,
488
+ KNOWN_CAPABILITIES: KNOWN_CAPABILITIES,
489
+ validateWithSchema: validateWithSchema,
490
+ loadPluginSchema: loadPluginSchema,
491
+ };