{"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/learn-chunks.js", "inference_info": {"prefix_code": "const { generateText } = require(\"ai\");\nconst { google } = require('./llm')\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n\nconst prompts = {\n system:\n \"You are a JS and opensource-software specialist, going to explain some uglified JS code.\",\n user: (\n code\n ) => `Here are some uglified codes. Read and answer the following questions\n\n1. Is it part of several open source projects code you know? If it is likely, tell me the name of the open source project.\n2. The purpose of the code snippet.\n\nResponse JSON Format:\n{\n \"ossProjects\": [\"$name_1\", \"$name_2\"],\n \"purpose\": \"$description\"\n}\n\n\\`\\`\\`\n${code}\n\\`\\`\\``,\n};\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\n(", "suffix_code": ")();\n\nfunction parseMessageToJson(input) {\n // Regular expression to match JSON code blocks\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n\n // Find all matches for JSON code blocks\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n\n let jsonString;\n\n if (matches.length === 1) {\n // Extract JSON content from the code block, trimming whitespace\n jsonString = matches[0][1].trim();\n } else {\n // No JSON code block found, use the entire input\n jsonString = input.trim();\n }\n\n try {\n // Parse the JSON string into an object\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}\n\nmodule.exports = {\n google,\n parseMessageToJson,\n prompts\n}", "middle_code": "async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/ask.js", "const { generateText } = require(\"ai\");\nconst { prompts } = require(\"./learn-chunks\");\nconst { google } = require(\"./llm\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst marked = require(\"marked\");\nconst { markedTerminal } = require(\"marked-terminal\");\nconst readline = require(\"readline\");\n\nmarked.use(markedTerminal());\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\n(async () => {\n // Prompt the user for a question\n const QUESTION = await new Promise((resolve) => {\n rl.question(\"Enter your question about the code: \", (answer) => {\n resolve(answer);\n });\n });\n\n console.log(`Analyzing question: \"${QUESTION}\"\\n`);\n\n let insight = \"\";\n let final = \"\";\n\n for (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (!chunk.startsWith(\"improved-\")) {\n continue;\n }\n\n console.log(\"Processing\", chunk);\n\n prompts.user = (\n code\n ) => `I am analyzing a Node.JS CLI AI program called claude-code, which implements an AI coder by interacting with LLM, using tool calling, ModelContextProtocol and other functions.\n\nThe question I want to focus on now is:\n\n\n${QUESTION}\n\n\nThe following is its source code fragment, which has been obfuscated by uglify. Please tell me the code logic that is directly or indirectly related to the problem I want to study.\nOnly answer me what you read from the code I provided.\n\nThe code logic I am more concerned about includes:\n\n1. Its prompt design\n2. Its LLM calling method\n3. Other related logic\n\n\n${insight}\n\n \n\n${code}\n\n\\`\\`\\``;\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(\n fs.readFileSync(path.resolve(mergedChunksDir, chunk), \"utf-8\")\n ),\n },\n ],\n maxRetries: 5,\n });\n\n insight += `\\n \n${text}\n \\n`;\n final = text;\n }\n\n console.log(`=== Answer ===\\n`);\n console.log(marked.parse(final));\n\n rl.close();\n})();\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\nconst mergedIndex = {};\n\nfunction manualFixNaming(project) {\n // fix LLM naming issue\n let lowerCaseProject = project.toLowerCase();\n\n return (\n {\n \"sentry-javascript\": \"sentry\",\n \"react devtools\": \"react\",\n \"aws-sdk-js-v3\": \"aws-sdk\",\n \"@aws-sdk/signature-v4\": \"aws-sdk\",\n \"@smithy/smithy-client\": \"aws-sdk\",\n \"aws sdk for javascript\": \"aws-sdk\",\n \"statsig-js\": \"statsig\",\n // 58\n \"claude-code\": \"claude-code-1\",\n // 59\n \"langchain.js\": 'claude-code-2',\n // 60\n zod: 'claude-code-3',\n // 61\n \"claude code\": \"claude-code-4\",\n // 62\n \"continue code\": \"claude-code-5\",\n tengu: \"claude-code-5\",\n // 64\n \"@anthropic-ai/claude-code\": \"claude-code-6\",\n }[lowerCaseProject] || lowerCaseProject\n );\n}\n\nfor (const chunk of fs.readdirSync(chunksDir)) {\n const chunkPath = path.resolve(chunksDir, chunk);\n if (!chunkPath.endsWith(\".json\")) {\n continue;\n }\n\n const { ossProjects = [] } = JSON.parse(\n fs.readFileSync(chunkPath, \"utf-8\")\n );\n\n for (const prpject of ossProjects) {\n const projectName = manualFixNaming(prpject);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n }\n}\n\nfor (const project in mergedIndex) {\n let content = \"\";\n for (const chunkPath of new Set(mergedIndex[project])) {\n content += fs.readFileSync(\n path.resolve(chunksDir, chunkPath.replace(\".json\", \".mjs\")),\n \"utf-8\"\n );\n }\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}\n\nfs.writeFileSync(\n path.resolve(mergedChunksDir, \"chunks.index.json\"),\n JSON.stringify(Object.keys(mergedIndex).reduce((prev, cur) => {\n for (const chunk of mergedIndex[cur]) {\n prev[chunk] = cur;\n }\n return prev;\n }, {}), null, 2)\n);\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/split.js", "const acorn = require(\"acorn\");\nconst walk = require(\"acorn-walk\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst CHUNK_THRESHOLD = 100_000;\nconst currentChunk = {\n pathCount: 1,\n content: \"\",\n};\n\nconst source = fs.readFileSync(\n path.resolve(__dirname, \"../cli.beautify.mjs\"),\n \"utf-8\"\n);\n\nconst ast = acorn.parse(source, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n});\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\nconst chunksEntry = path.resolve(chunksDir, \"cli.chunks.mjs\");\nfs.writeFileSync(chunksEntry, \"\");\n\n// help Mac users\nconst namedSet = new Set();\nfunction namer(value) {\n let count = 0;\n let newValue = `${value.toLowerCase()}_${count}`;\n while (namedSet.has(newValue)) {\n count++;\n newValue = `${value.toLowerCase()}_${count}`;\n }\n namedSet.add(newValue);\n return newValue;\n}\n\nconst chunksIndex = {};\n\nwalk.fullAncestor(ast, (node, _state, ancestors) => {\n if (node.type === \"Program\") {\n return;\n }\n\n const lastAncestor = ancestors[ancestors.length - 2]; // exclude current\n if (lastAncestor.type !== \"Program\") {\n // only split top level\n return;\n }\n\n let splited = false;\n switch (node.type) {\n case \"FunctionDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n case \"ExportNamedDeclaration\": {\n let exportName = node.specifiers.find((s) => s.type === \"ExportSpecifier\")\n .exported.name;\n splited = writeWithCheck(getContent(node), exportName);\n return;\n }\n case \"VariableDeclaration\":\n if (node.declarations.some((decl) => decl.id.type !== \"Identifier\")) {\n return;\n }\n node.declarations.forEach((decl) => {\n declSplited = writeWithCheck(getContent(decl), decl.id.name);\n });\n return;\n case \"ClassDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n default:\n }\n\n if (!splited) {\n appendToEntry(node);\n }\n});\n\n// flush last chunk\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`),\n currentChunk.content\n);\n\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.index.json`),\n JSON.stringify(chunksIndex, null, 2)\n);\n\nfunction getContent(node) {\n return `\\n// @from(${getPositionInfo(node)})\\n${source.slice(\n node.start,\n node.end\n )}`;\n}\n\nfunction writeWithCheck(content, name) {\n const chunkPath = path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`);\n if (currentChunk.content.length + content.length > CHUNK_THRESHOLD) {\n // flush\n fs.writeFileSync(chunkPath, currentChunk.content);\n currentChunk.content = \"\";\n currentChunk.pathCount++;\n }\n\n // keep small chunks inline\n // if (content.length < 2000) {\n // return false;\n // }\n\n if (chunksIndex[name]) {\n throw new Error(\"name conflict\", { name });\n }\n chunksIndex[name] = path.relative(chunksDir, chunkPath);\n\n currentChunk.content += content;\n return true;\n}\n\nfunction appendToEntry(node) {\n fs.appendFileSync(\n chunksEntry,\n `\\n// @from(${getPositionInfo(node)})\\n` + getContent(node) + \"\\n\"\n );\n}\n\nfunction getPositionInfo(node) {\n return node.loc\n ? `Ln ${node.loc.start.line}, Col ${node.loc.start.column}`\n : `Start ${node.start}, End ${node.end}`;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/improve-merged-chunks.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst acorn = require(\"acorn-loose\");\nconst walk = require(\"acorn-walk\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\nconst chunksIndex = JSON.parse(\n fs.readFileSync(path.resolve(chunksDir, \"chunks.index.json\"), \"utf-8\")\n);\nconst mergedIndex = JSON.parse(\n fs.readFileSync(path.resolve(mergedChunksDir, \"chunks.index.json\"), \"utf-8\")\n);\n\nfor (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (chunk.startsWith(\"claude-code-\")) {\n const content = fs.readFileSync(\n path.resolve(mergedChunksDir, chunk),\n \"utf-8\"\n );\n\n let depsSummary =\n \"/* Some variables in the code import from the following projects\\n\";\n const deps = {};\n for (const v of roughFindUndefinedVariables(content)) {\n if (chunksIndex[v]) {\n const project = mergedIndex[chunksIndex[v].replace(\".mjs\", \".json\")];\n if (project.startsWith(\"claude-code\")) {\n continue;\n }\n deps[project] = deps[project] || [];\n deps[project].push(v);\n }\n }\n for (const project in deps) {\n depsSummary += `* ${deps[project].join(\n \", \"\n )} import from OSS \"${project}\"\\n`;\n }\n depsSummary += \"*/\";\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `improved-${chunk}`),\n `${depsSummary}\\n${content}`\n );\n }\n}\n\nfunction roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n\n const defined = new Set();\n const used = new Set();\n\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/llm.js", "const { createGoogleGenerativeAI } = require(\"@ai-sdk/google\");\nconst { fetch, ProxyAgent } = require(\"undici\");\n\nconst dispatcher = process.env.http_proxy ? new ProxyAgent(process.env.http_proxy) : undefined;\n\nconst google = createGoogleGenerativeAI({\n fetch: async (req, options) => {\n return fetch(req, {\n ...options,\n ...(dispatcher && { dispatcher }),\n });\n },\n});\n\nmodule.exports = {\n google,\n};\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/beautify.js", "const beautify = require('js-beautify/js').js\nconst fs = require('fs')\nconst path = require('path')\n\nconst original = fs.readFileSync(path.resolve(__dirname, '../cli.mjs'), 'utf-8')\n\nfs.writeFileSync(path.resolve(__dirname, '../cli.beautify.mjs'), beautify(original, {\n indent_size: 2,\n space_in_empty_paren: true,\n}))"]], "task_instance_info": {"created_time": "2025-08-20 23:52:40", "created_task_model": "DeepSeek-R1", "function_skeleton": "async () => {}", "code_description": "This code segment functions to: Automatically process code files by generating descriptive metadata through an external language model and persist the structured results for subsequent analysis."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nasync () => {\n const chunkFiles = await fs.promises.readdir(chunksDir);\n const results = [];\n\n for (const file of chunkFiles) {\n const code = await fs.promises.readFile(path.join(chunksDir, file), \"utf-8\");\n const { text } = await generateText({\n model: google,\n system: prompts.system,\n prompt: prompts.user(code),\n });\n \n results.push(parseMessageToJson(text));\n }\n\n const merged = results.reduce((acc, cur) => ({\n ossProjects: [...new Set([...acc.ossProjects, ...cur.ossProjects])].sort(),\n purpose: [...acc.purpose.split('\\n'), cur.purpose].filter(Boolean).join('\\n')\n }), { ossProjects: [], purpose: '' });\n\n console.log('Analysis Results:', merged);\n return merged;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-53-03"}, "editdistance_info": {"edit_distance": 10.9453, "calculate_time": "2025-08-20 23:53:03", "true_code_clean": "async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n}", "predict_code_clean": "async () => {\n const chunkFiles = await fs.promises.readdir(chunksDir);\n const results = [];\n for (const file of chunkFiles) {\n const code = await fs.promises.readFile(path.join(chunksDir, file), \"utf-8\");\n const { text } = await generateText({\n model: google,\n system: prompts.system,\n prompt: prompts.user(code),\n });\n results.push(parseMessageToJson(text));\n }\n const merged = results.reduce((acc, cur) => ({\n ossProjects: [...new Set([...acc.ossProjects, ...cur.ossProjects])].sort(),\n purpose: [...acc.purpose.split('\\n'), cur.purpose].filter(Boolean).join('\\n')\n }), { ossProjects: [], purpose: '' });\n console.log('Analysis Results:', merged);\n return merged;\n}"}} {"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/learn-chunks.js", "inference_info": {"prefix_code": "const { generateText } = require(\"ai\");\nconst { google } = require('./llm')\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n\nconst prompts = {\n system:\n \"You are a JS and opensource-software specialist, going to explain some uglified JS code.\",\n user: (\n code\n ) => `Here are some uglified codes. Read and answer the following questions\n\n1. Is it part of several open source projects code you know? If it is likely, tell me the name of the open source project.\n2. The purpose of the code snippet.\n\nResponse JSON Format:\n{\n \"ossProjects\": [\"$name_1\", \"$name_2\"],\n \"purpose\": \"$description\"\n}\n\n\\`\\`\\`\n${code}\n\\`\\`\\``,\n};\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\n(async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n})();\n\n", "suffix_code": "\n\nmodule.exports = {\n google,\n parseMessageToJson,\n prompts\n}", "middle_code": "function parseMessageToJson(input) {\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n let jsonString;\n if (matches.length === 1) {\n jsonString = matches[0][1].trim();\n } else {\n jsonString = input.trim();\n }\n try {\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/ask.js", "const { generateText } = require(\"ai\");\nconst { prompts } = require(\"./learn-chunks\");\nconst { google } = require(\"./llm\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst marked = require(\"marked\");\nconst { markedTerminal } = require(\"marked-terminal\");\nconst readline = require(\"readline\");\n\nmarked.use(markedTerminal());\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\n(async () => {\n // Prompt the user for a question\n const QUESTION = await new Promise((resolve) => {\n rl.question(\"Enter your question about the code: \", (answer) => {\n resolve(answer);\n });\n });\n\n console.log(`Analyzing question: \"${QUESTION}\"\\n`);\n\n let insight = \"\";\n let final = \"\";\n\n for (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (!chunk.startsWith(\"improved-\")) {\n continue;\n }\n\n console.log(\"Processing\", chunk);\n\n prompts.user = (\n code\n ) => `I am analyzing a Node.JS CLI AI program called claude-code, which implements an AI coder by interacting with LLM, using tool calling, ModelContextProtocol and other functions.\n\nThe question I want to focus on now is:\n\n\n${QUESTION}\n\n\nThe following is its source code fragment, which has been obfuscated by uglify. Please tell me the code logic that is directly or indirectly related to the problem I want to study.\nOnly answer me what you read from the code I provided.\n\nThe code logic I am more concerned about includes:\n\n1. Its prompt design\n2. Its LLM calling method\n3. Other related logic\n\n\n${insight}\n\n \n\n${code}\n\n\\`\\`\\``;\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(\n fs.readFileSync(path.resolve(mergedChunksDir, chunk), \"utf-8\")\n ),\n },\n ],\n maxRetries: 5,\n });\n\n insight += `\\n \n${text}\n \\n`;\n final = text;\n }\n\n console.log(`=== Answer ===\\n`);\n console.log(marked.parse(final));\n\n rl.close();\n})();\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\nconst mergedIndex = {};\n\nfunction manualFixNaming(project) {\n // fix LLM naming issue\n let lowerCaseProject = project.toLowerCase();\n\n return (\n {\n \"sentry-javascript\": \"sentry\",\n \"react devtools\": \"react\",\n \"aws-sdk-js-v3\": \"aws-sdk\",\n \"@aws-sdk/signature-v4\": \"aws-sdk\",\n \"@smithy/smithy-client\": \"aws-sdk\",\n \"aws sdk for javascript\": \"aws-sdk\",\n \"statsig-js\": \"statsig\",\n // 58\n \"claude-code\": \"claude-code-1\",\n // 59\n \"langchain.js\": 'claude-code-2',\n // 60\n zod: 'claude-code-3',\n // 61\n \"claude code\": \"claude-code-4\",\n // 62\n \"continue code\": \"claude-code-5\",\n tengu: \"claude-code-5\",\n // 64\n \"@anthropic-ai/claude-code\": \"claude-code-6\",\n }[lowerCaseProject] || lowerCaseProject\n );\n}\n\nfor (const chunk of fs.readdirSync(chunksDir)) {\n const chunkPath = path.resolve(chunksDir, chunk);\n if (!chunkPath.endsWith(\".json\")) {\n continue;\n }\n\n const { ossProjects = [] } = JSON.parse(\n fs.readFileSync(chunkPath, \"utf-8\")\n );\n\n for (const prpject of ossProjects) {\n const projectName = manualFixNaming(prpject);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n }\n}\n\nfor (const project in mergedIndex) {\n let content = \"\";\n for (const chunkPath of new Set(mergedIndex[project])) {\n content += fs.readFileSync(\n path.resolve(chunksDir, chunkPath.replace(\".json\", \".mjs\")),\n \"utf-8\"\n );\n }\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}\n\nfs.writeFileSync(\n path.resolve(mergedChunksDir, \"chunks.index.json\"),\n JSON.stringify(Object.keys(mergedIndex).reduce((prev, cur) => {\n for (const chunk of mergedIndex[cur]) {\n prev[chunk] = cur;\n }\n return prev;\n }, {}), null, 2)\n);\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/split.js", "const acorn = require(\"acorn\");\nconst walk = require(\"acorn-walk\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst CHUNK_THRESHOLD = 100_000;\nconst currentChunk = {\n pathCount: 1,\n content: \"\",\n};\n\nconst source = fs.readFileSync(\n path.resolve(__dirname, \"../cli.beautify.mjs\"),\n \"utf-8\"\n);\n\nconst ast = acorn.parse(source, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n});\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\nconst chunksEntry = path.resolve(chunksDir, \"cli.chunks.mjs\");\nfs.writeFileSync(chunksEntry, \"\");\n\n// help Mac users\nconst namedSet = new Set();\nfunction namer(value) {\n let count = 0;\n let newValue = `${value.toLowerCase()}_${count}`;\n while (namedSet.has(newValue)) {\n count++;\n newValue = `${value.toLowerCase()}_${count}`;\n }\n namedSet.add(newValue);\n return newValue;\n}\n\nconst chunksIndex = {};\n\nwalk.fullAncestor(ast, (node, _state, ancestors) => {\n if (node.type === \"Program\") {\n return;\n }\n\n const lastAncestor = ancestors[ancestors.length - 2]; // exclude current\n if (lastAncestor.type !== \"Program\") {\n // only split top level\n return;\n }\n\n let splited = false;\n switch (node.type) {\n case \"FunctionDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n case \"ExportNamedDeclaration\": {\n let exportName = node.specifiers.find((s) => s.type === \"ExportSpecifier\")\n .exported.name;\n splited = writeWithCheck(getContent(node), exportName);\n return;\n }\n case \"VariableDeclaration\":\n if (node.declarations.some((decl) => decl.id.type !== \"Identifier\")) {\n return;\n }\n node.declarations.forEach((decl) => {\n declSplited = writeWithCheck(getContent(decl), decl.id.name);\n });\n return;\n case \"ClassDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n default:\n }\n\n if (!splited) {\n appendToEntry(node);\n }\n});\n\n// flush last chunk\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`),\n currentChunk.content\n);\n\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.index.json`),\n JSON.stringify(chunksIndex, null, 2)\n);\n\nfunction getContent(node) {\n return `\\n// @from(${getPositionInfo(node)})\\n${source.slice(\n node.start,\n node.end\n )}`;\n}\n\nfunction writeWithCheck(content, name) {\n const chunkPath = path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`);\n if (currentChunk.content.length + content.length > CHUNK_THRESHOLD) {\n // flush\n fs.writeFileSync(chunkPath, currentChunk.content);\n currentChunk.content = \"\";\n currentChunk.pathCount++;\n }\n\n // keep small chunks inline\n // if (content.length < 2000) {\n // return false;\n // }\n\n if (chunksIndex[name]) {\n throw new Error(\"name conflict\", { name });\n }\n chunksIndex[name] = path.relative(chunksDir, chunkPath);\n\n currentChunk.content += content;\n return true;\n}\n\nfunction appendToEntry(node) {\n fs.appendFileSync(\n chunksEntry,\n `\\n// @from(${getPositionInfo(node)})\\n` + getContent(node) + \"\\n\"\n );\n}\n\nfunction getPositionInfo(node) {\n return node.loc\n ? `Ln ${node.loc.start.line}, Col ${node.loc.start.column}`\n : `Start ${node.start}, End ${node.end}`;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/improve-merged-chunks.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst acorn = require(\"acorn-loose\");\nconst walk = require(\"acorn-walk\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\nconst chunksIndex = JSON.parse(\n fs.readFileSync(path.resolve(chunksDir, \"chunks.index.json\"), \"utf-8\")\n);\nconst mergedIndex = JSON.parse(\n fs.readFileSync(path.resolve(mergedChunksDir, \"chunks.index.json\"), \"utf-8\")\n);\n\nfor (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (chunk.startsWith(\"claude-code-\")) {\n const content = fs.readFileSync(\n path.resolve(mergedChunksDir, chunk),\n \"utf-8\"\n );\n\n let depsSummary =\n \"/* Some variables in the code import from the following projects\\n\";\n const deps = {};\n for (const v of roughFindUndefinedVariables(content)) {\n if (chunksIndex[v]) {\n const project = mergedIndex[chunksIndex[v].replace(\".mjs\", \".json\")];\n if (project.startsWith(\"claude-code\")) {\n continue;\n }\n deps[project] = deps[project] || [];\n deps[project].push(v);\n }\n }\n for (const project in deps) {\n depsSummary += `* ${deps[project].join(\n \", \"\n )} import from OSS \"${project}\"\\n`;\n }\n depsSummary += \"*/\";\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `improved-${chunk}`),\n `${depsSummary}\\n${content}`\n );\n }\n}\n\nfunction roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n\n const defined = new Set();\n const used = new Set();\n\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/llm.js", "const { createGoogleGenerativeAI } = require(\"@ai-sdk/google\");\nconst { fetch, ProxyAgent } = require(\"undici\");\n\nconst dispatcher = process.env.http_proxy ? new ProxyAgent(process.env.http_proxy) : undefined;\n\nconst google = createGoogleGenerativeAI({\n fetch: async (req, options) => {\n return fetch(req, {\n ...options,\n ...(dispatcher && { dispatcher }),\n });\n },\n});\n\nmodule.exports = {\n google,\n};\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/beautify.js", "const beautify = require('js-beautify/js').js\nconst fs = require('fs')\nconst path = require('path')\n\nconst original = fs.readFileSync(path.resolve(__dirname, '../cli.mjs'), 'utf-8')\n\nfs.writeFileSync(path.resolve(__dirname, '../cli.beautify.mjs'), beautify(original, {\n indent_size: 2,\n space_in_empty_paren: true,\n}))"]], "task_instance_info": {"created_time": "2025-08-20 23:52:40", "created_task_model": "DeepSeek-R1", "function_skeleton": "function parseMessageToJson (input) {}", "code_description": "This code segment functions to: Extract and validate structured data formats from text responses by locating potential code blocks, enforcing single-result constraints, and converting formatted strings into standardized data objects while providing error handling for parsing failures."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction parseMessageToJson(input) {\n const codeBlockRegex = /```(?:json)?\\n([\\s\\S]+?)\\n```/;\n const match = input.match(codeBlockRegex);\n let jsonStr = input;\n\n if (match) {\n jsonStr = match[1];\n } else {\n const firstBrace = jsonStr.indexOf('{');\n const lastBrace = jsonStr.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {\n jsonStr = jsonStr.slice(firstBrace, lastBrace + 1);\n }\n }\n\n try {\n return JSON.parse(jsonStr);\n } catch (e) {\n throw new Error(`Failed to parse JSON: ${e.message}`);\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-53-20"}, "editdistance_info": {"edit_distance": 32.7381, "calculate_time": "2025-08-20 23:53:20", "true_code_clean": "function parseMessageToJson(input) {\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n let jsonString;\n if (matches.length === 1) {\n jsonString = matches[0][1].trim();\n } else {\n jsonString = input.trim();\n }\n try {\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}", "predict_code_clean": "function parseMessageToJson(input) {\n const codeBlockRegex = /```(?:json)?\\n([\\s\\S]+?)\\n```/;\n const match = input.match(codeBlockRegex);\n let jsonStr = input;\n if (match) {\n jsonStr = match[1];\n } else {\n const firstBrace = jsonStr.indexOf('{');\n const lastBrace = jsonStr.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {\n jsonStr = jsonStr.slice(firstBrace, lastBrace + 1);\n }\n }\n try {\n return JSON.parse(jsonStr);\n } catch (e) {\n throw new Error(`Failed to parse JSON: ${e.message}`);\n }\n}"}} {"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/improve-merged-chunks.js", "inference_info": {"prefix_code": "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst acorn = require(\"acorn-loose\");\nconst walk = require(\"acorn-walk\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\nconst chunksIndex = JSON.parse(\n fs.readFileSync(path.resolve(chunksDir, \"chunks.index.json\"), \"utf-8\")\n);\nconst mergedIndex = JSON.parse(\n fs.readFileSync(path.resolve(mergedChunksDir, \"chunks.index.json\"), \"utf-8\")\n);\n\nfor (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (chunk.startsWith(\"claude-code-\")) {\n const content = fs.readFileSync(\n path.resolve(mergedChunksDir, chunk),\n \"utf-8\"\n );\n\n let depsSummary =\n \"/* Some variables in the code import from the following projects\\n\";\n const deps = {};\n for (const v of roughFindUndefinedVariables(content)) {\n if (chunksIndex[v]) {\n const project = mergedIndex[chunksIndex[v].replace(\".mjs\", \".json\")];\n if (project.startsWith(\"claude-code\")) {\n continue;\n }\n deps[project] = deps[project] || [];\n deps[project].push(v);\n }\n }\n for (const project in deps) {\n depsSummary += `* ${deps[project].join(\n \", \"\n )} import from OSS \"${project}\"\\n`;\n }\n depsSummary += \"*/\";\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `improved-${chunk}`),\n `${depsSummary}\\n${content}`\n );\n }\n}\n\n", "suffix_code": "\n", "middle_code": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/split.js", "const acorn = require(\"acorn\");\nconst walk = require(\"acorn-walk\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst CHUNK_THRESHOLD = 100_000;\nconst currentChunk = {\n pathCount: 1,\n content: \"\",\n};\n\nconst source = fs.readFileSync(\n path.resolve(__dirname, \"../cli.beautify.mjs\"),\n \"utf-8\"\n);\n\nconst ast = acorn.parse(source, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n});\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\nconst chunksEntry = path.resolve(chunksDir, \"cli.chunks.mjs\");\nfs.writeFileSync(chunksEntry, \"\");\n\n// help Mac users\nconst namedSet = new Set();\nfunction namer(value) {\n let count = 0;\n let newValue = `${value.toLowerCase()}_${count}`;\n while (namedSet.has(newValue)) {\n count++;\n newValue = `${value.toLowerCase()}_${count}`;\n }\n namedSet.add(newValue);\n return newValue;\n}\n\nconst chunksIndex = {};\n\nwalk.fullAncestor(ast, (node, _state, ancestors) => {\n if (node.type === \"Program\") {\n return;\n }\n\n const lastAncestor = ancestors[ancestors.length - 2]; // exclude current\n if (lastAncestor.type !== \"Program\") {\n // only split top level\n return;\n }\n\n let splited = false;\n switch (node.type) {\n case \"FunctionDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n case \"ExportNamedDeclaration\": {\n let exportName = node.specifiers.find((s) => s.type === \"ExportSpecifier\")\n .exported.name;\n splited = writeWithCheck(getContent(node), exportName);\n return;\n }\n case \"VariableDeclaration\":\n if (node.declarations.some((decl) => decl.id.type !== \"Identifier\")) {\n return;\n }\n node.declarations.forEach((decl) => {\n declSplited = writeWithCheck(getContent(decl), decl.id.name);\n });\n return;\n case \"ClassDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n default:\n }\n\n if (!splited) {\n appendToEntry(node);\n }\n});\n\n// flush last chunk\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`),\n currentChunk.content\n);\n\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.index.json`),\n JSON.stringify(chunksIndex, null, 2)\n);\n\nfunction getContent(node) {\n return `\\n// @from(${getPositionInfo(node)})\\n${source.slice(\n node.start,\n node.end\n )}`;\n}\n\nfunction writeWithCheck(content, name) {\n const chunkPath = path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`);\n if (currentChunk.content.length + content.length > CHUNK_THRESHOLD) {\n // flush\n fs.writeFileSync(chunkPath, currentChunk.content);\n currentChunk.content = \"\";\n currentChunk.pathCount++;\n }\n\n // keep small chunks inline\n // if (content.length < 2000) {\n // return false;\n // }\n\n if (chunksIndex[name]) {\n throw new Error(\"name conflict\", { name });\n }\n chunksIndex[name] = path.relative(chunksDir, chunkPath);\n\n currentChunk.content += content;\n return true;\n}\n\nfunction appendToEntry(node) {\n fs.appendFileSync(\n chunksEntry,\n `\\n// @from(${getPositionInfo(node)})\\n` + getContent(node) + \"\\n\"\n );\n}\n\nfunction getPositionInfo(node) {\n return node.loc\n ? `Ln ${node.loc.start.line}, Col ${node.loc.start.column}`\n : `Start ${node.start}, End ${node.end}`;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\nconst mergedIndex = {};\n\nfunction manualFixNaming(project) {\n // fix LLM naming issue\n let lowerCaseProject = project.toLowerCase();\n\n return (\n {\n \"sentry-javascript\": \"sentry\",\n \"react devtools\": \"react\",\n \"aws-sdk-js-v3\": \"aws-sdk\",\n \"@aws-sdk/signature-v4\": \"aws-sdk\",\n \"@smithy/smithy-client\": \"aws-sdk\",\n \"aws sdk for javascript\": \"aws-sdk\",\n \"statsig-js\": \"statsig\",\n // 58\n \"claude-code\": \"claude-code-1\",\n // 59\n \"langchain.js\": 'claude-code-2',\n // 60\n zod: 'claude-code-3',\n // 61\n \"claude code\": \"claude-code-4\",\n // 62\n \"continue code\": \"claude-code-5\",\n tengu: \"claude-code-5\",\n // 64\n \"@anthropic-ai/claude-code\": \"claude-code-6\",\n }[lowerCaseProject] || lowerCaseProject\n );\n}\n\nfor (const chunk of fs.readdirSync(chunksDir)) {\n const chunkPath = path.resolve(chunksDir, chunk);\n if (!chunkPath.endsWith(\".json\")) {\n continue;\n }\n\n const { ossProjects = [] } = JSON.parse(\n fs.readFileSync(chunkPath, \"utf-8\")\n );\n\n for (const prpject of ossProjects) {\n const projectName = manualFixNaming(prpject);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n }\n}\n\nfor (const project in mergedIndex) {\n let content = \"\";\n for (const chunkPath of new Set(mergedIndex[project])) {\n content += fs.readFileSync(\n path.resolve(chunksDir, chunkPath.replace(\".json\", \".mjs\")),\n \"utf-8\"\n );\n }\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}\n\nfs.writeFileSync(\n path.resolve(mergedChunksDir, \"chunks.index.json\"),\n JSON.stringify(Object.keys(mergedIndex).reduce((prev, cur) => {\n for (const chunk of mergedIndex[cur]) {\n prev[chunk] = cur;\n }\n return prev;\n }, {}), null, 2)\n);\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/learn-chunks.js", "const { generateText } = require(\"ai\");\nconst { google } = require('./llm')\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n\nconst prompts = {\n system:\n \"You are a JS and opensource-software specialist, going to explain some uglified JS code.\",\n user: (\n code\n ) => `Here are some uglified codes. Read and answer the following questions\n\n1. Is it part of several open source projects code you know? If it is likely, tell me the name of the open source project.\n2. The purpose of the code snippet.\n\nResponse JSON Format:\n{\n \"ossProjects\": [\"$name_1\", \"$name_2\"],\n \"purpose\": \"$description\"\n}\n\n\\`\\`\\`\n${code}\n\\`\\`\\``,\n};\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\n(async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n})();\n\nfunction parseMessageToJson(input) {\n // Regular expression to match JSON code blocks\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n\n // Find all matches for JSON code blocks\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n\n let jsonString;\n\n if (matches.length === 1) {\n // Extract JSON content from the code block, trimming whitespace\n jsonString = matches[0][1].trim();\n } else {\n // No JSON code block found, use the entire input\n jsonString = input.trim();\n }\n\n try {\n // Parse the JSON string into an object\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}\n\nmodule.exports = {\n google,\n parseMessageToJson,\n prompts\n}"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/ask.js", "const { generateText } = require(\"ai\");\nconst { prompts } = require(\"./learn-chunks\");\nconst { google } = require(\"./llm\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst marked = require(\"marked\");\nconst { markedTerminal } = require(\"marked-terminal\");\nconst readline = require(\"readline\");\n\nmarked.use(markedTerminal());\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\n(async () => {\n // Prompt the user for a question\n const QUESTION = await new Promise((resolve) => {\n rl.question(\"Enter your question about the code: \", (answer) => {\n resolve(answer);\n });\n });\n\n console.log(`Analyzing question: \"${QUESTION}\"\\n`);\n\n let insight = \"\";\n let final = \"\";\n\n for (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (!chunk.startsWith(\"improved-\")) {\n continue;\n }\n\n console.log(\"Processing\", chunk);\n\n prompts.user = (\n code\n ) => `I am analyzing a Node.JS CLI AI program called claude-code, which implements an AI coder by interacting with LLM, using tool calling, ModelContextProtocol and other functions.\n\nThe question I want to focus on now is:\n\n\n${QUESTION}\n\n\nThe following is its source code fragment, which has been obfuscated by uglify. Please tell me the code logic that is directly or indirectly related to the problem I want to study.\nOnly answer me what you read from the code I provided.\n\nThe code logic I am more concerned about includes:\n\n1. Its prompt design\n2. Its LLM calling method\n3. Other related logic\n\n\n${insight}\n\n \n\n${code}\n\n\\`\\`\\``;\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(\n fs.readFileSync(path.resolve(mergedChunksDir, chunk), \"utf-8\")\n ),\n },\n ],\n maxRetries: 5,\n });\n\n insight += `\\n \n${text}\n \\n`;\n final = text;\n }\n\n console.log(`=== Answer ===\\n`);\n console.log(marked.parse(final));\n\n rl.close();\n})();\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/llm.js", "const { createGoogleGenerativeAI } = require(\"@ai-sdk/google\");\nconst { fetch, ProxyAgent } = require(\"undici\");\n\nconst dispatcher = process.env.http_proxy ? new ProxyAgent(process.env.http_proxy) : undefined;\n\nconst google = createGoogleGenerativeAI({\n fetch: async (req, options) => {\n return fetch(req, {\n ...options,\n ...(dispatcher && { dispatcher }),\n });\n },\n});\n\nmodule.exports = {\n google,\n};\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/beautify.js", "const beautify = require('js-beautify/js').js\nconst fs = require('fs')\nconst path = require('path')\n\nconst original = fs.readFileSync(path.resolve(__dirname, '../cli.mjs'), 'utf-8')\n\nfs.writeFileSync(path.resolve(__dirname, '../cli.beautify.mjs'), beautify(original, {\n indent_size: 2,\n space_in_empty_paren: true,\n}))"]], "task_instance_info": {"created_time": "2025-08-20 23:52:55", "created_task_model": "DeepSeek-R1", "function_skeleton": "function roughFindUndefinedVariables (code) {}", "code_description": "This code segment functions to: Analyze source code syntax to detect identifiers that are referenced but not declared within the codebase, enabling identification of external dependencies through static analysis."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction roughFindUndefinedVariables(code) {\n const declared = new Set();\n const referenced = new Set();\n const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n\n // Collect declarations\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === 'Identifier') {\n declared.add(node.id.name);\n } else if (node.id.type === 'ObjectPattern') {\n node.id.properties.forEach(prop => {\n if (prop.value.type === 'Identifier') declared.add(prop.value.name);\n });\n }\n },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n },\n ClassDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n },\n ImportDefaultSpecifier(node) {\n declared.add(node.local.name);\n },\n ImportNamespaceSpecifier(node) {\n declared.add(node.local.name);\n },\n ImportSpecifier(node) {\n declared.add(node.local.name);\n },\n Function(node) {\n node.params.forEach(param => {\n if (param.type === 'Identifier') {\n declared.add(param.name);\n } else if (param.type === 'ObjectPattern') {\n param.properties.forEach(prop => {\n if (prop.value.type === 'Identifier') declared.add(prop.value.name);\n });\n }\n });\n }\n });\n\n // Collect references\n walk.simple(ast, {\n Identifier(node) {\n const parent = node.parent;\n if (!parent || \n (parent.type !== 'VariableDeclarator' || parent.id !== node) &&\n (parent.type !== 'FunctionDeclaration' || parent.id !== node) &&\n (parent.type !== 'FunctionExpression' || parent.id !== node) &&\n parent.type !== 'ImportSpecifier' &&\n parent.type !== 'ImportDefaultSpecifier' &&\n parent.type !== 'ImportNamespaceSpecifier' &&\n parent.type !== 'ClassDeclaration') {\n referenced.add(node.name);\n }\n }\n });\n\n const globals = new Set(['console', 'process', 'module', 'exports', 'require', 'global']);\n return [...new Set([...referenced].filter(name => \n !declared.has(name) && \n !globals.has(name) && \n !name.startsWith('_')\n ))];\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-54-16"}, "editdistance_info": {"edit_distance": 21.0191, "calculate_time": "2025-08-20 23:54:16", "true_code_clean": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "predict_code_clean": "function roughFindUndefinedVariables(code) {\n const declared = new Set();\n const referenced = new Set();\n const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === 'Identifier') {\n declared.add(node.id.name);\n } else if (node.id.type === 'ObjectPattern') {\n node.id.properties.forEach(prop => {\n if (prop.value.type === 'Identifier') declared.add(prop.value.name);\n });\n }\n },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n },\n ClassDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n },\n ImportDefaultSpecifier(node) {\n declared.add(node.local.name);\n },\n ImportNamespaceSpecifier(node) {\n declared.add(node.local.name);\n },\n ImportSpecifier(node) {\n declared.add(node.local.name);\n },\n Function(node) {\n node.params.forEach(param => {\n if (param.type === 'Identifier') {\n declared.add(param.name);\n } else if (param.type === 'ObjectPattern') {\n param.properties.forEach(prop => {\n if (prop.value.type === 'Identifier') declared.add(prop.value.name);\n });\n }\n });\n }\n });\n walk.simple(ast, {\n Identifier(node) {\n const parent = node.parent;\n if (!parent || \n (parent.type !== 'VariableDeclarator' || parent.id !== node) &&\n (parent.type !== 'FunctionDeclaration' || parent.id !== node) &&\n (parent.type !== 'FunctionExpression' || parent.id !== node) &&\n parent.type !== 'ImportSpecifier' &&\n parent.type !== 'ImportDefaultSpecifier' &&\n parent.type !== 'ImportNamespaceSpecifier' &&\n parent.type !== 'ClassDeclaration') {\n referenced.add(node.name);\n }\n }\n });\n const globals = new Set(['console', 'process', 'module', 'exports', 'require', 'global']);\n return [...new Set([...referenced].filter(name => \n !declared.has(name) && \n !globals.has(name) && \n !name.startsWith('_')\n ))];\n}"}} {"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/improve-merged-chunks.js", "inference_info": {"prefix_code": "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst acorn = require(\"acorn-loose\");\nconst walk = require(\"acorn-walk\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\nconst chunksIndex = JSON.parse(\n fs.readFileSync(path.resolve(chunksDir, \"chunks.index.json\"), \"utf-8\")\n);\nconst mergedIndex = JSON.parse(\n fs.readFileSync(path.resolve(mergedChunksDir, \"chunks.index.json\"), \"utf-8\")\n);\n\nfor (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (chunk.startsWith(\"claude-code-\")) {\n const content = fs.readFileSync(\n path.resolve(mergedChunksDir, chunk),\n \"utf-8\"\n );\n\n let depsSummary =\n \"/* Some variables in the code import from the following projects\\n\";\n const deps = {};\n for (const v of roughFindUndefinedVariables(content)) {\n if (chunksIndex[v]) {\n const project = mergedIndex[chunksIndex[v].replace(\".mjs\", \".json\")];\n if (project.startsWith(\"claude-code\")) {\n continue;\n }\n deps[project] = deps[project] || [];\n deps[project].push(v);\n }\n }\n for (const project in deps) {\n depsSummary += `* ${deps[project].join(\n \", \"\n )} import from OSS \"${project}\"\\n`;\n }\n depsSummary += \"*/\";\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `improved-${chunk}`),\n `${depsSummary}\\n${content}`\n );\n }\n}\n\n", "suffix_code": "\n", "middle_code": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/split.js", "const acorn = require(\"acorn\");\nconst walk = require(\"acorn-walk\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst CHUNK_THRESHOLD = 100_000;\nconst currentChunk = {\n pathCount: 1,\n content: \"\",\n};\n\nconst source = fs.readFileSync(\n path.resolve(__dirname, \"../cli.beautify.mjs\"),\n \"utf-8\"\n);\n\nconst ast = acorn.parse(source, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n});\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\nconst chunksEntry = path.resolve(chunksDir, \"cli.chunks.mjs\");\nfs.writeFileSync(chunksEntry, \"\");\n\n// help Mac users\nconst namedSet = new Set();\nfunction namer(value) {\n let count = 0;\n let newValue = `${value.toLowerCase()}_${count}`;\n while (namedSet.has(newValue)) {\n count++;\n newValue = `${value.toLowerCase()}_${count}`;\n }\n namedSet.add(newValue);\n return newValue;\n}\n\nconst chunksIndex = {};\n\nwalk.fullAncestor(ast, (node, _state, ancestors) => {\n if (node.type === \"Program\") {\n return;\n }\n\n const lastAncestor = ancestors[ancestors.length - 2]; // exclude current\n if (lastAncestor.type !== \"Program\") {\n // only split top level\n return;\n }\n\n let splited = false;\n switch (node.type) {\n case \"FunctionDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n case \"ExportNamedDeclaration\": {\n let exportName = node.specifiers.find((s) => s.type === \"ExportSpecifier\")\n .exported.name;\n splited = writeWithCheck(getContent(node), exportName);\n return;\n }\n case \"VariableDeclaration\":\n if (node.declarations.some((decl) => decl.id.type !== \"Identifier\")) {\n return;\n }\n node.declarations.forEach((decl) => {\n declSplited = writeWithCheck(getContent(decl), decl.id.name);\n });\n return;\n case \"ClassDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n default:\n }\n\n if (!splited) {\n appendToEntry(node);\n }\n});\n\n// flush last chunk\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`),\n currentChunk.content\n);\n\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.index.json`),\n JSON.stringify(chunksIndex, null, 2)\n);\n\nfunction getContent(node) {\n return `\\n// @from(${getPositionInfo(node)})\\n${source.slice(\n node.start,\n node.end\n )}`;\n}\n\nfunction writeWithCheck(content, name) {\n const chunkPath = path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`);\n if (currentChunk.content.length + content.length > CHUNK_THRESHOLD) {\n // flush\n fs.writeFileSync(chunkPath, currentChunk.content);\n currentChunk.content = \"\";\n currentChunk.pathCount++;\n }\n\n // keep small chunks inline\n // if (content.length < 2000) {\n // return false;\n // }\n\n if (chunksIndex[name]) {\n throw new Error(\"name conflict\", { name });\n }\n chunksIndex[name] = path.relative(chunksDir, chunkPath);\n\n currentChunk.content += content;\n return true;\n}\n\nfunction appendToEntry(node) {\n fs.appendFileSync(\n chunksEntry,\n `\\n// @from(${getPositionInfo(node)})\\n` + getContent(node) + \"\\n\"\n );\n}\n\nfunction getPositionInfo(node) {\n return node.loc\n ? `Ln ${node.loc.start.line}, Col ${node.loc.start.column}`\n : `Start ${node.start}, End ${node.end}`;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\nconst mergedIndex = {};\n\nfunction manualFixNaming(project) {\n // fix LLM naming issue\n let lowerCaseProject = project.toLowerCase();\n\n return (\n {\n \"sentry-javascript\": \"sentry\",\n \"react devtools\": \"react\",\n \"aws-sdk-js-v3\": \"aws-sdk\",\n \"@aws-sdk/signature-v4\": \"aws-sdk\",\n \"@smithy/smithy-client\": \"aws-sdk\",\n \"aws sdk for javascript\": \"aws-sdk\",\n \"statsig-js\": \"statsig\",\n // 58\n \"claude-code\": \"claude-code-1\",\n // 59\n \"langchain.js\": 'claude-code-2',\n // 60\n zod: 'claude-code-3',\n // 61\n \"claude code\": \"claude-code-4\",\n // 62\n \"continue code\": \"claude-code-5\",\n tengu: \"claude-code-5\",\n // 64\n \"@anthropic-ai/claude-code\": \"claude-code-6\",\n }[lowerCaseProject] || lowerCaseProject\n );\n}\n\nfor (const chunk of fs.readdirSync(chunksDir)) {\n const chunkPath = path.resolve(chunksDir, chunk);\n if (!chunkPath.endsWith(\".json\")) {\n continue;\n }\n\n const { ossProjects = [] } = JSON.parse(\n fs.readFileSync(chunkPath, \"utf-8\")\n );\n\n for (const prpject of ossProjects) {\n const projectName = manualFixNaming(prpject);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n }\n}\n\nfor (const project in mergedIndex) {\n let content = \"\";\n for (const chunkPath of new Set(mergedIndex[project])) {\n content += fs.readFileSync(\n path.resolve(chunksDir, chunkPath.replace(\".json\", \".mjs\")),\n \"utf-8\"\n );\n }\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}\n\nfs.writeFileSync(\n path.resolve(mergedChunksDir, \"chunks.index.json\"),\n JSON.stringify(Object.keys(mergedIndex).reduce((prev, cur) => {\n for (const chunk of mergedIndex[cur]) {\n prev[chunk] = cur;\n }\n return prev;\n }, {}), null, 2)\n);\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/learn-chunks.js", "const { generateText } = require(\"ai\");\nconst { google } = require('./llm')\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n\nconst prompts = {\n system:\n \"You are a JS and opensource-software specialist, going to explain some uglified JS code.\",\n user: (\n code\n ) => `Here are some uglified codes. Read and answer the following questions\n\n1. Is it part of several open source projects code you know? If it is likely, tell me the name of the open source project.\n2. The purpose of the code snippet.\n\nResponse JSON Format:\n{\n \"ossProjects\": [\"$name_1\", \"$name_2\"],\n \"purpose\": \"$description\"\n}\n\n\\`\\`\\`\n${code}\n\\`\\`\\``,\n};\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\n(async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n})();\n\nfunction parseMessageToJson(input) {\n // Regular expression to match JSON code blocks\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n\n // Find all matches for JSON code blocks\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n\n let jsonString;\n\n if (matches.length === 1) {\n // Extract JSON content from the code block, trimming whitespace\n jsonString = matches[0][1].trim();\n } else {\n // No JSON code block found, use the entire input\n jsonString = input.trim();\n }\n\n try {\n // Parse the JSON string into an object\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}\n\nmodule.exports = {\n google,\n parseMessageToJson,\n prompts\n}"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/ask.js", "const { generateText } = require(\"ai\");\nconst { prompts } = require(\"./learn-chunks\");\nconst { google } = require(\"./llm\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst marked = require(\"marked\");\nconst { markedTerminal } = require(\"marked-terminal\");\nconst readline = require(\"readline\");\n\nmarked.use(markedTerminal());\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\n(async () => {\n // Prompt the user for a question\n const QUESTION = await new Promise((resolve) => {\n rl.question(\"Enter your question about the code: \", (answer) => {\n resolve(answer);\n });\n });\n\n console.log(`Analyzing question: \"${QUESTION}\"\\n`);\n\n let insight = \"\";\n let final = \"\";\n\n for (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (!chunk.startsWith(\"improved-\")) {\n continue;\n }\n\n console.log(\"Processing\", chunk);\n\n prompts.user = (\n code\n ) => `I am analyzing a Node.JS CLI AI program called claude-code, which implements an AI coder by interacting with LLM, using tool calling, ModelContextProtocol and other functions.\n\nThe question I want to focus on now is:\n\n\n${QUESTION}\n\n\nThe following is its source code fragment, which has been obfuscated by uglify. Please tell me the code logic that is directly or indirectly related to the problem I want to study.\nOnly answer me what you read from the code I provided.\n\nThe code logic I am more concerned about includes:\n\n1. Its prompt design\n2. Its LLM calling method\n3. Other related logic\n\n\n${insight}\n\n \n\n${code}\n\n\\`\\`\\``;\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(\n fs.readFileSync(path.resolve(mergedChunksDir, chunk), \"utf-8\")\n ),\n },\n ],\n maxRetries: 5,\n });\n\n insight += `\\n \n${text}\n \\n`;\n final = text;\n }\n\n console.log(`=== Answer ===\\n`);\n console.log(marked.parse(final));\n\n rl.close();\n})();\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/llm.js", "const { createGoogleGenerativeAI } = require(\"@ai-sdk/google\");\nconst { fetch, ProxyAgent } = require(\"undici\");\n\nconst dispatcher = process.env.http_proxy ? new ProxyAgent(process.env.http_proxy) : undefined;\n\nconst google = createGoogleGenerativeAI({\n fetch: async (req, options) => {\n return fetch(req, {\n ...options,\n ...(dispatcher && { dispatcher }),\n });\n },\n});\n\nmodule.exports = {\n google,\n};\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/beautify.js", "const beautify = require('js-beautify/js').js\nconst fs = require('fs')\nconst path = require('path')\n\nconst original = fs.readFileSync(path.resolve(__dirname, '../cli.mjs'), 'utf-8')\n\nfs.writeFileSync(path.resolve(__dirname, '../cli.beautify.mjs'), beautify(original, {\n indent_size: 2,\n space_in_empty_paren: true,\n}))"]], "task_instance_info": {"created_time": "2025-08-20 23:53:00", "created_task_model": "DeepSeek-R1", "function_skeleton": "function roughFindUndefinedVariables (code) {}", "code_description": "This code segment functions to: Analyze source code structure to detect unresolved variable references by comparing identifier usage against declarations and return missing dependencies requiring external resolution"}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction roughFindUndefinedVariables(code) {\n const ast = acorn.loose.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n const declared = new Set();\n const referenced = new Set();\n\n function collectDeclaredIds(node) {\n if (!node) return;\n if (node.type === 'Identifier') {\n declared.add(node.name);\n } else if (node.type === 'ObjectPattern') {\n node.properties.forEach(prop => {\n if (prop.type === 'Property') collectDeclaredIds(prop.value);\n else if (prop.type === 'RestElement') collectDeclaredIds(prop.argument);\n });\n } else if (node.type === 'ArrayPattern') {\n node.elements.forEach(element => element && collectDeclaredIds(element));\n } else if (node.type === 'RestElement') {\n collectDeclaredIds(node.argument);\n } else if (node.type === 'AssignmentPattern') {\n collectDeclaredIds(node.left);\n }\n }\n\n walk.simple(ast, {\n VariableDeclarator(node) { collectDeclaredIds(node.id) },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(collectDeclaredIds);\n },\n FunctionExpression(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(collectDeclaredIds);\n },\n ArrowFunctionExpression(node) { node.params.forEach(collectDeclaredIds) },\n ClassDeclaration(node) { node.id && declared.add(node.id.name) },\n CatchClause(node) { node.param && collectDeclaredIds(node.param) }\n });\n\n walk.simple(ast, {\n Identifier(node) {\n if (declared.has(node.name)) return;\n const parent = node.parent;\n const isPropertyKey = parent.type === 'Property' && parent.key === node && !parent.computed;\n const isMemberProp = parent.type === 'MemberExpression' && parent.property === node && !parent.computed;\n if (!isPropertyKey && !isMemberProp) referenced.add(node.name);\n }\n });\n\n return Array.from(referenced);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-54-26"}, "editdistance_info": {"edit_distance": 19.6347, "calculate_time": "2025-08-20 23:54:26", "true_code_clean": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "predict_code_clean": "function roughFindUndefinedVariables(code) {\n const ast = acorn.loose.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n const declared = new Set();\n const referenced = new Set();\n function collectDeclaredIds(node) {\n if (!node) return;\n if (node.type === 'Identifier') {\n declared.add(node.name);\n } else if (node.type === 'ObjectPattern') {\n node.properties.forEach(prop => {\n if (prop.type === 'Property') collectDeclaredIds(prop.value);\n else if (prop.type === 'RestElement') collectDeclaredIds(prop.argument);\n });\n } else if (node.type === 'ArrayPattern') {\n node.elements.forEach(element => element && collectDeclaredIds(element));\n } else if (node.type === 'RestElement') {\n collectDeclaredIds(node.argument);\n } else if (node.type === 'AssignmentPattern') {\n collectDeclaredIds(node.left);\n }\n }\n walk.simple(ast, {\n VariableDeclarator(node) { collectDeclaredIds(node.id) },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(collectDeclaredIds);\n },\n FunctionExpression(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(collectDeclaredIds);\n },\n ArrowFunctionExpression(node) { node.params.forEach(collectDeclaredIds) },\n ClassDeclaration(node) { node.id && declared.add(node.id.name) },\n CatchClause(node) { node.param && collectDeclaredIds(node.param) }\n });\n walk.simple(ast, {\n Identifier(node) {\n if (declared.has(node.name)) return;\n const parent = node.parent;\n const isPropertyKey = parent.type === 'Property' && parent.key === node && !parent.computed;\n const isMemberProp = parent.type === 'MemberExpression' && parent.property === node && !parent.computed;\n if (!isPropertyKey && !isMemberProp) referenced.add(node.name);\n }\n });\n return Array.from(referenced);\n}"}} {"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/improve-merged-chunks.js", "inference_info": {"prefix_code": "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst acorn = require(\"acorn-loose\");\nconst walk = require(\"acorn-walk\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\nconst chunksIndex = JSON.parse(\n fs.readFileSync(path.resolve(chunksDir, \"chunks.index.json\"), \"utf-8\")\n);\nconst mergedIndex = JSON.parse(\n fs.readFileSync(path.resolve(mergedChunksDir, \"chunks.index.json\"), \"utf-8\")\n);\n\nfor (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (chunk.startsWith(\"claude-code-\")) {\n const content = fs.readFileSync(\n path.resolve(mergedChunksDir, chunk),\n \"utf-8\"\n );\n\n let depsSummary =\n \"/* Some variables in the code import from the following projects\\n\";\n const deps = {};\n for (const v of roughFindUndefinedVariables(content)) {\n if (chunksIndex[v]) {\n const project = mergedIndex[chunksIndex[v].replace(\".mjs\", \".json\")];\n if (project.startsWith(\"claude-code\")) {\n continue;\n }\n deps[project] = deps[project] || [];\n deps[project].push(v);\n }\n }\n for (const project in deps) {\n depsSummary += `* ${deps[project].join(\n \", \"\n )} import from OSS \"${project}\"\\n`;\n }\n depsSummary += \"*/\";\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `improved-${chunk}`),\n `${depsSummary}\\n${content}`\n );\n }\n}\n\n", "suffix_code": "\n", "middle_code": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/split.js", "const acorn = require(\"acorn\");\nconst walk = require(\"acorn-walk\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst CHUNK_THRESHOLD = 100_000;\nconst currentChunk = {\n pathCount: 1,\n content: \"\",\n};\n\nconst source = fs.readFileSync(\n path.resolve(__dirname, \"../cli.beautify.mjs\"),\n \"utf-8\"\n);\n\nconst ast = acorn.parse(source, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n});\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\nconst chunksEntry = path.resolve(chunksDir, \"cli.chunks.mjs\");\nfs.writeFileSync(chunksEntry, \"\");\n\n// help Mac users\nconst namedSet = new Set();\nfunction namer(value) {\n let count = 0;\n let newValue = `${value.toLowerCase()}_${count}`;\n while (namedSet.has(newValue)) {\n count++;\n newValue = `${value.toLowerCase()}_${count}`;\n }\n namedSet.add(newValue);\n return newValue;\n}\n\nconst chunksIndex = {};\n\nwalk.fullAncestor(ast, (node, _state, ancestors) => {\n if (node.type === \"Program\") {\n return;\n }\n\n const lastAncestor = ancestors[ancestors.length - 2]; // exclude current\n if (lastAncestor.type !== \"Program\") {\n // only split top level\n return;\n }\n\n let splited = false;\n switch (node.type) {\n case \"FunctionDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n case \"ExportNamedDeclaration\": {\n let exportName = node.specifiers.find((s) => s.type === \"ExportSpecifier\")\n .exported.name;\n splited = writeWithCheck(getContent(node), exportName);\n return;\n }\n case \"VariableDeclaration\":\n if (node.declarations.some((decl) => decl.id.type !== \"Identifier\")) {\n return;\n }\n node.declarations.forEach((decl) => {\n declSplited = writeWithCheck(getContent(decl), decl.id.name);\n });\n return;\n case \"ClassDeclaration\":\n splited = writeWithCheck(getContent(node), node.id.name);\n return;\n default:\n }\n\n if (!splited) {\n appendToEntry(node);\n }\n});\n\n// flush last chunk\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`),\n currentChunk.content\n);\n\nfs.writeFileSync(\n path.resolve(chunksDir, `chunks.index.json`),\n JSON.stringify(chunksIndex, null, 2)\n);\n\nfunction getContent(node) {\n return `\\n// @from(${getPositionInfo(node)})\\n${source.slice(\n node.start,\n node.end\n )}`;\n}\n\nfunction writeWithCheck(content, name) {\n const chunkPath = path.resolve(chunksDir, `chunks.${currentChunk.pathCount}.mjs`);\n if (currentChunk.content.length + content.length > CHUNK_THRESHOLD) {\n // flush\n fs.writeFileSync(chunkPath, currentChunk.content);\n currentChunk.content = \"\";\n currentChunk.pathCount++;\n }\n\n // keep small chunks inline\n // if (content.length < 2000) {\n // return false;\n // }\n\n if (chunksIndex[name]) {\n throw new Error(\"name conflict\", { name });\n }\n chunksIndex[name] = path.relative(chunksDir, chunkPath);\n\n currentChunk.content += content;\n return true;\n}\n\nfunction appendToEntry(node) {\n fs.appendFileSync(\n chunksEntry,\n `\\n// @from(${getPositionInfo(node)})\\n` + getContent(node) + \"\\n\"\n );\n}\n\nfunction getPositionInfo(node) {\n return node.loc\n ? `Ln ${node.loc.start.line}, Col ${node.loc.start.column}`\n : `Start ${node.start}, End ${node.end}`;\n}\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "const fs = require(\"fs\");\nconst path = require(\"path\");\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\nconst mergedIndex = {};\n\nfunction manualFixNaming(project) {\n // fix LLM naming issue\n let lowerCaseProject = project.toLowerCase();\n\n return (\n {\n \"sentry-javascript\": \"sentry\",\n \"react devtools\": \"react\",\n \"aws-sdk-js-v3\": \"aws-sdk\",\n \"@aws-sdk/signature-v4\": \"aws-sdk\",\n \"@smithy/smithy-client\": \"aws-sdk\",\n \"aws sdk for javascript\": \"aws-sdk\",\n \"statsig-js\": \"statsig\",\n // 58\n \"claude-code\": \"claude-code-1\",\n // 59\n \"langchain.js\": 'claude-code-2',\n // 60\n zod: 'claude-code-3',\n // 61\n \"claude code\": \"claude-code-4\",\n // 62\n \"continue code\": \"claude-code-5\",\n tengu: \"claude-code-5\",\n // 64\n \"@anthropic-ai/claude-code\": \"claude-code-6\",\n }[lowerCaseProject] || lowerCaseProject\n );\n}\n\nfor (const chunk of fs.readdirSync(chunksDir)) {\n const chunkPath = path.resolve(chunksDir, chunk);\n if (!chunkPath.endsWith(\".json\")) {\n continue;\n }\n\n const { ossProjects = [] } = JSON.parse(\n fs.readFileSync(chunkPath, \"utf-8\")\n );\n\n for (const prpject of ossProjects) {\n const projectName = manualFixNaming(prpject);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n }\n}\n\nfor (const project in mergedIndex) {\n let content = \"\";\n for (const chunkPath of new Set(mergedIndex[project])) {\n content += fs.readFileSync(\n path.resolve(chunksDir, chunkPath.replace(\".json\", \".mjs\")),\n \"utf-8\"\n );\n }\n\n fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}\n\nfs.writeFileSync(\n path.resolve(mergedChunksDir, \"chunks.index.json\"),\n JSON.stringify(Object.keys(mergedIndex).reduce((prev, cur) => {\n for (const chunk of mergedIndex[cur]) {\n prev[chunk] = cur;\n }\n return prev;\n }, {}), null, 2)\n);\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/learn-chunks.js", "const { generateText } = require(\"ai\");\nconst { google } = require('./llm')\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n\nconst prompts = {\n system:\n \"You are a JS and opensource-software specialist, going to explain some uglified JS code.\",\n user: (\n code\n ) => `Here are some uglified codes. Read and answer the following questions\n\n1. Is it part of several open source projects code you know? If it is likely, tell me the name of the open source project.\n2. The purpose of the code snippet.\n\nResponse JSON Format:\n{\n \"ossProjects\": [\"$name_1\", \"$name_2\"],\n \"purpose\": \"$description\"\n}\n\n\\`\\`\\`\n${code}\n\\`\\`\\``,\n};\n\nconst chunksDir = path.resolve(__dirname, \"../chunks\");\n\n(async () => {\n for (const chunk of fs.readdirSync(chunksDir)) {\n const mjsPath = path.resolve(chunksDir, chunk);\n if (!mjsPath.endsWith(\".mjs\") || chunk === 'cli.chunks.mjs') {\n continue;\n }\n\n const jsonPath = mjsPath.replace(\".mjs\", \".json\");\n if (fs.existsSync(jsonPath)) {\n continue\n }\n\n const content = fs.readFileSync(mjsPath, \"utf-8\");\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(content),\n },\n ],\n maxRetries: 5\n });\n\n const struct = parseMessageToJson(text)\n fs.writeFileSync(jsonPath, JSON.stringify(struct, null, 2));\n }\n})();\n\nfunction parseMessageToJson(input) {\n // Regular expression to match JSON code blocks\n const jsonCodeBlockRegex = /```json\\n([\\s\\S]*?)\\n```/g;\n\n // Find all matches for JSON code blocks\n const matches = Array.from(input.matchAll(jsonCodeBlockRegex));\n\n if (matches.length > 1) {\n throw new Error(\"Multiple JSON code blocks found in the input string.\");\n }\n\n let jsonString;\n\n if (matches.length === 1) {\n // Extract JSON content from the code block, trimming whitespace\n jsonString = matches[0][1].trim();\n } else {\n // No JSON code block found, use the entire input\n jsonString = input.trim();\n }\n\n try {\n // Parse the JSON string into an object\n return JSON.parse(jsonString);\n } catch (error) {\n throw new Error(\"Failed to parse JSON: \" + error + \"\\n\\n\" + jsonString);\n }\n}\n\nmodule.exports = {\n google,\n parseMessageToJson,\n prompts\n}"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/ask.js", "const { generateText } = require(\"ai\");\nconst { prompts } = require(\"./learn-chunks\");\nconst { google } = require(\"./llm\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst marked = require(\"marked\");\nconst { markedTerminal } = require(\"marked-terminal\");\nconst readline = require(\"readline\");\n\nmarked.use(markedTerminal());\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nconst mergedChunksDir = path.resolve(__dirname, \"../merged-chunks\");\n\n(async () => {\n // Prompt the user for a question\n const QUESTION = await new Promise((resolve) => {\n rl.question(\"Enter your question about the code: \", (answer) => {\n resolve(answer);\n });\n });\n\n console.log(`Analyzing question: \"${QUESTION}\"\\n`);\n\n let insight = \"\";\n let final = \"\";\n\n for (const chunk of fs.readdirSync(mergedChunksDir)) {\n if (!chunk.startsWith(\"improved-\")) {\n continue;\n }\n\n console.log(\"Processing\", chunk);\n\n prompts.user = (\n code\n ) => `I am analyzing a Node.JS CLI AI program called claude-code, which implements an AI coder by interacting with LLM, using tool calling, ModelContextProtocol and other functions.\n\nThe question I want to focus on now is:\n\n\n${QUESTION}\n\n\nThe following is its source code fragment, which has been obfuscated by uglify. Please tell me the code logic that is directly or indirectly related to the problem I want to study.\nOnly answer me what you read from the code I provided.\n\nThe code logic I am more concerned about includes:\n\n1. Its prompt design\n2. Its LLM calling method\n3. Other related logic\n\n\n${insight}\n\n \n\n${code}\n\n\\`\\`\\``;\n\n const { text } = await generateText({\n model: google(\"gemini-2.0-flash\"),\n messages: [\n {\n role: \"system\",\n content: prompts.system,\n },\n {\n role: \"user\",\n content: prompts.user(\n fs.readFileSync(path.resolve(mergedChunksDir, chunk), \"utf-8\")\n ),\n },\n ],\n maxRetries: 5,\n });\n\n insight += `\\n \n${text}\n \\n`;\n final = text;\n }\n\n console.log(`=== Answer ===\\n`);\n console.log(marked.parse(final));\n\n rl.close();\n})();\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/llm.js", "const { createGoogleGenerativeAI } = require(\"@ai-sdk/google\");\nconst { fetch, ProxyAgent } = require(\"undici\");\n\nconst dispatcher = process.env.http_proxy ? new ProxyAgent(process.env.http_proxy) : undefined;\n\nconst google = createGoogleGenerativeAI({\n fetch: async (req, options) => {\n return fetch(req, {\n ...options,\n ...(dispatcher && { dispatcher }),\n });\n },\n});\n\nmodule.exports = {\n google,\n};\n"], ["/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/beautify.js", "const beautify = require('js-beautify/js').js\nconst fs = require('fs')\nconst path = require('path')\n\nconst original = fs.readFileSync(path.resolve(__dirname, '../cli.mjs'), 'utf-8')\n\nfs.writeFileSync(path.resolve(__dirname, '../cli.beautify.mjs'), beautify(original, {\n indent_size: 2,\n space_in_empty_paren: true,\n}))"]], "task_instance_info": {"created_time": "2025-08-20 23:52:55", "created_task_model": "DeepSeek-R1", "function_skeleton": "function roughFindUndefinedVariables (code) {}", "code_description": "This code segment functions to: Analyze source code to detect undeclared variable references by comparing identifier usage against defined declarations, identifying external dependencies through unresolved symbols."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n const declared = new Set();\n const knownGlobals = new Set(['require', 'module', 'exports', 'console', 'process', 'global', '__dirname', '__filename']);\n\n // Collect declared identifiers from various patterns\n function collectFromPattern(pattern) {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n declared.add(pattern.name);\n break;\n case 'ObjectPattern':\n pattern.properties.forEach(prop => {\n if (prop.type === 'Property') collectFromPattern(prop.value);\n else if (prop.type === 'RestElement') collectFromPattern(prop.argument);\n });\n break;\n case 'ArrayPattern':\n pattern.elements.forEach(el => el && collectFromPattern(el));\n break;\n case 'AssignmentPattern':\n collectFromPattern(pattern.left);\n break;\n case 'RestElement':\n collectFromPattern(pattern.argument);\n break;\n }\n }\n\n // First pass: collect all declared variables\n walk.ancestor(ast, {\n VariableDeclarator(node) { collectFromPattern(node.id) },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(p => collectFromPattern(p));\n },\n FunctionExpression(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(p => collectFromPattern(p));\n },\n ArrowFunctionExpression(node) {\n node.params.forEach(p => collectFromPattern(p));\n },\n ClassDeclaration(node) { node.id && declared.add(node.id.name) },\n CatchClause(node) { collectFromPattern(node.param) },\n ForInStatement(node) { node.left.type === 'VariableDeclaration' && node.left.declarations.forEach(d => collectFromPattern(d.id)) },\n ForOfStatement(node) { node.left.type === 'VariableDeclaration' && node.left.declarations.forEach(d => collectFromPattern(d.id)) }\n });\n\n // Second pass: find undefined references\n const undefinedVars = new Set();\n walk.simple(ast, {\n Identifier(node) {\n if (declared.has(node.name) || knownGlobals.has(node.name)) return;\n if (node.parent.type === 'MemberExpression' && node.parent.object === node) return;\n if (node.parent.type === 'Property' && node.parent.key === node) return;\n if (node.parent.type === 'MethodDefinition') return;\n \n undefinedVars.add(node.name);\n }\n });\n\n return Array.from(undefinedVars);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-54-57"}, "editdistance_info": {"edit_distance": 17.2147, "calculate_time": "2025-08-20 23:54:57", "true_code_clean": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, {\n allowHashBang: true,\n sourceType: \"module\",\n ecmaVersion: \"latest\",\n });\n const defined = new Set();\n const used = new Set();\n walk.simple(ast, {\n VariableDeclarator(node) {\n if (node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n FunctionDeclaration(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n ClassExpression(node) {\n if (node.id && node.id.type === \"Identifier\") {\n defined.add(node.id.name);\n }\n },\n Identifier(node) {\n used.add(node.name);\n },\n });\n const undefinedVars = [...used].filter((name) => !defined.has(name));\n return undefinedVars;\n}", "predict_code_clean": "function roughFindUndefinedVariables(code) {\n const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });\n const declared = new Set();\n const knownGlobals = new Set(['require', 'module', 'exports', 'console', 'process', 'global', '__dirname', '__filename']);\n function collectFromPattern(pattern) {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n declared.add(pattern.name);\n break;\n case 'ObjectPattern':\n pattern.properties.forEach(prop => {\n if (prop.type === 'Property') collectFromPattern(prop.value);\n else if (prop.type === 'RestElement') collectFromPattern(prop.argument);\n });\n break;\n case 'ArrayPattern':\n pattern.elements.forEach(el => el && collectFromPattern(el));\n break;\n case 'AssignmentPattern':\n collectFromPattern(pattern.left);\n break;\n case 'RestElement':\n collectFromPattern(pattern.argument);\n break;\n }\n }\n walk.ancestor(ast, {\n VariableDeclarator(node) { collectFromPattern(node.id) },\n FunctionDeclaration(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(p => collectFromPattern(p));\n },\n FunctionExpression(node) {\n if (node.id) declared.add(node.id.name);\n node.params.forEach(p => collectFromPattern(p));\n },\n ArrowFunctionExpression(node) {\n node.params.forEach(p => collectFromPattern(p));\n },\n ClassDeclaration(node) { node.id && declared.add(node.id.name) },\n CatchClause(node) { collectFromPattern(node.param) },\n ForInStatement(node) { node.left.type === 'VariableDeclaration' && node.left.declarations.forEach(d => collectFromPattern(d.id)) },\n ForOfStatement(node) { node.left.type === 'VariableDeclaration' && node.left.declarations.forEach(d => collectFromPattern(d.id)) }\n });\n const undefinedVars = new Set();\n walk.simple(ast, {\n Identifier(node) {\n if (declared.has(node.name) || knownGlobals.has(node.name)) return;\n if (node.parent.type === 'MemberExpression' && node.parent.object === node) return;\n if (node.parent.type === 'Property' && node.parent.key === node) return;\n if (node.parent.type === 'MethodDefinition') return;\n undefinedVars.add(node.name);\n }\n });\n return Array.from(undefinedVars);\n}"}}