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,692 @@
1
+ /**
2
+ * yaml-parser - Hand-written YAML parser for harness-config.yaml
3
+ *
4
+ * Supports a limited YAML subset: flat key-value pairs, single-level lists,
5
+ * and single-level nested objects. Designed for parsing harness-config.yaml
6
+ * sections — any top-level key is automatically detected as a section.
7
+ *
8
+ * Limitations:
9
+ * - No multi-line strings
10
+ * - No anchors/aliases
11
+ * - No flow-style collections
12
+ * - Unsupported features are silently ignored
13
+ *
14
+ * @module yaml-parser
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ var fs = require('fs');
20
+
21
+ // Security limits
22
+ var MAX_YAML_SIZE = 102400; // 100KB
23
+ var MAX_DEPTH = 10;
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Scalar parsing
27
+ // ---------------------------------------------------------------------------
28
+
29
+ /**
30
+ * Parse a YAML scalar value.
31
+ *
32
+ * @public
33
+ * @param {string} val - raw string value (already trimmed, comments stripped)
34
+ * @returns {boolean|null|number|string} parsed value
35
+ */
36
+ function parseValue(val) {
37
+ if (val === 'true') return true;
38
+ if (val === 'false') return false;
39
+ if (val === 'null' || val === '~') return null;
40
+ // B12: require length >= 2 before treating as a quoted string, so a lone
41
+ // quote char (e.g. '"') is not truncated to '' and an unbalanced leading
42
+ // quote (e.g. '"hello') is returned verbatim rather than stripped.
43
+ if (val.length >= 2 &&
44
+ ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') ||
45
+ (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'"))) {
46
+ var content = val.substring(1, val.length - 1);
47
+ // 双引号字符串处理转义字符(YAML 规范)
48
+ if (val.charAt(0) === '"') {
49
+ content = content.replace(/\\(.)/g, function (_, ch) {
50
+ switch (ch) {
51
+ case '\\': return '\\';
52
+ case '"': return '"';
53
+ case 'n': return '\n';
54
+ case 't': return '\t';
55
+ case 'r': return '\r';
56
+ default: return '\\' + ch;
57
+ }
58
+ });
59
+ }
60
+ return content;
61
+ }
62
+ // Inline flow array: [a, b, "c"] (S8 consolidation — adopted from
63
+ // config-validator's parseValue so the shared parser covers the same surface).
64
+ if (val.charAt(0) === '[' && val.charAt(val.length - 1) === ']') {
65
+ return _parseInlineArray(val);
66
+ }
67
+ var num = Number(val);
68
+ if (!isNaN(num) && val !== '') return num;
69
+ return val;
70
+ }
71
+
72
+ /**
73
+ * Parse a YAML inline (flow-style) array `[a, b, "c"]` into a JS array.
74
+ * Respects quoted strings and commas inside quotes. Used by parseValue.
75
+ * @internal
76
+ * @param {string} val - starts with '[' and ends with ']'
77
+ * @returns {Array}
78
+ */
79
+ function _parseInlineArray(val) {
80
+ var inner = val.substring(1, val.length - 1).trim();
81
+ if (inner === '') return [];
82
+ var items = [];
83
+ var current = '';
84
+ var inQuotes = false;
85
+ var quoteChar = '';
86
+ for (var i = 0; i < inner.length; i++) {
87
+ var ch = inner.charAt(i);
88
+ if ((ch === '"' || ch === "'") && (i === 0 || inner.charAt(i - 1) !== '\\')) {
89
+ if (!inQuotes) {
90
+ inQuotes = true;
91
+ quoteChar = ch;
92
+ } else if (ch === quoteChar) {
93
+ inQuotes = false;
94
+ quoteChar = '';
95
+ } else {
96
+ current += ch;
97
+ }
98
+ } else if (ch === ',' && !inQuotes) {
99
+ items.push(parseValue(current.trim()));
100
+ current = '';
101
+ } else {
102
+ current += ch;
103
+ }
104
+ }
105
+ if (current.trim() !== '') {
106
+ items.push(parseValue(current.trim()));
107
+ }
108
+ return items;
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Block parsing
113
+ // ---------------------------------------------------------------------------
114
+
115
+ /**
116
+ * Parse a nested YAML block from raw string lines.
117
+ * Converts raw lines to {text, indent} objects, then delegates to parseChildLines.
118
+ *
119
+ * @internal
120
+ * @param {string[]} lines - all raw lines
121
+ * @param {number} startIdx - index of the first child line
122
+ * @param {number} parentIndent - indentation of the parent key
123
+ * @returns {{value: object|Array, endIdx: number}}
124
+ */
125
+ function parseNestedBlock(lines, startIdx, parentIndent, depth) {
126
+ if (depth === undefined) depth = 0;
127
+ if (depth > MAX_DEPTH) {
128
+ throw new Error('YAML nesting depth exceeds maximum allowed depth (' + MAX_DEPTH + ')');
129
+ }
130
+ var childLines = [];
131
+ var endIdx = startIdx;
132
+ for (var i = startIdx; i < lines.length; i++) {
133
+ var line = lines[i];
134
+ if (!line.trim() || line.trim().indexOf('#') === 0) continue;
135
+ var indent = line.search(/\S/);
136
+ if (indent <= parentIndent) break;
137
+ childLines.push({ text: line.trim(), indent: indent });
138
+ endIdx = i;
139
+ }
140
+
141
+ if (childLines.length === 0) {
142
+ return { value: {}, endIdx: startIdx - 1 };
143
+ }
144
+
145
+ return parseChildLines(childLines, endIdx, depth + 1);
146
+ }
147
+
148
+ /**
149
+ * Parse pre-collected child lines (always {text, indent} objects).
150
+ * Determines list vs object block and dispatches accordingly.
151
+ *
152
+ * @internal
153
+ * @param {object[]} childLines - {text, indent} objects
154
+ * @param {number} rawEndIdx - last index consumed
155
+ * @returns {{value: object|Array, endIdx: number}}
156
+ */
157
+ function parseChildLines(childLines, rawEndIdx, depth) {
158
+ if (depth === undefined) depth = 0;
159
+ if (depth > MAX_DEPTH) {
160
+ throw new Error('YAML nesting depth exceeds maximum allowed depth (' + MAX_DEPTH + ')');
161
+ }
162
+ var isList = childLines[0].text.indexOf('- ') === 0;
163
+ if (isList) {
164
+ return { value: parseListItems(childLines, depth), endIdx: rawEndIdx };
165
+ }
166
+ return { value: parseObjectItems(childLines, depth), endIdx: rawEndIdx };
167
+ }
168
+
169
+ /**
170
+ * Parse list items from child lines.
171
+ * Each "- " prefixed line starts a new item; subsequent more-indented lines
172
+ * belong to that item as nested properties.
173
+ *
174
+ * @internal
175
+ * @param {object[]} childLines - {text, indent} objects
176
+ * @returns {Array} parsed list
177
+ */
178
+ function parseListItems(childLines, depth) {
179
+ if (depth === undefined) depth = 0;
180
+ var arr = [];
181
+ var currentItem = null;
182
+ var itemStartIndent = -1;
183
+
184
+ for (var i = 0; i < childLines.length; i++) {
185
+ var cl = childLines[i];
186
+
187
+ if (cl.text.indexOf('- ') === 0) {
188
+ if (currentItem !== null) arr.push(currentItem);
189
+ var itemContent = cl.text.substring(2);
190
+ currentItem = parseLineAsObject(itemContent);
191
+ itemStartIndent = cl.indent;
192
+ } else if (currentItem !== null && cl.indent > itemStartIndent) {
193
+ var colonIdx = cl.text.indexOf(':');
194
+ if (colonIdx >= 0) {
195
+ var key = cl.text.substring(0, colonIdx).trim();
196
+ var val = cl.text.substring(colonIdx + 1).trim();
197
+ var commentIdx = val.indexOf(' #');
198
+ if (commentIdx >= 0) val = val.substring(0, commentIdx).trim();
199
+
200
+ if (val === '') {
201
+ // Nested object within list item — collect and parse children inline
202
+ var subChildren = collectChildren(childLines, i + 1, cl.indent);
203
+ var subResult = parseChildLines(subChildren, 0, depth + 1);
204
+ currentItem[key] = subResult.value;
205
+ i = subChildren.length > 0 ? childLines.indexOf(subChildren[subChildren.length - 1]) : i;
206
+ } else {
207
+ currentItem[key] = parseValue(val);
208
+ }
209
+ }
210
+ }
211
+ }
212
+ if (currentItem !== null) arr.push(currentItem);
213
+ return arr;
214
+ }
215
+
216
+ /**
217
+ * Collect consecutive child lines with indent > parentIndent,
218
+ * starting from startIdx in the childLines array.
219
+ *
220
+ * @internal
221
+ * @param {object[]} childLines - {text, indent} objects
222
+ * @param {number} startIdx - start index
223
+ * @param {number} parentIndent - parent indentation level
224
+ * @returns {object[]} collected child lines
225
+ */
226
+ function collectChildren(childLines, startIdx, parentIndent) {
227
+ var result = [];
228
+ for (var i = startIdx; i < childLines.length; i++) {
229
+ if (childLines[i].indent <= parentIndent) break;
230
+ result.push(childLines[i]);
231
+ }
232
+ return result;
233
+ }
234
+
235
+ /**
236
+ * Parse a single "- key: value" or "- value" line into an object.
237
+ *
238
+ * @internal
239
+ * @param {string} text - content after "- " prefix
240
+ * @returns {object|*} parsed object or scalar
241
+ */
242
+ function parseLineAsObject(text) {
243
+ var colonIdx = text.indexOf(':');
244
+ if (colonIdx >= 0) {
245
+ var key = text.substring(0, colonIdx).trim();
246
+ var val = text.substring(colonIdx + 1).trim();
247
+ var commentIdx = val.indexOf(' #');
248
+ if (commentIdx >= 0) val = val.substring(0, commentIdx).trim();
249
+ var obj = {};
250
+ obj[key] = val === '' ? {} : parseValue(val);
251
+ return obj;
252
+ }
253
+ return parseValue(text);
254
+ }
255
+
256
+ /**
257
+ * Parse object block (key-value pairs from child lines).
258
+ *
259
+ * @internal
260
+ * @param {object[]} childLines - {text, indent} objects
261
+ * @returns {object} parsed object
262
+ */
263
+ function parseObjectItems(childLines, depth) {
264
+ if (depth === undefined) depth = 0;
265
+ var obj = {};
266
+ for (var i = 0; i < childLines.length; i++) {
267
+ var cl = childLines[i];
268
+ var colonIdx = cl.text.indexOf(':');
269
+ if (colonIdx === -1) continue;
270
+
271
+ var key = cl.text.substring(0, colonIdx).trim();
272
+ var val = cl.text.substring(colonIdx + 1).trim();
273
+ var commentIdx = val.indexOf(' #');
274
+ if (commentIdx >= 0) val = val.substring(0, commentIdx).trim();
275
+
276
+ if (val === '') {
277
+ var subChildren = collectChildren(childLines, i + 1, cl.indent);
278
+ if (subChildren.length === 0) {
279
+ obj[key] = {};
280
+ } else {
281
+ var subResult = parseChildLines(subChildren, 0, depth + 1);
282
+ obj[key] = subResult.value;
283
+ }
284
+ i = childLines.indexOf(subChildren[subChildren.length - 1]);
285
+ } else {
286
+ obj[key] = parseValue(val);
287
+ }
288
+ }
289
+ return obj;
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // Public API
294
+ // ---------------------------------------------------------------------------
295
+
296
+ /**
297
+ * Parse a YAML file into a JavaScript object.
298
+ * Extracts multiple top-level sections (e.g. context_window, agent_dispatcher).
299
+ * Returns an object keyed by section name.
300
+ *
301
+ * @public
302
+ * @param {string} filePath - absolute path to the YAML file
303
+ * @returns {object} parsed configuration object, empty object on error
304
+ */
305
+ function parseYamlFile(filePath) {
306
+ try {
307
+ var content = fs.readFileSync(filePath, 'utf-8');
308
+ return parseYamlString(content);
309
+ } catch (err) {
310
+ // Re-throw security limit errors so callers are aware
311
+ if (err.message && (err.message.indexOf('maximum allowed size') !== -1 ||
312
+ err.message.indexOf('maximum allowed depth') !== -1)) {
313
+ throw err;
314
+ }
315
+ return {};
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Parse a YAML string into a JavaScript object.
321
+ * Extracts multiple top-level sections (e.g. context_window, agent_dispatcher).
322
+ * Returns an object keyed by section name.
323
+ *
324
+ * @public
325
+ * @param {string} content - YAML string content
326
+ * @returns {object} parsed configuration object, empty object on error
327
+ */
328
+ function parseYamlString(content) {
329
+ if (content && content.length > MAX_YAML_SIZE) {
330
+ throw new Error('YAML input exceeds maximum allowed size (' + MAX_YAML_SIZE + ' bytes)');
331
+ }
332
+ try {
333
+ var result = {};
334
+ var inSection = false;
335
+ var currentSection = null;
336
+ var sectionIndent = -1;
337
+ var lines = content.split('\n');
338
+
339
+ for (var i = 0; i < lines.length; i++) {
340
+ var line = lines[i];
341
+ var trimmed = line.trim();
342
+
343
+ // Detect section start — any top-level key (indent 0)
344
+ if (trimmed && trimmed.indexOf('#') !== 0 && trimmed !== '---' &&
345
+ line.search(/\S/) === 0 && /^([a-zA-Z_][a-zA-Z0-9_]*)\s*:/.test(trimmed)) {
346
+ inSection = true;
347
+ currentSection = trimmed.replace(/\s*:$/, '');
348
+ sectionIndent = 0;
349
+ result[currentSection] = {};
350
+ continue;
351
+ }
352
+
353
+ if (inSection && currentSection) {
354
+ // Stop at next top-level section (--- separator or same-indent key)
355
+ if (trimmed === '---' || (line.search(/\S/) >= 0 && line.search(/\S/) <= sectionIndent && !/^[\s#]/.test(trimmed) && trimmed.indexOf(currentSection) === -1 && /^[a-z_]/.test(trimmed))) {
356
+ inSection = false;
357
+ currentSection = null;
358
+ continue;
359
+ }
360
+
361
+ // Skip empty lines and comments
362
+ if (!trimmed || trimmed.indexOf('#') === 0) {
363
+ continue;
364
+ }
365
+
366
+ // Parse simple key-value pairs (flat or one level nested)
367
+ var colonIdx = trimmed.indexOf(':');
368
+ if (colonIdx === -1) continue;
369
+
370
+ var key = trimmed.substring(0, colonIdx).trim();
371
+ var valuePart = trimmed.substring(colonIdx + 1).trim();
372
+
373
+ // Remove inline comments
374
+ var commentIdx = valuePart.indexOf(' #');
375
+ if (commentIdx >= 0) {
376
+ valuePart = valuePart.substring(0, commentIdx).trim();
377
+ }
378
+
379
+ // Skip nested keys — delegate to parseNestedBlock
380
+ if (valuePart === '' || valuePart === null) {
381
+ var nestedIndent = lines[i] ? lines[i].search(/\S/) : -1;
382
+ var parsed = parseNestedBlock(lines, i + 1, nestedIndent);
383
+ result[currentSection][key] = parsed.value;
384
+ i = parsed.endIdx;
385
+ continue;
386
+ }
387
+
388
+ result[currentSection][key] = parseValue(valuePart);
389
+ }
390
+ }
391
+
392
+ return result;
393
+ } catch (err) {
394
+ // Re-throw security limit errors
395
+ if (err.message && (err.message.indexOf('maximum allowed size') !== -1 ||
396
+ err.message.indexOf('maximum allowed depth') !== -1)) {
397
+ throw err;
398
+ }
399
+ return {};
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Serialize a config value for injection into skill.md comment blocks.
405
+ * Arrays and nested objects become compact JSON; scalars stay as-is.
406
+ *
407
+ * @public
408
+ * @param {*} val - value to serialize
409
+ * @returns {string} serialized string
410
+ */
411
+ function serializeConfigValue(val) {
412
+ if (val === null || val === undefined) return '';
413
+ if (typeof val !== 'object') return String(val);
414
+ if (Array.isArray(val)) {
415
+ return '[' + val.map(function (item) { return serializeConfigValue(item); }).join(', ') + ']';
416
+ }
417
+ var parts = [];
418
+ for (var k in val) {
419
+ if (val.hasOwnProperty(k)) {
420
+ parts.push(k + '=' + serializeConfigValue(val[k]));
421
+ }
422
+ }
423
+ return '{' + parts.join(', ') + '}';
424
+ }
425
+
426
+ // ---------------------------------------------------------------------------
427
+ // parseSimpleYaml — S8/A3 consolidation target
428
+ // ---------------------------------------------------------------------------
429
+
430
+ /**
431
+ * Parse a simple YAML subset into a plain nested JS object (NOT sectioned).
432
+ *
433
+ * This is the shared parser used by ConfigManager, ConfigValidator,
434
+ * hook-skill-gate and provider-role-registry (S8/A3 — previously each had its
435
+ * own divergent copy). Behaviour:
436
+ * - Flat key-value pairs: `key: value`
437
+ * - Nested objects via indentation: `key:\n child: value`
438
+ * - Lists via `- ` items, including TOP-LEVEL scalar arrays (B4 fix):
439
+ * `triggers:\n- foo\n- bar` → `{ triggers: ['foo', 'bar'] }`
440
+ * - List-of-objects: `- key: value`
441
+ * - Inline `# comments` and full-line comments stripped
442
+ * - Quoted strings ("..." / '...'), booleans, null (~), numbers
443
+ *
444
+ * Enforces MAX_YAML_SIZE and MAX_DEPTH to bound resource use (S8 DoS surface
445
+ * that the previous 4 copies lacked).
446
+ *
447
+ * @public
448
+ * @param {string} content - YAML string
449
+ * @returns {object} parsed object (empty on error / oversize)
450
+ */
451
+ function parseSimpleYaml(content) {
452
+ if (typeof content !== 'string') return {};
453
+ if (content.length > MAX_YAML_SIZE) {
454
+ throw new Error('YAML input exceeds maximum allowed size (' + MAX_YAML_SIZE + ' bytes)');
455
+ }
456
+ var result = {};
457
+ // Each frame: { obj, indent }. obj is either an Array or a plain object.
458
+ var stack = [{ obj: result, indent: -1 }];
459
+ var lines = content.split('\n');
460
+ var depth = 0;
461
+
462
+ for (var i = 0; i < lines.length; i++) {
463
+ var line = lines[i];
464
+
465
+ // Skip empty lines, comments, and document separators
466
+ var trimmed = line.trim();
467
+ if (!trimmed || trimmed.indexOf('#') === 0 || trimmed === '---') continue;
468
+
469
+ var indent = line.search(/\S/);
470
+ if (indent < 0) continue;
471
+
472
+ // List item handling — special stack popping: a `- ` item belongs to the
473
+ // nearest array frame that is an ancestor (strictly shallower indent) of
474
+ // this item. Pop frames until we either (a) reach an array frame shallower
475
+ // than this item's indent, or (b) reach the root (orphan item — drop it).
476
+ // Frames at this item's indent or deeper (e.g. a half-step item-object
477
+ // frame from a previous list item) are popped to get back to the array.
478
+ if (trimmed.indexOf('- ') === 0 || trimmed === '-') {
479
+ while (stack.length > 1) {
480
+ var topFrame = stack[stack.length - 1];
481
+ if (Array.isArray(topFrame.obj) && topFrame.indent < indent) {
482
+ // Found the array this item belongs to.
483
+ break;
484
+ }
485
+ // Otherwise pop and keep looking (covers item-object frames, deeper
486
+ // array frames, and same-indent object frames from prior items).
487
+ stack.pop();
488
+ depth--;
489
+ }
490
+ var listParentFrame = stack[stack.length - 1];
491
+ var listParent = listParentFrame.obj;
492
+ // Only append if we actually found an array frame shallower than indent
493
+ if (listParentFrame.indent < indent && Array.isArray(listParent)) {
494
+ var itemContent = trimmed === '-' ? '' : trimmed.substring(2).trim();
495
+ _appendListItem(stack, listParent, itemContent, indent, trimmed);
496
+ }
497
+ // else: orphan `- ` item outside any list — drop
498
+ continue;
499
+ }
500
+
501
+ // Key-value handling: pop stack to the parent whose indent is strictly
502
+ // less than ours.
503
+ while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
504
+ stack.pop();
505
+ depth--;
506
+ }
507
+ var parent = stack[stack.length - 1].obj;
508
+
509
+ var colonIdx = trimmed.indexOf(':');
510
+ if (colonIdx === -1) continue;
511
+
512
+ var key = trimmed.substring(0, colonIdx).trim();
513
+ var valuePart = trimmed.substring(colonIdx + 1).trim();
514
+ // Strip inline comments (only outside quotes)
515
+ valuePart = _stripInlineComment(valuePart);
516
+
517
+ if (valuePart === '' || valuePart === null) {
518
+ // Could be a nested object OR a list — look ahead at the next non-comment line
519
+ var nextReal = _nextNonCommentLine(lines, i + 1);
520
+ var keyForObj = _safeKey(key);
521
+ if (nextReal && nextReal.trimmed.indexOf('- ') === 0 && nextReal.indent > indent) {
522
+ // List (B4: includes top-level scalar arrays like `triggers:\n- foo`)
523
+ if (depth >= MAX_DEPTH) {
524
+ throw new Error('YAML nesting depth exceeds maximum allowed depth (' + MAX_DEPTH + ')');
525
+ }
526
+ var arr = [];
527
+ if (Array.isArray(parent)) {
528
+ // list-of-lists: wrap as a single-element nested array entry
529
+ parent.push(arr);
530
+ } else {
531
+ parent[keyForObj] = arr;
532
+ }
533
+ // Array frame indent = key indent, so items at indent > key indent land here.
534
+ stack.push({ obj: arr, indent: indent });
535
+ depth++;
536
+ } else {
537
+ // Nested object
538
+ if (depth >= MAX_DEPTH) {
539
+ throw new Error('YAML nesting depth exceeds maximum allowed depth (' + MAX_DEPTH + ')');
540
+ }
541
+ var child = {};
542
+ if (Array.isArray(parent)) {
543
+ // list-of-objects: add a fresh object to the list and descend into it
544
+ parent.push(child);
545
+ } else {
546
+ parent[keyForObj] = child;
547
+ }
548
+ stack.push({ obj: child, indent: indent });
549
+ depth++;
550
+ }
551
+ } else {
552
+ var kvKey = _safeKey(key);
553
+ if (Array.isArray(parent)) {
554
+ // Inline object inside a list item: `- key: value` already handled in
555
+ // _appendListItem; reaching here means a bare `- key: value` form on a
556
+ // list frame — push as a single-key object.
557
+ var inline = {};
558
+ inline[kvKey] = parseValue(valuePart);
559
+ parent.push(inline);
560
+ } else {
561
+ parent[kvKey] = parseValue(valuePart);
562
+ }
563
+ }
564
+ }
565
+
566
+ return result;
567
+ }
568
+
569
+ /**
570
+ * Append a `- ` list item to the current parent array. If the parent is not
571
+ * yet an array (defensive — should not happen because we look-ahead before
572
+ * pushing an array frame), no-op.
573
+ *
574
+ * Multi-line object items: `- id: planning` followed by more-indented
575
+ * `name: p1` lines — the deeper lines are merged into the same object via a
576
+ * list-item-object frame pushed onto the stack.
577
+ * @internal
578
+ */
579
+ function _appendListItem(stack, parent, itemContent, indent, trimmed) {
580
+ if (!Array.isArray(parent)) {
581
+ // The list frame should already be on the stack via look-ahead. If we
582
+ // somehow land here, drop the item rather than corrupting the parent.
583
+ return;
584
+ }
585
+ if (itemContent === '') {
586
+ // `- ` with nothing after → null placeholder
587
+ parent.push(null);
588
+ return;
589
+ }
590
+ // Object item: `- key: value` or `- key:` (start of multi-line object item)
591
+ var colonIdx = itemContent.indexOf(':');
592
+ if (colonIdx !== -1 && /^\S/.test(itemContent)) {
593
+ var candidateKey = itemContent.substring(0, colonIdx).trim();
594
+ // Only treat as object-item if the part before the colon looks like a bare
595
+ // key (no spaces inside). Avoids misclassifying `http://...` style scalars.
596
+ if (candidateKey && candidateKey.indexOf(' ') === -1) {
597
+ var itemVal = _stripInlineComment(itemContent.substring(colonIdx + 1).trim());
598
+ var obj = {};
599
+ parent.push(obj);
600
+ if (itemVal === '') {
601
+ // `- key:` → start of a nested block under this list item; descend into
602
+ // the object so subsequent deeper lines populate it.
603
+ obj[_safeKey(candidateKey)] = {};
604
+ // Push a frame for the inline value object at the item's indent so that
605
+ // deeper child lines attach to it, then a frame for the item object
606
+ // itself at the same indent.
607
+ stack.push({ obj: obj[_safeKey(candidateKey)], indent: indent });
608
+ stack.push({ obj: obj, indent: indent - 0.5 });
609
+ } else {
610
+ obj[_safeKey(candidateKey)] = parseValue(itemVal);
611
+ // Push a frame for the item object at a half-step deeper indent so
612
+ // subsequent deeper lines (e.g. `name: p1`) merge into THIS object
613
+ // rather than being treated as new list items.
614
+ stack.push({ obj: obj, indent: indent - 0.5 });
615
+ }
616
+ return;
617
+ }
618
+ }
619
+ // Plain scalar item (including quoted strings, URLs, etc.)
620
+ parent.push(parseValue(_stripInlineComment(itemContent)));
621
+ }
622
+
623
+ /**
624
+ * Strip an inline ` # comment` from a value, respecting quoted strings.
625
+ * @internal
626
+ * @param {string} val
627
+ * @returns {string}
628
+ */
629
+ function _stripInlineComment(val) {
630
+ if (!val) return val;
631
+ var inSingle = false, inDouble = false;
632
+ for (var i = 0; i < val.length; i++) {
633
+ var ch = val.charAt(i);
634
+ if (ch === '"' && !inSingle) inDouble = !inDouble;
635
+ else if (ch === "'" && !inDouble) inSingle = !inSingle;
636
+ else if (ch === '#' && !inSingle && !inDouble) {
637
+ // Must be preceded by whitespace or start-of-string to count as a comment
638
+ if (i === 0 || val.charAt(i - 1) === ' ' || val.charAt(i - 1) === '\t') {
639
+ return val.substring(0, i).trim();
640
+ }
641
+ }
642
+ }
643
+ return val.trim();
644
+ }
645
+
646
+ /**
647
+ * Find the next non-empty, non-comment line. Returns null at EOF.
648
+ * @internal
649
+ * @param {string[]} lines
650
+ * @param {number} startIdx
651
+ * @returns {{trimmed: string, indent: number}|null}
652
+ */
653
+ function _nextNonCommentLine(lines, startIdx) {
654
+ for (var i = startIdx; i < lines.length; i++) {
655
+ var l = lines[i];
656
+ var t = l.trim();
657
+ if (!t || t.indexOf('#') === 0 || t === '---') continue;
658
+ return { trimmed: t, indent: l.search(/\S/) };
659
+ }
660
+ return null;
661
+ }
662
+
663
+ /**
664
+ * Reject prototype-pollution keys (S7-style guard for parsed YAML).
665
+ * @internal
666
+ * @param {string} k
667
+ * @returns {string}
668
+ */
669
+ function _safeKey(k) {
670
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') {
671
+ return '_';
672
+ }
673
+ return k;
674
+ }
675
+
676
+ module.exports = {
677
+ parseYamlFile: parseYamlFile,
678
+ parseYamlString: parseYamlString,
679
+ parseSimpleYaml: parseSimpleYaml,
680
+ parseValue: parseValue,
681
+ serializeConfigValue: serializeConfigValue,
682
+ // Internal helpers exported for testing
683
+ parseNestedBlock: parseNestedBlock,
684
+ parseChildLines: parseChildLines,
685
+ parseListItems: parseListItems,
686
+ collectChildren: collectChildren,
687
+ parseLineAsObject: parseLineAsObject,
688
+ parseObjectItems: parseObjectItems,
689
+ // Constants exposed for tests / callers that want to surface limits
690
+ MAX_YAML_SIZE: MAX_YAML_SIZE,
691
+ MAX_DEPTH: MAX_DEPTH,
692
+ };