monomind 1.11.14 → 1.12.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 (172) hide show
  1. package/.claude/agents/generated/channel-intelligence-director.md +87 -0
  2. package/.claude/agents/generated/chief-growth-officer.md +88 -0
  3. package/.claude/agents/generated/content-seo-strategist.md +90 -0
  4. package/.claude/agents/generated/developer-community-strategist.md +91 -0
  5. package/.claude/agents/generated/outreach-partnership-strategist.md +90 -0
  6. package/.claude/agents/generated/social-media-strategist.md +91 -0
  7. package/.claude/agents/generated/video-visual-strategist.md +90 -0
  8. package/.claude/commands/mastermind/master.md +1 -1
  9. package/.claude/helpers/auto-memory-hook.mjs +13 -4
  10. package/.claude/helpers/control-start.cjs +5 -0
  11. package/.claude/helpers/event-logger.cjs +114 -0
  12. package/.claude/helpers/handlers/adr-draft-handler.cjs +19 -5
  13. package/.claude/helpers/handlers/agent-start-handler.cjs +13 -4
  14. package/.claude/helpers/handlers/compact-handler.cjs +2 -0
  15. package/.claude/helpers/handlers/edit-handler.cjs +1 -1
  16. package/.claude/helpers/handlers/gates-handler.cjs +3 -0
  17. package/.claude/helpers/handlers/graph-status-handler.cjs +14 -8
  18. package/.claude/helpers/handlers/loops-status-handler.cjs +5 -2
  19. package/.claude/helpers/handlers/route-handler.cjs +13 -6
  20. package/.claude/helpers/handlers/session-handler.cjs +11 -4
  21. package/.claude/helpers/handlers/session-restore-handler.cjs +21 -11
  22. package/.claude/helpers/handlers/task-handler.cjs +13 -5
  23. package/.claude/helpers/intelligence.cjs +7 -2
  24. package/.claude/helpers/loop-tracker.cjs +15 -3
  25. package/.claude/helpers/memory.cjs +6 -1
  26. package/.claude/helpers/router.cjs +5 -2
  27. package/.claude/helpers/session.cjs +2 -0
  28. package/.claude/helpers/statusline.cjs +10 -2
  29. package/.claude/helpers/utils/micro-agents.cjs +20 -4
  30. package/.claude/scheduled_tasks.lock +1 -1
  31. package/.claude/settings.json +92 -1
  32. package/.claude/skills/mastermind/_protocol.md +25 -15
  33. package/.claude/skills/mastermind/architect.md +3 -3
  34. package/.claude/skills/mastermind/autodev.md +4 -2
  35. package/.claude/skills/mastermind/idea.md +10 -0
  36. package/.claude/skills/mastermind/ops.md +3 -3
  37. package/.claude/skills/mastermind/runorg.md +153 -86
  38. package/package.json +20 -3
  39. package/packages/@monomind/cli/dist/src/agents/registry-builder.js +2 -0
  40. package/packages/@monomind/cli/dist/src/autopilot-state.js +10 -5
  41. package/packages/@monomind/cli/dist/src/benchmarks/benchmark-runner.js +13 -0
  42. package/packages/@monomind/cli/dist/src/benchmarks/metric-evaluators.js +20 -9
  43. package/packages/@monomind/cli/dist/src/browser/actions.js +10 -3
  44. package/packages/@monomind/cli/dist/src/browser/browser.js +12 -2
  45. package/packages/@monomind/cli/dist/src/browser/cdp.js +21 -3
  46. package/packages/@monomind/cli/dist/src/browser/har.js +27 -5
  47. package/packages/@monomind/cli/dist/src/commands/agent.js +11 -8
  48. package/packages/@monomind/cli/dist/src/commands/analyze.js +36 -21
  49. package/packages/@monomind/cli/dist/src/commands/autopilot.js +12 -4
  50. package/packages/@monomind/cli/dist/src/commands/benchmark.js +51 -8
  51. package/packages/@monomind/cli/dist/src/commands/browse.js +5 -2
  52. package/packages/@monomind/cli/dist/src/commands/claims.js +29 -11
  53. package/packages/@monomind/cli/dist/src/commands/cleanup.js +25 -5
  54. package/packages/@monomind/cli/dist/src/commands/config.js +15 -7
  55. package/packages/@monomind/cli/dist/src/commands/daemon.js +6 -0
  56. package/packages/@monomind/cli/dist/src/commands/deployment.js +34 -19
  57. package/packages/@monomind/cli/dist/src/commands/doctor.js +97 -20
  58. package/packages/@monomind/cli/dist/src/commands/guidance.js +15 -2
  59. package/packages/@monomind/cli/dist/src/commands/hive-mind.js +37 -14
  60. package/packages/@monomind/cli/dist/src/commands/hooks.js +42 -25
  61. package/packages/@monomind/cli/dist/src/commands/init.js +9 -4
  62. package/packages/@monomind/cli/dist/src/commands/issues.js +29 -26
  63. package/packages/@monomind/cli/dist/src/commands/mcp.js +11 -5
  64. package/packages/@monomind/cli/dist/src/commands/memory.js +10 -0
  65. package/packages/@monomind/cli/dist/src/commands/migrate.js +5 -5
  66. package/packages/@monomind/cli/dist/src/commands/monograph.js +18 -5
  67. package/packages/@monomind/cli/dist/src/commands/monovector/backup.js +8 -2
  68. package/packages/@monomind/cli/dist/src/commands/monovector/benchmark.js +20 -7
  69. package/packages/@monomind/cli/dist/src/commands/monovector/import.js +15 -0
  70. package/packages/@monomind/cli/dist/src/commands/monovector/migrate.js +4 -1
  71. package/packages/@monomind/cli/dist/src/commands/monovector/optimize.js +11 -0
  72. package/packages/@monomind/cli/dist/src/commands/monovector/setup.js +11 -1
  73. package/packages/@monomind/cli/dist/src/commands/neural.js +1 -1
  74. package/packages/@monomind/cli/dist/src/commands/performance.js +20 -7
  75. package/packages/@monomind/cli/dist/src/commands/platforms.js +90 -8
  76. package/packages/@monomind/cli/dist/src/commands/plugins.js +12 -5
  77. package/packages/@monomind/cli/dist/src/commands/process.js +33 -10
  78. package/packages/@monomind/cli/dist/src/commands/progress.js +5 -3
  79. package/packages/@monomind/cli/dist/src/commands/providers.js +5 -5
  80. package/packages/@monomind/cli/dist/src/commands/replay.js +8 -2
  81. package/packages/@monomind/cli/dist/src/commands/route.js +27 -7
  82. package/packages/@monomind/cli/dist/src/commands/security.js +4 -0
  83. package/packages/@monomind/cli/dist/src/commands/session.js +12 -1
  84. package/packages/@monomind/cli/dist/src/commands/start.js +11 -4
  85. package/packages/@monomind/cli/dist/src/commands/status.js +7 -4
  86. package/packages/@monomind/cli/dist/src/commands/swarm.js +27 -13
  87. package/packages/@monomind/cli/dist/src/commands/task.js +26 -11
  88. package/packages/@monomind/cli/dist/src/commands/tokens.js +7 -2
  89. package/packages/@monomind/cli/dist/src/commands/transfer-store.js +36 -22
  90. package/packages/@monomind/cli/dist/src/commands/update.js +15 -3
  91. package/packages/@monomind/cli/dist/src/commands/workflow.js +39 -6
  92. package/packages/@monomind/cli/dist/src/consensus/audit-writer.js +18 -7
  93. package/packages/@monomind/cli/dist/src/consensus/vote-signer.js +25 -8
  94. package/packages/@monomind/cli/dist/src/index.js +7 -3
  95. package/packages/@monomind/cli/dist/src/init/executor.js +14 -11
  96. package/packages/@monomind/cli/dist/src/init/shared-instructions-generator.js +20 -4
  97. package/packages/@monomind/cli/dist/src/init/statusline-generator.js +36 -15
  98. package/packages/@monomind/cli/dist/src/mcp-tools/a2a-tools.js +98 -13
  99. package/packages/@monomind/cli/dist/src/mcp-tools/agent-tools.js +16 -3
  100. package/packages/@monomind/cli/dist/src/mcp-tools/analyze-tools.js +80 -17
  101. package/packages/@monomind/cli/dist/src/mcp-tools/browser-tools.js +84 -22
  102. package/packages/@monomind/cli/dist/src/mcp-tools/claims-tools.js +35 -7
  103. package/packages/@monomind/cli/dist/src/mcp-tools/config-tools.js +82 -17
  104. package/packages/@monomind/cli/dist/src/mcp-tools/coordination-tools.js +37 -4
  105. package/packages/@monomind/cli/dist/src/mcp-tools/daa-tools.js +49 -7
  106. package/packages/@monomind/cli/dist/src/mcp-tools/embeddings-tools.js +45 -18
  107. package/packages/@monomind/cli/dist/src/mcp-tools/github-tools.js +75 -25
  108. package/packages/@monomind/cli/dist/src/mcp-tools/guidance-tools.js +32 -10
  109. package/packages/@monomind/cli/dist/src/mcp-tools/hive-mind-tools.js +91 -20
  110. package/packages/@monomind/cli/dist/src/mcp-tools/hooks-tools.js +188 -29
  111. package/packages/@monomind/cli/dist/src/mcp-tools/memory-tools.js +25 -7
  112. package/packages/@monomind/cli/dist/src/mcp-tools/monograph-compat.js +11 -2
  113. package/packages/@monomind/cli/dist/src/mcp-tools/monograph-tools.js +148 -26
  114. package/packages/@monomind/cli/dist/src/mcp-tools/neural-tools.js +44 -9
  115. package/packages/@monomind/cli/dist/src/mcp-tools/performance-tools.js +45 -10
  116. package/packages/@monomind/cli/dist/src/mcp-tools/progress-tools.js +7 -4
  117. package/packages/@monomind/cli/dist/src/mcp-tools/request-tracker.js +15 -1
  118. package/packages/@monomind/cli/dist/src/mcp-tools/security-tools.js +61 -9
  119. package/packages/@monomind/cli/dist/src/mcp-tools/session-tools.js +45 -14
  120. package/packages/@monomind/cli/dist/src/mcp-tools/swarm-tools.js +15 -3
  121. package/packages/@monomind/cli/dist/src/mcp-tools/system-tools.js +14 -7
  122. package/packages/@monomind/cli/dist/src/mcp-tools/task-tools.js +52 -10
  123. package/packages/@monomind/cli/dist/src/mcp-tools/terminal-tools.js +40 -6
  124. package/packages/@monomind/cli/dist/src/mcp-tools/transfer-tools.js +37 -4
  125. package/packages/@monomind/cli/dist/src/mcp-tools/workflow-tools.js +29 -6
  126. package/packages/@monomind/cli/dist/src/memory/ewc-consolidation.js +26 -10
  127. package/packages/@monomind/cli/dist/src/memory/intelligence.js +80 -19
  128. package/packages/@monomind/cli/dist/src/memory/memory-bridge.js +21 -2
  129. package/packages/@monomind/cli/dist/src/memory/memory-initializer.js +67 -3
  130. package/packages/@monomind/cli/dist/src/memory/sona-optimizer.js +14 -4
  131. package/packages/@monomind/cli/dist/src/monovector/command-outcomes.js +43 -7
  132. package/packages/@monomind/cli/dist/src/monovector/coverage-router.js +8 -4
  133. package/packages/@monomind/cli/dist/src/monovector/coverage-tools.js +6 -3
  134. package/packages/@monomind/cli/dist/src/monovector/diff-classifier.js +13 -0
  135. package/packages/@monomind/cli/dist/src/monovector/route-outcomes.d.ts +2 -1
  136. package/packages/@monomind/cli/dist/src/monovector/route-outcomes.js +46 -4
  137. package/packages/@monomind/cli/dist/src/plugins/manager.js +8 -3
  138. package/packages/@monomind/cli/dist/src/plugins/store/discovery.js +46 -2
  139. package/packages/@monomind/cli/dist/src/plugins/store/search.js +5 -4
  140. package/packages/@monomind/cli/dist/src/production/circuit-breaker.js +17 -3
  141. package/packages/@monomind/cli/dist/src/production/error-handler.js +3 -0
  142. package/packages/@monomind/cli/dist/src/production/monitoring.js +20 -3
  143. package/packages/@monomind/cli/dist/src/production/rate-limiter.js +13 -4
  144. package/packages/@monomind/cli/dist/src/production/retry.js +17 -9
  145. package/packages/@monomind/cli/dist/src/routing/embed-worker.js +6 -2
  146. package/packages/@monomind/cli/dist/src/routing/embedder.js +0 -0
  147. package/packages/@monomind/cli/dist/src/routing/llm-caller.js +13 -2
  148. package/packages/@monomind/cli/dist/src/routing/route-layer-factory.js +18 -3
  149. package/packages/@monomind/cli/dist/src/services/claim-service.d.ts +1 -0
  150. package/packages/@monomind/cli/dist/src/services/claim-service.js +8 -0
  151. package/packages/@monomind/cli/dist/src/services/config-file-manager.js +14 -2
  152. package/packages/@monomind/cli/dist/src/services/headless-worker-executor.js +18 -2
  153. package/packages/@monomind/cli/dist/src/services/worker-daemon.js +53 -12
  154. package/packages/@monomind/cli/dist/src/transfer/anonymization/index.d.ts +0 -3
  155. package/packages/@monomind/cli/dist/src/transfer/anonymization/index.js +16 -1
  156. package/packages/@monomind/cli/dist/src/transfer/export.js +8 -0
  157. package/packages/@monomind/cli/dist/src/transfer/ipfs/upload.js +33 -3
  158. package/packages/@monomind/cli/dist/src/transfer/serialization/cfp.js +9 -3
  159. package/packages/@monomind/cli/dist/src/transfer/storage/gcs.js +37 -3
  160. package/packages/@monomind/cli/dist/src/transfer/store/discovery.js +45 -3
  161. package/packages/@monomind/cli/dist/src/transfer/store/download.js +5 -0
  162. package/packages/@monomind/cli/dist/src/transfer/store/publish.js +13 -1
  163. package/packages/@monomind/cli/dist/src/transfer/store/registry.d.ts +8 -0
  164. package/packages/@monomind/cli/dist/src/transfer/store/registry.js +30 -5
  165. package/packages/@monomind/cli/dist/src/transfer/store/search.js +20 -5
  166. package/packages/@monomind/cli/dist/src/update/checker.js +59 -7
  167. package/packages/@monomind/cli/dist/src/update/executor.js +50 -3
  168. package/packages/@monomind/cli/dist/src/update/index.js +18 -1
  169. package/packages/@monomind/cli/dist/src/update/rate-limiter.d.ts +6 -0
  170. package/packages/@monomind/cli/dist/src/update/rate-limiter.js +79 -7
  171. package/packages/@monomind/cli/dist/src/update/validator.js +52 -1
  172. package/packages/@monomind/cli/package.json +2 -3
@@ -10,7 +10,14 @@ import { select, confirm, input } from '../prompt.js';
10
10
  import { callMCPTool, MCPClientError } from '../mcp-client.js';
11
11
  import { spawn as childSpawn, execSync } from 'child_process';
12
12
  import { mkdir, writeFile } from 'fs/promises';
13
- import { join } from 'path';
13
+ import { join, resolve as resolvePath, sep } from 'path';
14
+ // Input length caps
15
+ const MAX_OBJECTIVE_LEN = 2_000;
16
+ const MAX_TASK_DESC_LEN = 4_000;
17
+ const MAX_MESSAGE_LEN = 2_000;
18
+ const MAX_KEY_LEN = 256;
19
+ const MAX_VALUE_LEN = 65_536;
20
+ const MAX_AGENT_ID_LEN = 128;
14
21
  // Hive topologies
15
22
  const TOPOLOGIES = [
16
23
  { value: 'hierarchical', label: 'Hierarchical', hint: 'Queen-led with worker agents' },
@@ -177,11 +184,21 @@ async function spawnClaudeCodeInstance(swarmId, swarmName, objective, workers, f
177
184
  `Consensus: ${output.highlight(flags.consensus || 'byzantine')}`,
178
185
  `MCP Tools: ${output.success('Full Monomind integration enabled')}`
179
186
  ]);
180
- // Ensure sessions directory exists
181
- const sessionsDir = join('.hive-mind', 'sessions');
187
+ // Ensure sessions directory exists (anchor to process.cwd() so relative paths
188
+ // don't escape when the caller changes directory)
189
+ const baseDir = resolvePath(process.cwd());
190
+ const sessionsDir = resolvePath(baseDir, '.hive-mind', 'sessions');
191
+ // Guard: sessions directory must stay inside cwd
192
+ if (!sessionsDir.startsWith(baseDir + sep) && sessionsDir !== baseDir) {
193
+ throw new Error('Sessions directory path traversal detected');
194
+ }
182
195
  await mkdir(sessionsDir, { recursive: true });
183
196
  const safeSwarmId = swarmId.replace(/[^a-zA-Z0-9_-]/g, '_');
184
197
  const promptFile = join(sessionsDir, `hive-mind-prompt-${safeSwarmId}.txt`);
198
+ // Guard: prompt file must stay inside sessions directory
199
+ if (!resolvePath(promptFile).startsWith(sessionsDir + sep)) {
200
+ throw new Error('Prompt file path traversal detected');
201
+ }
185
202
  await writeFile(promptFile, hiveMindPrompt, 'utf8');
186
203
  output.writeln();
187
204
  output.printSuccess(`Hive Mind prompt saved to: ${promptFile}`);
@@ -295,10 +312,14 @@ async function spawnClaudeCodeInstance(swarmId, swarmName, objective, workers, f
295
312
  spinner.fail('Failed to prepare Claude Code coordination');
296
313
  const errorMessage = error instanceof Error ? error.message : String(error);
297
314
  output.printError(`Error: ${errorMessage}`);
298
- // Try to save prompt as fallback
315
+ // Try to save prompt as fallback — write inside cwd to avoid path issues
299
316
  try {
300
317
  const safeSwarmIdFallback = swarmId.replace(/[^a-zA-Z0-9_-]/g, '_');
301
- const promptFile = `hive-mind-prompt-${safeSwarmIdFallback}-fallback.txt`;
318
+ const fallbackDir = resolvePath(process.cwd());
319
+ const promptFile = join(fallbackDir, `hive-mind-prompt-${safeSwarmIdFallback}-fallback.txt`);
320
+ if (!resolvePath(promptFile).startsWith(fallbackDir + sep)) {
321
+ throw new Error('Fallback path traversal');
322
+ }
302
323
  const workerGroups = groupWorkersByType(workers);
303
324
  const hiveMindPrompt = generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags);
304
325
  await writeFile(promptFile, hiveMindPrompt, 'utf8');
@@ -502,12 +523,13 @@ const spawnCommand = {
502
523
  ],
503
524
  action: async (ctx) => {
504
525
  // Parse count with fallback to default
505
- const count = ctx.flags.count || 1;
526
+ const rawCount = ctx.flags.count || 1;
527
+ const count = Number.isFinite(rawCount) ? Math.max(1, Math.min(rawCount, 50)) : 1;
506
528
  const role = ctx.flags.role || 'worker';
507
529
  const agentType = ctx.flags.type || 'worker';
508
530
  const prefix = ctx.flags.prefix || 'hive-worker';
509
531
  const launchClaude = ctx.flags.claude;
510
- let objective = ctx.flags.objective || ctx.args.join(' ');
532
+ let objective = (ctx.flags.objective || ctx.args.join(' ')).slice(0, MAX_OBJECTIVE_LEN);
511
533
  output.printInfo(`Spawning ${count} ${role} agent(s)...`);
512
534
  try {
513
535
  const result = await callMCPTool('hive-mind_spawn', {
@@ -761,12 +783,13 @@ const taskCommand = {
761
783
  { command: 'monomind hive-mind task -d "Security review" -p critical -c', description: 'Critical task with consensus' }
762
784
  ],
763
785
  action: async (ctx) => {
764
- let description = ctx.flags.description || ctx.args.join(' ');
786
+ let description = (ctx.flags.description || ctx.args.join(' ')).slice(0, MAX_TASK_DESC_LEN);
765
787
  if (!description && ctx.interactive) {
766
788
  description = await input({
767
789
  message: 'Task description:',
768
790
  validate: (v) => v.length > 0 || 'Description is required'
769
791
  });
792
+ description = description.slice(0, MAX_TASK_DESC_LEN);
770
793
  }
771
794
  if (!description) {
772
795
  output.printError('Task description is required');
@@ -888,7 +911,7 @@ const joinCommand = {
888
911
  { name: 'role', short: 'r', description: 'Agent role (worker, specialist, scout)', type: 'string', default: 'worker' }
889
912
  ],
890
913
  action: async (ctx) => {
891
- const agentId = ctx.args[0] || ctx.flags['agent-id'] || ctx.flags.agentId;
914
+ const agentId = (ctx.args[0] || ctx.flags['agent-id'] || ctx.flags.agentId || '').slice(0, MAX_AGENT_ID_LEN);
892
915
  if (!agentId) {
893
916
  output.printError('Agent ID is required. Use --agent-id or -a flag, or provide as argument.');
894
917
  return { success: false, exitCode: 1 };
@@ -914,7 +937,7 @@ const leaveCommand = {
914
937
  description: 'Remove an agent from the hive mind',
915
938
  options: [{ name: 'agent-id', short: 'a', description: 'Agent ID to remove', type: 'string' }],
916
939
  action: async (ctx) => {
917
- const agentId = ctx.args[0] || ctx.flags['agent-id'] || ctx.flags.agentId;
940
+ const agentId = (ctx.args[0] || ctx.flags['agent-id'] || ctx.flags.agentId || '').slice(0, MAX_AGENT_ID_LEN);
918
941
  if (!agentId) {
919
942
  output.printError('Agent ID required.');
920
943
  return { success: false, exitCode: 1 };
@@ -986,13 +1009,13 @@ const broadcastCommand = {
986
1009
  { name: 'from', short: 'f', description: 'Sender agent ID', type: 'string' }
987
1010
  ],
988
1011
  action: async (ctx) => {
989
- const message = ctx.args.join(' ') || ctx.flags.message;
1012
+ const message = (ctx.args.join(' ') || ctx.flags.message || '').slice(0, MAX_MESSAGE_LEN);
990
1013
  if (!message) {
991
1014
  output.printError('Message required. Use --message or -m flag.');
992
1015
  return { success: false, exitCode: 1 };
993
1016
  }
994
1017
  try {
995
- const result = await callMCPTool('hive-mind_broadcast', { message, priority: ctx.flags.priority, fromId: ctx.flags.from });
1018
+ const result = await callMCPTool('hive-mind_broadcast', { message, priority: ctx.flags.priority, fromId: typeof ctx.flags.from === 'string' ? ctx.flags.from.slice(0, MAX_AGENT_ID_LEN) : undefined });
996
1019
  if (!result.success) {
997
1020
  output.printError(result.error || 'Failed');
998
1021
  return { success: false, exitCode: 1 };
@@ -1017,8 +1040,8 @@ const memorySubCommand = {
1017
1040
  ],
1018
1041
  action: async (ctx) => {
1019
1042
  const action = ctx.flags.action || 'list';
1020
- const key = ctx.flags.key;
1021
- const value = ctx.flags.value;
1043
+ const key = typeof ctx.flags.key === 'string' ? ctx.flags.key.slice(0, MAX_KEY_LEN) : undefined;
1044
+ const value = typeof ctx.flags.value === 'string' ? ctx.flags.value.slice(0, MAX_VALUE_LEN) : undefined;
1022
1045
  if ((action === 'get' || action === 'delete') && !key) {
1023
1046
  output.printError('Key required for get/delete.');
1024
1047
  return { success: false, exitCode: 1 };
@@ -27,8 +27,10 @@ function readCoverageFromDisk() {
27
27
  const summaryPath = join(cwd, relPath);
28
28
  if (existsSync(summaryPath)) {
29
29
  try {
30
- const raw = JSON.parse(readFileSync(summaryPath, 'utf-8'));
31
- return parseCoverageSummaryJson(raw, relPath);
30
+ if (statSync(summaryPath).size <= 4_194_304) {
31
+ const raw = JSON.parse(readFileSync(summaryPath, 'utf-8'));
32
+ return parseCoverageSummaryJson(raw, relPath);
33
+ }
32
34
  }
33
35
  catch {
34
36
  // malformed, try next
@@ -40,8 +42,10 @@ function readCoverageFromDisk() {
40
42
  const lcovPath = join(cwd, relPath);
41
43
  if (existsSync(lcovPath)) {
42
44
  try {
43
- const raw = readFileSync(lcovPath, 'utf-8');
44
- return parseLcovInfo(raw, relPath);
45
+ if (statSync(lcovPath).size <= 8_388_608) {
46
+ const raw = readFileSync(lcovPath, 'utf-8');
47
+ return parseLcovInfo(raw, relPath);
48
+ }
45
49
  }
46
50
  catch {
47
51
  // malformed, try next
@@ -52,8 +56,10 @@ function readCoverageFromDisk() {
52
56
  const nycPath = join(cwd, '.nyc_output', 'out.json');
53
57
  if (existsSync(nycPath)) {
54
58
  try {
55
- const raw = JSON.parse(readFileSync(nycPath, 'utf-8'));
56
- return parseCoverageSummaryJson(raw, '.nyc_output/out.json');
59
+ if (statSync(nycPath).size <= 4_194_304) {
60
+ const raw = JSON.parse(readFileSync(nycPath, 'utf-8'));
61
+ return parseCoverageSummaryJson(raw, '.nyc_output/out.json');
62
+ }
57
63
  }
58
64
  catch {
59
65
  // malformed
@@ -1785,9 +1791,11 @@ const intelligenceCommand = {
1785
1791
  try {
1786
1792
  const pStat = statSync(persistence.patternsFile);
1787
1793
  patternsFileSize = pStat.size;
1788
- const pData = JSON.parse(readFileSync(persistence.patternsFile, 'utf-8'));
1789
- if (Array.isArray(pData))
1790
- patternsFileEntries = pData.length;
1794
+ if (patternsFileSize <= 4_194_304) {
1795
+ const pData = JSON.parse(readFileSync(persistence.patternsFile, 'utf-8'));
1796
+ if (Array.isArray(pData))
1797
+ patternsFileEntries = pData.length;
1798
+ }
1791
1799
  }
1792
1800
  catch { /* ignore */ }
1793
1801
  }
@@ -1796,9 +1804,12 @@ const intelligenceCommand = {
1796
1804
  let lastAdaptationFromDisk = null;
1797
1805
  if (persistence.statsExist) {
1798
1806
  try {
1799
- const sData = JSON.parse(readFileSync(persistence.statsFile, 'utf-8'));
1800
- trajectoriesFromDisk = sData?.trajectoriesRecorded ?? 0;
1801
- lastAdaptationFromDisk = sData?.lastAdaptation ?? null;
1807
+ const sStat = statSync(persistence.statsFile);
1808
+ if (sStat.size <= 524_288) {
1809
+ const sData = JSON.parse(readFileSync(persistence.statsFile, 'utf-8'));
1810
+ trajectoriesFromDisk = sData?.trajectoriesRecorded ?? 0;
1811
+ lastAdaptationFromDisk = sData?.lastAdaptation ?? null;
1812
+ }
1802
1813
  }
1803
1814
  catch { /* ignore */ }
1804
1815
  }
@@ -3375,10 +3386,12 @@ const statuslineCommand = {
3375
3386
  for (const lPath of learningJsonPaths) {
3376
3387
  if (fs.existsSync(lPath)) {
3377
3388
  try {
3378
- const data = JSON.parse(fs.readFileSync(lPath, 'utf-8'));
3379
- if (data.intelligence?.score !== undefined) {
3380
- intelligencePct = Math.min(100, Math.floor(data.intelligence.score));
3381
- break;
3389
+ if (fs.statSync(lPath).size <= 524_288) {
3390
+ const data = JSON.parse(fs.readFileSync(lPath, 'utf-8'));
3391
+ if (data.intelligence?.score !== undefined) {
3392
+ intelligencePct = Math.min(100, Math.floor(data.intelligence.score));
3393
+ break;
3394
+ }
3382
3395
  }
3383
3396
  }
3384
3397
  catch { /* ignore */ }
@@ -3500,9 +3513,11 @@ const statuslineCommand = {
3500
3513
  const settingsPath = path.join(process.cwd(), '.claude', 'settings.json');
3501
3514
  if (fs.existsSync(settingsPath)) {
3502
3515
  try {
3503
- const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
3504
- if (settings.hooks) {
3505
- hooksStats.enabled = Object.values(settings.hooks).filter((h) => h && typeof h === 'object').length;
3516
+ if (fs.statSync(settingsPath).size <= 524_288) {
3517
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
3518
+ if (settings.hooks) {
3519
+ hooksStats.enabled = Object.values(settings.hooks).filter((h) => h && typeof h === 'object').length;
3520
+ }
3506
3521
  }
3507
3522
  }
3508
3523
  catch { /* ignore */ }
@@ -3585,12 +3600,14 @@ const statuslineCommand = {
3585
3600
  const vectorsPath = path.join(process.cwd(), '.monomind', 'vectors.json');
3586
3601
  if (fs.existsSync(vectorsPath) && agentdbStats.vectorCount === 0) {
3587
3602
  try {
3588
- const data = JSON.parse(fs.readFileSync(vectorsPath, 'utf-8'));
3589
- if (Array.isArray(data)) {
3590
- agentdbStats.vectorCount = data.length;
3591
- }
3592
- else if (data.vectors) {
3593
- agentdbStats.vectorCount = Object.keys(data.vectors).length;
3603
+ if (fs.statSync(vectorsPath).size <= 8_388_608) {
3604
+ const data = JSON.parse(fs.readFileSync(vectorsPath, 'utf-8'));
3605
+ if (Array.isArray(data)) {
3606
+ agentdbStats.vectorCount = data.length;
3607
+ }
3608
+ else if (data.vectors) {
3609
+ agentdbStats.vectorCount = Object.keys(data.vectors).length;
3610
+ }
3594
3611
  }
3595
3612
  }
3596
3613
  catch { /* ignore */ }
@@ -99,7 +99,7 @@ const initAction = async (ctx) => {
99
99
  const { spawn } = await import('child_process');
100
100
  const pidFile = path.join(ctx.cwd, '.monomind', 'monograph-watch.pid');
101
101
  let alreadyRunning = false;
102
- if (fs.existsSync(pidFile)) {
102
+ if (fs.existsSync(pidFile) && fs.statSync(pidFile).size <= 32) {
103
103
  const existingPid = parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
104
104
  if (!isNaN(existingPid)) {
105
105
  try {
@@ -738,9 +738,14 @@ const upgradeCommand = {
738
738
  // Try to read control URL for dashboard progress events (best-effort)
739
739
  let controlUrl = 'http://localhost:4242';
740
740
  try {
741
- const ctrlCfg = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.monomind', 'control.json'), 'utf-8'));
742
- if (ctrlCfg.url)
743
- controlUrl = ctrlCfg.url;
741
+ const ctrlPath = path.join(process.cwd(), '.monomind', 'control.json');
742
+ if (fs.existsSync(ctrlPath) && fs.statSync(ctrlPath).size <= 4096) {
743
+ const ctrlCfg = JSON.parse(fs.readFileSync(ctrlPath, 'utf-8'));
744
+ // Only allow localhost/127.0.0.1 URLs to prevent SSRF via attacker-controlled control.json
745
+ if (typeof ctrlCfg.url === 'string' && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(ctrlCfg.url)) {
746
+ controlUrl = ctrlCfg.url;
747
+ }
748
+ }
744
749
  }
745
750
  catch { }
746
751
  const emitUpgradeProgress = async (projDir, status, current, total) => {
@@ -106,9 +106,9 @@ const claimCommand = {
106
106
  },
107
107
  ],
108
108
  action: async (ctx) => {
109
- const issueId = (ctx.flags.issue || ctx.args[0]);
110
- const agentStr = ctx.flags.agent;
111
- const userStr = ctx.flags.user;
109
+ const issueId = (ctx.flags.issue || ctx.args[0])?.slice(0, 256);
110
+ const agentStr = ctx.flags.agent?.slice(0, 256);
111
+ const userStr = ctx.flags.user?.slice(0, 256);
112
112
  if (!issueId) {
113
113
  output.printError('Issue ID is required');
114
114
  return { success: false, exitCode: 1 };
@@ -120,13 +120,13 @@ const claimCommand = {
120
120
  const claimant = agentStr
121
121
  ? {
122
122
  type: 'agent',
123
- agentType: agentStr.split(':')[0],
124
- agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
123
+ agentType: agentStr.split(':')[0].slice(0, 64),
124
+ agentId: (agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`).slice(0, 128),
125
125
  }
126
126
  : {
127
127
  type: 'human',
128
- userId: userStr.split(':')[0],
129
- name: userStr.split(':')[1] || userStr.split(':')[0],
128
+ userId: userStr.split(':')[0].slice(0, 128),
129
+ name: (userStr.split(':')[1] || userStr.split(':')[0]).slice(0, 128),
130
130
  };
131
131
  const service = getClaimService(ctx.cwd);
132
132
  await service.initialize();
@@ -165,9 +165,9 @@ const releaseCommand = {
165
165
  },
166
166
  ],
167
167
  action: async (ctx) => {
168
- const issueId = (ctx.flags.issue || ctx.args[0]);
169
- const agentStr = ctx.flags.agent;
170
- const userStr = ctx.flags.user;
168
+ const issueId = (ctx.flags.issue || ctx.args[0])?.slice(0, 256);
169
+ const agentStr = ctx.flags.agent?.slice(0, 256);
170
+ const userStr = ctx.flags.user?.slice(0, 256);
171
171
  if (!issueId) {
172
172
  output.printError('Issue ID is required');
173
173
  return { success: false, exitCode: 1 };
@@ -179,13 +179,13 @@ const releaseCommand = {
179
179
  const claimant = agentStr
180
180
  ? {
181
181
  type: 'agent',
182
- agentType: agentStr.split(':')[0],
183
- agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
182
+ agentType: agentStr.split(':')[0].slice(0, 64),
183
+ agentId: (agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`).slice(0, 128),
184
184
  }
185
185
  : {
186
186
  type: 'human',
187
- userId: userStr.split(':')[0],
188
- name: userStr.split(':')[1] || userStr.split(':')[0],
187
+ userId: userStr.split(':')[0].slice(0, 128),
188
+ name: (userStr.split(':')[1] || userStr.split(':')[0]).slice(0, 128),
189
189
  };
190
190
  const service = getClaimService(ctx.cwd);
191
191
  await service.initialize();
@@ -210,10 +210,10 @@ const handoffCommand = {
210
210
  { name: 'reason', short: 'r', type: 'string', description: 'Handoff reason', default: 'Handoff requested' },
211
211
  ],
212
212
  action: async (ctx) => {
213
- const issueId = (ctx.flags.issue || ctx.args[0]);
214
- const toStr = ctx.flags.to;
215
- const fromStr = ctx.flags.from;
216
- const reason = ctx.flags.reason;
213
+ const issueId = (ctx.flags.issue || ctx.args[0])?.slice(0, 256);
214
+ const toStr = ctx.flags.to?.slice(0, 256);
215
+ const fromStr = ctx.flags.from?.slice(0, 256);
216
+ const reason = (ctx.flags.reason || 'Handoff requested').slice(0, 512);
217
217
  if (!issueId || !toStr) {
218
218
  output.printError('Issue ID and --to are required');
219
219
  return { success: false, exitCode: 1 };
@@ -257,7 +257,7 @@ const statusCommand = {
257
257
  { name: 'note', short: 'n', type: 'string', description: 'Status note' },
258
258
  ],
259
259
  action: async (ctx) => {
260
- const issueId = (ctx.flags.issue || ctx.args[0]);
260
+ const issueId = (ctx.flags.issue || ctx.args[0])?.slice(0, 256);
261
261
  if (!issueId) {
262
262
  output.printError('Issue ID is required');
263
263
  return { success: false, exitCode: 1 };
@@ -265,8 +265,11 @@ const statusCommand = {
265
265
  const service = getClaimService(ctx.cwd);
266
266
  await service.initialize();
267
267
  const newStatus = ctx.flags.set;
268
- const progress = ctx.flags.progress;
269
- const note = ctx.flags.note;
268
+ const rawProgress = ctx.flags.progress;
269
+ const progress = rawProgress !== undefined
270
+ ? Math.max(0, Math.min(100, Math.floor(rawProgress)))
271
+ : undefined;
272
+ const note = ctx.flags.note?.slice(0, 512);
270
273
  try {
271
274
  if (newStatus) {
272
275
  await service.updateStatus(issueId, newStatus, note);
@@ -301,7 +304,7 @@ const stealableCommand = {
301
304
  { name: 'type', short: 't', type: 'string', description: 'Filter by agent type' },
302
305
  ],
303
306
  action: async (ctx) => {
304
- const agentType = ctx.flags.type;
307
+ const agentType = ctx.flags.type?.slice(0, 64);
305
308
  const service = getClaimService(ctx.cwd);
306
309
  await service.initialize();
307
310
  const stealable = await service.getStealable(agentType);
@@ -331,16 +334,16 @@ const stealCommand = {
331
334
  { name: 'agent', short: 'a', type: 'string', description: 'Steal as agent', required: true },
332
335
  ],
333
336
  action: async (ctx) => {
334
- const issueId = (ctx.flags.issue || ctx.args[0]);
335
- const agentStr = ctx.flags.agent;
337
+ const issueId = (ctx.flags.issue || ctx.args[0])?.slice(0, 256);
338
+ const agentStr = (ctx.flags.agent || '').slice(0, 256);
336
339
  if (!issueId) {
337
340
  output.printError('Issue ID is required');
338
341
  return { success: false, exitCode: 1 };
339
342
  }
340
343
  const stealer = {
341
344
  type: 'agent',
342
- agentType: agentStr.split(':')[0],
343
- agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
345
+ agentType: agentStr.split(':')[0].slice(0, 64),
346
+ agentId: (agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`).slice(0, 128),
344
347
  };
345
348
  const service = getClaimService(ctx.cwd);
346
349
  await service.initialize();
@@ -88,10 +88,15 @@ const startCommand = {
88
88
  { command: 'monomind mcp start -f', description: 'Force restart (kill existing)' }
89
89
  ],
90
90
  action: async (ctx) => {
91
- const port = ctx.flags.port ?? 3000;
92
- const host = ctx.flags.host ?? 'localhost';
91
+ const rawPort = ctx.flags.port ?? 3000;
92
+ const port = Number.isFinite(rawPort) && rawPort >= 1 && rawPort <= 65535 ? Math.floor(rawPort) : 3000;
93
+ const rawHost = ctx.flags.host ?? 'localhost';
94
+ // Cap host length and reject control chars to prevent injection
95
+ const host = typeof rawHost === 'string' ? rawHost.slice(0, 253).replace(/[\x00-\x1f]/g, '') : 'localhost';
93
96
  const transport = ctx.flags.transport ?? 'stdio';
94
- const tools = ctx.flags.tools || 'all';
97
+ const rawTools = ctx.flags.tools || 'all';
98
+ // Cap tools string to prevent DoS via oversized comma-separated lists
99
+ const tools = typeof rawTools === 'string' ? rawTools.slice(0, 2000) : 'all';
95
100
  const daemon = ctx.flags.daemon ?? false;
96
101
  const force = ctx.flags.force ?? false;
97
102
  output.writeln();
@@ -599,14 +604,15 @@ const logsCommand = {
599
604
  action: async (ctx) => {
600
605
  const lines = ctx.flags.lines || 50;
601
606
  // Try to find and read the actual log file
602
- const { existsSync, readFileSync } = await import('fs');
607
+ const { existsSync, readFileSync, statSync } = await import('fs');
603
608
  const { join } = await import('path');
609
+ const MAX_MCP_LOG_BYTES = 10 * 1024 * 1024; // 10 MB
604
610
  const logPaths = [
605
611
  join(ctx.cwd, '.monomind', 'logs', 'mcp-server.log'),
606
612
  join(ctx.cwd, '.monomind', 'logs', 'daemon.log'),
607
613
  join(ctx.cwd, '.monomind', 'mcp.log'),
608
614
  ];
609
- const logFile = logPaths.find(p => existsSync(p));
615
+ const logFile = logPaths.find(p => existsSync(p) && statSync(p).size <= MAX_MCP_LOG_BYTES);
610
616
  output.writeln();
611
617
  output.writeln(output.bold('MCP Server Logs'));
612
618
  output.writeln(output.dim('─'.repeat(50)));
@@ -511,6 +511,11 @@ const editCommand = {
511
511
  output.printError(`File not found: ${filePath}`);
512
512
  return { success: false, exitCode: 1 };
513
513
  }
514
+ const MAX_MEMORY_FILE_BYTES = 50 * 1024 * 1024; // 50 MB
515
+ if (fs.statSync(filePath).size > MAX_MEMORY_FILE_BYTES) {
516
+ output.printError(`Memory file too large (> 50 MB): ${filePath}`);
517
+ return { success: false, exitCode: 1 };
518
+ }
514
519
  let entries;
515
520
  try {
516
521
  const raw = fs.readFileSync(filePath, 'utf8');
@@ -763,6 +768,11 @@ const deleteCommand = {
763
768
  output.printError(`File not found: ${filePath}`);
764
769
  return { success: false, exitCode: 1 };
765
770
  }
771
+ const MAX_MEMORY_FILE_BYTES = 50 * 1024 * 1024; // 50 MB
772
+ if (fs.statSync(filePath).size > MAX_MEMORY_FILE_BYTES) {
773
+ output.printError(`Memory file too large (> 50 MB): ${filePath}`);
774
+ return { success: false, exitCode: 1 };
775
+ }
766
776
  let entries;
767
777
  try {
768
778
  const raw = fs.readFileSync(filePath, 'utf8');
@@ -47,7 +47,7 @@ const statusCommand = {
47
47
  let hasV2Config = false;
48
48
  let hasv1Config = false;
49
49
  try {
50
- if (fs.existsSync(v2ConfigPath)) {
50
+ if (fs.existsSync(v2ConfigPath) && fs.statSync(v2ConfigPath).size <= MAX_MIGRATE_FILE_BYTES) {
51
51
  const raw = fs.readFileSync(v2ConfigPath, 'utf-8');
52
52
  const parsed = JSON.parse(raw);
53
53
  if (parsed.version === '2' || parsed.version === 2 || !parsed.version) {
@@ -110,7 +110,7 @@ const statusCommand = {
110
110
  const migrationStatePath = path.join(cwd, '.monomind', 'migration-state.json');
111
111
  let migrationState = null;
112
112
  try {
113
- if (fs.existsSync(migrationStatePath)) {
113
+ if (fs.existsSync(migrationStatePath) && fs.statSync(migrationStatePath).size <= MAX_MIGRATE_FILE_BYTES) {
114
114
  const raw = fs.readFileSync(migrationStatePath, 'utf-8');
115
115
  const parsed = JSON.parse(raw);
116
116
  migrationState = parsed.status || 'unknown';
@@ -214,7 +214,7 @@ const runCommand = {
214
214
  if (!target || target === 'config') {
215
215
  const v2ConfigPath = path.join(cwd, 'monomind.config.json');
216
216
  try {
217
- if (fs.existsSync(v2ConfigPath)) {
217
+ if (fs.existsSync(v2ConfigPath) && fs.statSync(v2ConfigPath).size <= MAX_MIGRATE_FILE_BYTES) {
218
218
  const raw = fs.readFileSync(v2ConfigPath, 'utf-8');
219
219
  const parsed = JSON.parse(raw);
220
220
  if (parsed.version === '2' || parsed.version === 2 || !parsed.version) {
@@ -415,7 +415,7 @@ const verifyCommand = {
415
415
  // Check 1: Migration state file exists
416
416
  let migrationState = null;
417
417
  try {
418
- if (fs.existsSync(migrationStatePath)) {
418
+ if (fs.existsSync(migrationStatePath) && fs.statSync(migrationStatePath).size <= MAX_MIGRATE_FILE_BYTES) {
419
419
  const raw = fs.readFileSync(migrationStatePath, 'utf-8');
420
420
  migrationState = JSON.parse(raw);
421
421
  checks.push({ check: 'Migration state file', result: 'passed' });
@@ -432,7 +432,7 @@ const verifyCommand = {
432
432
  // Check 2: v1 config exists and is valid JSON
433
433
  const v1ConfigPath = path.join(v1Dir, 'config.json');
434
434
  try {
435
- if (fs.existsSync(v1ConfigPath)) {
435
+ if (fs.existsSync(v1ConfigPath) && fs.statSync(v1ConfigPath).size <= MAX_MIGRATE_FILE_BYTES) {
436
436
  const raw = fs.readFileSync(v1ConfigPath, 'utf-8');
437
437
  JSON.parse(raw); // validate JSON
438
438
  checks.push({ check: 'v1 config (valid JSON)', result: 'passed' });
@@ -255,16 +255,27 @@ const searchCommand = {
255
255
  { command: 'monomind monograph search -q "pipeline" --mode semantic', description: 'Semantic (embedding) search' },
256
256
  ],
257
257
  action: async (ctx) => {
258
- const query = ctx.flags.query;
259
- const limit = parseInt(ctx.flags.limit || '15', 10);
260
- const label = ctx.flags.label;
261
- const mode = ctx.flags.mode ?? 'hybrid';
258
+ const rawQuery = ctx.flags.query;
259
+ const rawLimit = parseInt(ctx.flags.limit || '15', 10);
260
+ const rawLabel = ctx.flags.label;
261
+ const rawMode = ctx.flags.mode ?? 'hybrid';
262
262
  const root = resolve(ctx.flags.path ?? process.cwd());
263
263
  const dbPath = getDbPath(root);
264
+ // Cap query to prevent SQLite FTS DoS from multi-MB query strings
265
+ const MAX_QUERY_LEN = 2048;
266
+ const query = typeof rawQuery === 'string' ? rawQuery.slice(0, MAX_QUERY_LEN) : '';
264
267
  if (!query) {
265
268
  output.printError('--query is required');
266
269
  return { success: false, exitCode: 1 };
267
270
  }
271
+ // Clamp limit to prevent huge result sets from causing OOM
272
+ const limit = isFinite(rawLimit) && rawLimit > 0 ? Math.min(rawLimit, 500) : 15;
273
+ // Validate mode to an explicit allowlist
274
+ const VALID_MODES = new Set(['bm25', 'semantic', 'hybrid']);
275
+ const mode = VALID_MODES.has(rawMode) ? rawMode : 'hybrid';
276
+ // Cap label to prevent oversized SQL filter values
277
+ const MAX_LABEL_LEN = 64;
278
+ const label = typeof rawLabel === 'string' ? rawLabel.slice(0, MAX_LABEL_LEN) : undefined;
268
279
  if (!existsSync(dbPath)) {
269
280
  output.printWarning('No knowledge graph found. Run: monomind monograph build');
270
281
  return { success: false, exitCode: 1 };
@@ -345,7 +356,9 @@ const statsCommand = {
345
356
  ],
346
357
  action: async (ctx) => {
347
358
  const root = resolve(ctx.flags.path ?? process.cwd());
348
- const top = parseInt(ctx.flags.top || '10', 10);
359
+ const rawTop = parseInt(ctx.flags.top || '10', 10);
360
+ // Clamp top-N to prevent arbitrarily large SQL LIMIT values
361
+ const top = isFinite(rawTop) && rawTop > 0 ? Math.min(rawTop, 200) : 10;
349
362
  const dbPath = getDbPath(root);
350
363
  if (!existsSync(dbPath)) {
351
364
  output.printWarning('No knowledge graph found. Run: monomind monograph build');
@@ -461,7 +461,14 @@ const restoreSubcommand = {
461
461
  output.printError(`File not found: ${inputPath}`);
462
462
  return { success: false, exitCode: 1 };
463
463
  }
464
- // Read file
464
+ // Read file — check size first to avoid OOM on a runaway or corrupt file.
465
+ const fileSize = fs.statSync(inputPath).size;
466
+ const MAX_BACKUP_BYTES = 500 * 1024 * 1024; // 500 MB
467
+ if (fileSize > MAX_BACKUP_BYTES) {
468
+ spinner.fail('Backup file too large');
469
+ output.printError(`Backup file exceeds size limit (${formatBytes(fileSize)} > ${formatBytes(MAX_BACKUP_BYTES)})`);
470
+ return { success: false, exitCode: 1 };
471
+ }
465
472
  let content;
466
473
  if (inputPath.endsWith('.gz')) {
467
474
  const zlib = await import('zlib');
@@ -473,7 +480,6 @@ const restoreSubcommand = {
473
480
  else {
474
481
  content = fs.readFileSync(inputPath, 'utf-8');
475
482
  }
476
- const fileSize = fs.statSync(inputPath).size;
477
483
  spinner.succeed(`Read backup file (${formatBytes(fileSize)})`);
478
484
  // Determine format
479
485
  const isJson = content.trim().startsWith('{');
@@ -151,13 +151,26 @@ export const benchmarkCommand = {
151
151
  ],
152
152
  action: async (ctx) => {
153
153
  const config = getConnectionConfig(ctx);
154
- const numVectors = parseInt(ctx.flags.vectors || '10000', 10);
155
- const dimensions = parseInt(ctx.flags.dimensions || '1536', 10);
156
- const numQueries = parseInt(ctx.flags.queries || '100', 10);
157
- const topK = parseInt(ctx.flags.k || '10', 10);
158
- const metric = ctx.flags.metric || 'cosine';
159
- const indexType = ctx.flags.index || 'hnsw';
160
- const batchSize = parseInt(ctx.flags['batch-size'] || '1000', 10);
154
+ // Clamp numeric inputs to safe ranges to prevent DoS via OOM
155
+ const numVectors = Math.min(Math.max(1, parseInt(ctx.flags.vectors || '10000', 10)), 1_000_000);
156
+ const dimensions = Math.min(Math.max(1, parseInt(ctx.flags.dimensions || '1536', 10)), 65536);
157
+ const numQueries = Math.min(Math.max(1, parseInt(ctx.flags.queries || '100', 10)), 10_000);
158
+ const topK = Math.min(Math.max(1, parseInt(ctx.flags.k || '10', 10)), 10_000);
159
+ // Validate metric and indexType against allowlists to prevent SQL injection
160
+ const VALID_METRICS = ['cosine', 'l2', 'inner'];
161
+ const VALID_INDEX_TYPES = ['hnsw', 'ivfflat', 'none'];
162
+ const rawMetric = ctx.flags.metric || 'cosine';
163
+ const rawIndexType = ctx.flags.index || 'hnsw';
164
+ const metric = VALID_METRICS.includes(rawMetric) ? rawMetric : 'cosine';
165
+ const indexType = VALID_INDEX_TYPES.includes(rawIndexType) ? rawIndexType : 'hnsw';
166
+ const batchSize = Math.min(Math.max(1, parseInt(ctx.flags['batch-size'] || '1000', 10)), 100_000);
167
+ // Validate schema identifier against safe pattern to prevent SQL injection
168
+ const rawSchema = config.schema || 'monomind';
169
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(rawSchema)) {
170
+ output.printError('Invalid schema name. Only alphanumeric characters and underscores are allowed.');
171
+ return { success: false, exitCode: 1 };
172
+ }
173
+ config.schema = rawSchema;
161
174
  const cleanup = ctx.flags.cleanup !== false;
162
175
  output.writeln();
163
176
  output.writeln(output.bold('MonoVector Performance Benchmark'));