File size: 33,836 Bytes
b29a38b |
1 2 3 |
{"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 ", "suffix_code": "\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}", "middle_code": "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 }", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "javascript", "sub_task_type": "for_statement"}, "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<focus_question>\n${QUESTION}\n</focus_question>\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<insight_from_other_code_fragment>\n${insight}\n</insight_from_other_code_fragment>\n \n<current_code_fragment>\n${code}\n</current_code_fragment>\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 <insight_from_${chunk}>\n${text}\n </insight_from_${chunk}>\\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-21 00:04:21", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Iterate through specified files in a directory, generate AI-powered analysis of their contents using predefined prompts, extract structured data from the responses, and persist the processed results as JSON files while avoiding redundant processing of previously analyzed files."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\n const files = await fs.promises.readdir(chunksDir);\n const results = [];\n\n for (const file of files) {\n const code = await fs.promises.readFile(path.join(chunksDir, file), \"utf8\");\n const { text } = await generateText({\n model: google,\n systemPrompt: prompts.system,\n prompt: prompts.user(code),\n });\n \n const analysis = parseMessageToJson(text);\n results.push({\n file,\n code,\n analysis\n });\n }\n\n await fs.promises.writeFile(\n path.join(chunksDir, \"results.json\"),\n JSON.stringify(results, null, 2)\n );\n[TASK_END]\n```", "inference_time": "2025-08-21 00-04-37"}, "editdistance_info": {"edit_distance": 20.0, "calculate_time": "2025-08-21 00:04:37", "true_code_clean": "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 }", "predict_code_clean": "const files = await fs.promises.readdir(chunksDir);\n const results = [];\n for (const file of files) {\n const code = await fs.promises.readFile(path.join(chunksDir, file), \"utf8\");\n const { text } = await generateText({\n model: google,\n systemPrompt: prompts.system,\n prompt: prompts.user(code),\n });\n const analysis = parseMessageToJson(text);\n results.push({\n file,\n code,\n analysis\n });\n }\n await fs.promises.writeFile(\n path.join(chunksDir, \"results.json\"),\n JSON.stringify(results, null, 2)\n );"}}
{"repo_name": "analysis_claude_code", "file_name": "/analysis_claude_code/claude_code_v_1.0.33/stage1_analysis_workspace/scripts/merge-again.js", "inference_info": {"prefix_code": "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\n", "suffix_code": "\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", "middle_code": "for (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 fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "javascript", "sub_task_type": "for_statement"}, "context_code": [["/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/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/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<focus_question>\n${QUESTION}\n</focus_question>\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<insight_from_other_code_fragment>\n${insight}\n</insight_from_other_code_fragment>\n \n<current_code_fragment>\n${code}\n</current_code_fragment>\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 <insight_from_${chunk}>\n${text}\n </insight_from_${chunk}>\\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-21 00:04:21", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Aggregate file contents from multiple sources into consolidated output files by iterating through grouped entries, deduplicating file references, and combining textual data into project-specific resources."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfor (const project of ossProjects) {\n const projectName = manualFixNaming(project);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-04-45"}, "editdistance_info": {"edit_distance": 16.4835, "calculate_time": "2025-08-21 00:04:45", "true_code_clean": "for (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 fs.writeFileSync(\n path.resolve(mergedChunksDir, `${project.replaceAll(\"/\", \"__\")}.mjs`),\n content\n );\n}", "predict_code_clean": "for (const project of ossProjects) {\n const projectName = manualFixNaming(project);\n mergedIndex[projectName] = mergedIndex[projectName] || [];\n mergedIndex[projectName].push(path.relative(chunksDir, chunkPath));\n}"}}
|