Resolve conflicts: keep local changes on zzx_branch

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
狗gogo 2026-07-07 13:08:51 +08:00
parent 4379b16083
commit 08037ca60b
8 changed files with 1010 additions and 163 deletions

View File

@ -162,6 +162,24 @@
.mode-toggle button:hover:not(.active) {
background:var(--bg-hover); border-color:var(--border-accent);
}
/* ── Agent selector buttons ── */
.agent-selector {
display:flex; gap:0; margin-top:6px;
}
.agent-selector button {
flex:1; padding:5px 8px; border:1px solid var(--border);
background:#fff; color:var(--text-dim); cursor:pointer;
font-size:11px; font-weight:500; transition: all .12s;
}
.agent-selector button:first-child { border-radius:var(--radius-sm) 0 0 var(--radius-sm); }
.agent-selector button:last-child { border-radius:0 var(--radius-sm) var(--radius-sm) 0; }
.agent-selector button:hover:not(.active) {
background:var(--bg-hover); border-color:var(--border-accent);
}
.agent-selector button.active { color:#fff; z-index:1; }
.agent-selector button.agent-claude.active { background:var(--purple); border-color:var(--purple); }
.agent-selector button.agent-codex.active { background:#0ea5e9; border-color:#0ea5e9; }
.agent-selector button.agent-zcode.active { background:#f59e0b; border-color:#f59e0b; }
#sidebar .modules {
padding:4px 0;
}
@ -386,11 +404,16 @@
</div>
</div>
<!-- ── Section 2: Claude Code Skills ── -->
<!-- ── Section 2: Agent Skills ── -->
<div class="sidebar-section" id="skills-section">
<div class="sidebar-header skills-header" onclick="toggleSection('skills-section')">
<span class="section-arrow"></span> 🤖 Claude Code Skills
<span class="section-arrow"></span> 🤖 AGENT SKILLS
<span id="session-badge" style="display:none;font-size:10px;background:var(--purple);color:#fff;padding:1px 6px;border-radius:8px;margin-left:6px;" title="会话进行中">● 会话中</span>
<div class="agent-selector" onclick="event.stopPropagation()">
<button id="agent-claude" class="agent-claude active" onclick="setAgent('claude')">🤖 Claude Code</button>
<button id="agent-codex" class="agent-codex" onclick="setAgent('codex')">📟 Codex</button>
<button id="agent-zcode" class="agent-zcode" onclick="setAgent('zcode')">⚡ ZCode</button>
</div>
<div class="mode-toggle" onclick="event.stopPropagation()">
<button id="skills-mode-direct" class="active" onclick="setSkillsExecMode('direct')">⚡ 直接运行</button>
<button id="skills-mode-input" onclick="setSkillsExecMode('input')">✎ 编辑模式</button>
@ -658,6 +681,12 @@ var currentEngine = 'powershell'; // 'powershell' | 'claude'
var cliExecMode = 'direct'; // CLI section mode
var skillsExecMode = 'direct'; // Skills section mode
var claudeSessionId = null; // Claude Code session ID for multi-turn
var currentAgent = 'claude'; // 'claude' | 'codex' | 'zcode'
var AGENT_META = {
claude: { icon: '🤖', name: 'Claude Code', btnColor: 'var(--purple)' },
codex: { icon: '📟', name: 'Codex', btnColor: '#0ea5e9' },
zcode: { icon: '⚡', name: 'ZCode', btnColor: '#f59e0b' }
};
// ═══════════════════════════════════════════════
// Section Toggle (top-level collapse)
@ -728,11 +757,12 @@ function setSkillsExecMode(mode) {
function setEngine(engine) {
currentEngine = engine;
if (engine === 'claude') {
inputPrompt.innerHTML = '🤖&gt;';
var meta = AGENT_META[currentAgent];
inputPrompt.innerHTML = meta.icon + '&gt;';
inputPrompt.title = '点击切换为 PowerShell';
cmdInput.placeholder = '输入 Claude Code 提示词或从左侧 Skills 选择...';
btnRun.textContent = '▶ 执行 (Claude)';
btnRun.style.background = 'var(--purple)';
btnRun.textContent = '▶ 执行 (' + meta.name + ')';
btnRun.style.background = meta.btnColor;
} else {
inputPrompt.innerHTML = 'PS&gt;';
inputPrompt.title = '点击切换为 Claude Code';
@ -746,6 +776,48 @@ function toggleEngine() {
setEngine(currentEngine === 'powershell' ? 'claude' : 'powershell');
}
// ═══════════════════════════════════════════════
// Prompt helper: update input prompt from AGENT_META
// ═══════════════════════════════════════════════
function updateInputPrompt() {
if (currentEngine === 'claude') {
var meta = AGENT_META[currentAgent];
inputPrompt.innerHTML = meta.icon + '&gt;';
} else {
inputPrompt.innerHTML = 'PS&gt;';
}
}
// ═══════════════════════════════════════════════
// Agent Selector (Skills section)
// ═══════════════════════════════════════════════
function setAgent(agent) {
if (agent === currentAgent) return;
currentAgent = agent;
// Update button active states
document.getElementById('agent-claude').className = 'agent-claude' + (agent === 'claude' ? ' active' : '');
document.getElementById('agent-codex').className = 'agent-codex' + (agent === 'codex' ? ' active' : '');
document.getElementById('agent-zcode').className = 'agent-zcode' + (agent === 'zcode' ? ' active' : '');
// Clear terminal output (but keep session)
terminal.innerHTML = '';
// Show switch message
var meta = AGENT_META[agent];
appendEntry('info', 'agent已切换为 ' + meta.name);
// Switch engine to Claude mode if not already
if (currentEngine !== 'claude') {
setEngine('claude');
} else {
updateInputPrompt();
}
scrollToBottom();
}
// ═══════════════════════════════════════════════
// Module Toggle
// ═══════════════════════════════════════════════
@ -832,8 +904,9 @@ function executeDirectClaude(prompt) {
btnCancel.classList.add('visible');
cmdInput.value = '';
var meta = AGENT_META[currentAgent];
appendEntry('cmd-line',
'<span class="prompt">🤖</span> <span class="cmd-text">' + escHtml(prompt) + '</span>');
'<span class="prompt">' + meta.icon + '</span> <span class="cmd-text">' + escHtml(prompt) + '</span>');
sendClaudeRequest(prompt);
}
@ -852,7 +925,8 @@ function executeCommand() {
btnRun.classList.add('running');
btnCancel.classList.add('visible');
var promptHtml = isClaude ? '🤖&gt;' : 'PS&gt;';
var meta = AGENT_META[currentAgent];
var promptHtml = isClaude ? meta.icon + '&gt;' : 'PS&gt;';
appendEntry('cmd-line',
'<span class="prompt">' + promptHtml + '</span> <span class="cmd-text">' + escHtml(command) + '</span>');
@ -1112,8 +1186,9 @@ function resetExecState() {
cmdInput.focus();
// Restore button text based on current engine
if (currentEngine === 'claude') {
btnRun.textContent = '▶ 执行 (Claude)';
btnRun.style.background = 'var(--purple)';
var meta = AGENT_META[currentAgent];
btnRun.textContent = '▶ 执行 (' + meta.name + ')';
btnRun.style.background = meta.btnColor;
} else {
btnRun.textContent = '▶ 执行';
btnRun.style.background = '';

Binary file not shown.

View File

@ -23,7 +23,7 @@ param(
)
$ErrorActionPreference = "Stop"
Import-Module "$PSScriptRoot/lib/common.psm1" -Force
Import-Module "$PSScriptRoot/lib/common.psm1" -Force -WarningAction SilentlyContinue
if ($Help) {
Write-Host "Usage: powershell 04-multi-repo-collab.ps1 -Org ORG [-Repos 'repo1,repo2'] [-Release TAG] [-Output FILE] [-DryRun]"

View File

@ -28,7 +28,7 @@ param(
)
$ErrorActionPreference = "Stop"
Import-Module "$PSScriptRoot/lib/common.psm1" -Force
Import-Module "$PSScriptRoot/lib/common.psm1" -Force -WarningAction SilentlyContinue
if ($Help) {
Write-Host "Usage: powershell 05-contributor-growth.ps1 -Owner OWNER -Repo REPO [-Sample N] [-Award] [-DryRun]"

View File

@ -1,11 +1,11 @@
# GitLink 科研辅助 — 场景 1仓库级科研项目洞察 (PowerShell)
# GitLink Research - Scenario 1: Repository Project Insight (PowerShell)
param(
[string]$Owner, [string]$Repo, [string]$Output = "",
[switch]$NoWiki, [switch]$DryRun
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\lib\common.psm1" -Force
Import-Module "$ScriptDir\..\lib\common.psm1" -Force -WarningAction SilentlyContinue
$ErrorActionPreference = "Continue"
Check-Auth
@ -16,47 +16,49 @@ $OutputDir = Join-Path $ScriptDir "..\output"
if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null }
$OutputFile = if ($Output) { $Output } else { Join-Path $OutputDir "research-insights-${Repo}-${Today}.html" }
Log-Title "GitLink 科研辅助 — 仓库级项目洞察"
Log-Title "GitLink Research - Repository Project Insight"
# 1. Repo metadata
Log-Step "1/6 获取仓库元数据..."
Log-Step "1/6 Fetching repo metadata..."
$repoJson = Invoke-GLCheck @("repo", "+info", "--owner", $Owner, "--repo", $Repo)
$repoName = $repoJson.data.name ?? $repoJson.data.full_name ?? $Repo
$repoDesc = $repoJson.data.description ?? "No description"
$repoLang = $repoJson.data.language ?? "Unknown"
$stars = [int]($repoJson.data.stars_count ?? $repoJson.data.stars ?? 0)
$forks = [int]($repoJson.data.forks_count ?? $repoJson.data.forks ?? 0)
$openIssues = [int]($repoJson.data.open_issues_count ?? 0)
$updatedAt = $repoJson.data.updated_at ?? ""
$repoName = if ($repoJson.data.name) { $repoJson.data.name } elseif ($repoJson.data.full_name) { $repoJson.data.full_name } else { $Repo }
$repoDesc = if ($repoJson.data.description) { $repoJson.data.description } else { "No description" }
$repoLang = if ($repoJson.data.language) { $repoJson.data.language } else { "Unknown" }
$stars = if ($repoJson.data.stars_count) { [int]$repoJson.data.stars_count } elseif ($repoJson.data.stars) { [int]$repoJson.data.stars } else { 0 }
$forks = if ($repoJson.data.forks_count) { [int]$repoJson.data.forks_count } elseif ($repoJson.data.forks) { [int]$repoJson.data.forks } else { 0 }
$openIssues = if ($repoJson.data.open_issues_count) { [int]$repoJson.data.open_issues_count } else { 0 }
$updatedAt = if ($repoJson.data.updated_at) { $repoJson.data.updated_at } else { "" }
Log-Info " 名称: $repoName | 语言: $repoLang | Stars: $stars"
Log-Info " Name: $repoName | Lang: $repoLang | Stars: $stars"
# 2. Issues
Log-Step "2/6 收集 Issue 数据..."
Log-Step "2/6 Collecting Issue data..."
$openIssuesJson = Invoke-GL @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "100")
$closedIssuesJson = Invoke-GL @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "closed", "--limit", "100")
$totalOpen = if ($openIssuesJson.ok) { @($openIssuesJson.data.issues ?? $openIssuesJson.data).Count } else { 0 }
$totalClosed = if ($closedIssuesJson.ok) { @($closedIssuesJson.data.issues ?? $closedIssuesJson.data).Count } else { 0 }
$totalOpen = if ($openIssuesJson.ok) { $d = if ($openIssuesJson.data.issues) { $openIssuesJson.data.issues } else { $openIssuesJson.data }; @($d).Count } else { 0 }
$totalClosed = if ($closedIssuesJson.ok) { $d = if ($closedIssuesJson.data.issues) { $closedIssuesJson.data.issues } else { $closedIssuesJson.data }; @($d).Count } else { 0 }
# 3. PRs
Log-Step "3/6 收集 PR 数据..."
Log-Step "3/6 Collecting PR data..."
$mergedPrsJson = Invoke-GL @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "merged", "--limit", "100")
$openPrsJson = Invoke-GL @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "50")
$totalMerged = if ($mergedPrsJson.ok) { @($mergedPrsJson.data.issues ?? $mergedPrsJson.data.pulls ?? $mergedPrsJson.data).Count } else { 0 }
$totalOpenPrs = if ($openPrsJson.ok) { @($openPrsJson.data.issues ?? $openPrsJson.data.pulls ?? $openPrsJson.data).Count } else { 0 }
$md = if ($mergedPrsJson.data.issues) { $mergedPrsJson.data.issues } elseif ($mergedPrsJson.data.pulls) { $mergedPrsJson.data.pulls } else { $mergedPrsJson.data }
$totalMerged = if ($mergedPrsJson.ok) { @($md).Count } else { 0 }
$od = if ($openPrsJson.data.issues) { $openPrsJson.data.issues } elseif ($openPrsJson.data.pulls) { $openPrsJson.data.pulls } else { $openPrsJson.data }
$totalOpenPrs = if ($openPrsJson.ok) { @($od).Count } else { 0 }
# 4. Releases
Log-Step "4/6 收集 Release 数据..."
Log-Step "4/6 Collecting Release data..."
$releasesJson = Invoke-GL @("release", "+list", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$releaseCount = if ($releasesJson.ok) { @($releasesJson.data).Count } else { 0 }
# 5. CI
Log-Step "5/6 收集 CI 数据..."
Log-Step "5/6 Collecting CI data..."
$ciJson = Invoke-GL @("ci", "+builds", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$ciBuilds = if ($ciJson.ok) { @($ciJson.data).Count } else { 0 }
# 6. Members
Log-Step "6/6 获取贡献者..."
Log-Step "6/6 Fetching contributors..."
$membersJson = Invoke-GL @("repo", "+members", "--owner", $Owner, "--repo", $Repo, "--limit", "50")
$memberCount = if ($membersJson.ok) {
$d = if ($membersJson.data.members) { $membersJson.data.members } else { $membersJson.data }
@ -75,18 +77,298 @@ $hotness = [Math]::Round($starsNorm * 0.15 + $forksNorm * 0.10 + $issuesScore *
$prMergeRate = if (($totalMerged + $totalOpenPrs) -gt 0) { [Math]::Round($totalMerged / ($totalMerged + $totalOpenPrs) * 100, 1) } else { 0 }
Log-Ok "热度评分: ${hotness}/100"
Log-Info " Issues: $totalOpen 开放 / $totalClosed 关闭"
Log-Info " PR 合并率: ${prMergeRate}% | Releases: $releaseCount | 贡献者: $memberCount"
Log-Ok "Hotness score: ${hotness}/100"
Log-Info " Issues: $totalOpen open / $totalClosed closed"
Log-Info " PR merge rate: ${prMergeRate}% | Releases: $releaseCount | Contributors: $memberCount"
# Additional data for HTML report
$ciPassRate = 0
if ($ciBuilds -gt 0) {
$ciSuccess = 0
if ($ciJson.ok) {
$ciData = if ($ciJson.data) { $ciJson.data } else { @() }
foreach ($b in $ciData) {
$status = if ($b.status) { $b.status } else { "" }
if ($status -eq "success" -or $status -eq "completed") { $ciSuccess++ }
}
}
$ciPassRate = [Math]::Round($ciSuccess / $ciBuilds * 100, 1)
}
$daysSinceUpdate = 365
if ($updatedAt -and $updatedAt.Length -ge 10) {
try { $daysSinceUpdate = ((Get-Date) - [DateTime]$updatedAt.Substring(0, 10)).Days } catch { $daysSinceUpdate = 365 }
}
$recencyFactor = if ($daysSinceUpdate -le 30) { 100 } elseif ($daysSinceUpdate -le 90) { 50 } else { 10 }
$hotnessLabel = if ($hotness -ge 50) { "Hot" } elseif ($hotness -ge 30) { "Warm" } else { "Cool" }
$starsNorm = [Math]::Round([Math]::Min($stars / 1000.0, 1.0) * 100, 1)
$forksNorm = [Math]::Round([Math]::Min($forks / 200.0, 1.0) * 100, 1)
$issuesActive = [Math]::Round([Math]::Min($totalOpen / 50.0, 1.0) * 100, 1)
$prsActive = [Math]::Round([Math]::Min(($totalMerged + $totalOpenPrs) / 30.0, 1.0) * 100, 1)
$releasesActive = [Math]::Round([Math]::Min($releaseCount / 10.0, 1.0) * 100, 1)
$createdAt = if ($repoJson.data.created_at) { $repoJson.data.created_at } else { "" }
$createdAtDisplay = if ($createdAt.Length -ge 10) { $createdAt.Substring(0, 10) } else { "Unknown" }
$updatedAtDisplay = if ($updatedAt.Length -ge 10) { $updatedAt.Substring(0, 10) } else { "Unknown" }
# Detect tech stack
Log-Step "Detecting tech stack..."
$techStack = $repoLang
$researchFeatures = ""
$hasCitationCff = $false
$subJson = try { Invoke-GL @("api", "GET", "/v1/$Owner/$Repo/sub_entries?ref=master") } catch { $null }
if ($subJson -and $subJson.ok -and ($subJson.data -is [array])) {
$names = @($subJson.data | ForEach-Object { if ($_.name) { $_.name } else { "" } })
$ecosystem = @()
if ($names -contains "go.mod") { $ecosystem += "Go" }
if ($names -contains "package.json") { $ecosystem += "Node.js" }
if ($names | Where-Object { $_ -match "requirements\.txt|pyproject\.toml|setup\.py|setup\.cfg|Pipfile" }) { $ecosystem += "Python" }
if ($names -contains "Cargo.toml") { $ecosystem += "Rust" }
if ($names -contains "CMakeLists.txt") { $ecosystem += "C/C++" }
if ($names | Where-Object { $_ -match "pom\.xml|build\.gradle" }) { $ecosystem += "Java/Kotlin" }
if ($names -contains "CITATION.cff") { $hasCitationCff = $true; $ecosystem += "+CITATION.cff" }
if ($ecosystem.Count -gt 0) { $techStack = ($ecosystem -join " ") }
if ($names | Where-Object { $_ -match "Dockerfile|docker-compose" }) { $researchFeatures += " Docker" }
if ($names | Where-Object { $_ -match "^data/|^datasets/" }) { $researchFeatures += " dataset" }
if ($names | Where-Object { $_ -match "\.ipynb$" }) { $researchFeatures += " Jupyter" }
if ($names | Where-Object { $_ -match "^scripts/|^experiments/" }) { $researchFeatures += " experiment-scripts" }
}
Log-Info " Tech stack: $techStack"
# Readme analysis
Log-Step "Reading README for project positioning..."
$readmeText = ""
try {
$readmeResult = Invoke-GL @("api", "GET", "raw/$Owner/$Repo/master/README.md")
if ($readmeResult.ok) { $readmeText = if ($readmeResult.data) { $readmeResult.data } else { "" } }
} catch { $readmeText = "" }
$projectTopics = ""
$topicKeywords = @("machine learning","deep learning","neural network","NLP","computer vision",
"reinforcement learning","GAN","transformer","LLM","RAG","agent","bioinformatics","genomics",
"drug discovery","robotics","autonomous","simulation","optimization","benchmark","dataset",
"pre-trained","fine-tuning","distributed","federated","graph neural","knowledge graph",
"recommender","anomaly detection","scientific computing","HPC","quantum","climate","physics",
"chemistry")
foreach ($kw in $topicKeywords) {
if ($repoDesc -match [regex]::Escape($kw) -or $readmeText -match [regex]::Escape($kw)) {
if ($projectTopics) { $projectTopics += ", " }
$projectTopics += $kw
}
}
$doiFound = ""
if ($repoDesc -match '10\.\d{4,}/[\w.\-/]+') { $doiFound = $Matches[0] }
elseif ($readmeText -match '10\.\d{4,}/[\w.\-/]+') { $doiFound = $Matches[0] }
# ===== Generate HTML Report =====
Log-Step "Generating HTML report..."
$hotnessClass = $hotnessLabel.ToLower()
# Build tech stack tags
$techStackTags = ""
foreach ($t in ($techStack -split '\s+')) {
if ($t) { $techStackTags += "<span class=`"tag lang`">$t</span> " }
}
# Build research features tags
$researchTags = ""
foreach ($f in ($researchFeatures -split '\s+' | Where-Object { $_ })) {
$researchTags += "<span class=`"tag research`">$f</span> "
}
if (-not $researchTags) { $researchTags = "<span class=`"tag lang`">None detected</span>" }
# Build topic tags
$topicTags = ""
foreach ($t in ($projectTopics -split ', ' | Where-Object { $_ })) {
$topicTags += "<span class=`"tag lang`">$t</span> "
}
if (-not $topicTags) { $topicTags = "<span>None detected</span>" }
$issueStatus = if ($totalOpen -gt 20) { "<span class=`"tag warn`">Needs attention</span>" } else { "<span class=`"tag research`">Normal</span>" }
$prStatus = if ($prMergeRate -gt 70) { "<span class=`"tag research`">Healthy</span>" } else { "<span class=`"tag warn`">Needs improvement</span>" }
$releaseStatus = if ($releaseCount -gt 0) { "<span class=`"tag research`">Released</span>" } else { "<span class=`"tag warn`">No release</span>" }
$ciStatus = if ($ciPassRate -gt 80) { "<span class=`"tag research`">Stable</span>" } else { "<span class=`"tag warn`">Unstable</span>" }
$memberStatus = if ($memberCount -gt 3) { "<span class=`"tag research`">Active community</span>" } else { "<span class=`"tag warn`">Solo project</span>" }
$activityStatus = if ($daysSinceUpdate -le 30) { "<span class=`"tag research`">Active</span>" } else { "<span class=`"tag warn`">Inactive</span>" }
$doiRow = ""
if ($doiFound) { $doiRow = "<tr><th>DOI</th><td><a href=`"https://doi.org/$doiFound`">$doiFound</a></td></tr>" }
$htmlContent = @"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$Owner/$Repo &mdash; Research Project Insight Report</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #333; }
.header { background: linear-gradient(135deg, #1a237e 0%, #283593 50%, #3949ab 100%); color: #fff; padding: 40px 30px; }
.header h1 { font-size: 28px; margin-bottom: 8px; }
.header .subtitle { opacity: 0.85; font-size: 14px; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.card .label { font-size: 12px; color: #888; text-transform: uppercase; margin-bottom: 6px; }
.card .value { font-size: 28px; font-weight: 700; }
.card .value.hot { color: #e53935; }
.card .value.warm { color: #f57c00; }
.card .value.cool { color: #1565c0; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
.panel { background: #fff; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.panel h2 { font-size: 18px; margin-bottom: 16px; color: #1a237e; border-bottom: 2px solid #3949ab; padding-bottom: 8px; }
.chart { width: 100%; height: 350px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid #eee; font-size: 14px; }
th { background: #f5f7fa; color: #555; font-weight: 600; }
.tag { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; margin: 2px; }
.tag.lang { background: #e3f2fd; color: #1565c0; }
.tag.research { background: #e8f5e9; color: #2e7d32; }
.tag.warn { background: #fff3e0; color: #e65100; }
.footer { text-align: center; padding: 24px; color: #999; font-size: 12px; }
@media (max-width: 768px) { .row { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="header">
<h1>$Owner/$Repo</h1>
<div class="subtitle">Research Project Insight Report &mdash; $Today</div>
</div>
<div class="container">
<div class="cards">
<div class="card">
<div class="label">Hotness Score</div>
<div class="value $hotnessClass">$hotness</div>
<div class="label">$hotnessLabel</div>
</div>
<div class="card">
<div class="label">Stars</div>
<div class="value">$stars</div>
</div>
<div class="card">
<div class="label">Forks</div>
<div class="value">$forks</div>
</div>
<div class="card">
<div class="label">Contributors</div>
<div class="value">$memberCount</div>
</div>
<div class="card">
<div class="label">Open Issues</div>
<div class="value">$totalOpen</div>
</div>
<div class="card">
<div class="label">PR Merge Rate</div>
<div class="value">${prMergeRate}%</div>
</div>
</div>
<div class="row">
<div class="panel">
<h2>Project Overview</h2>
<table>
<tr><th>Name</th><td>$repoName</td></tr>
<tr><th>Description</th><td>$repoDesc</td></tr>
<tr><th>Language</th><td><span class="tag lang">$repoLang</span></td></tr>
<tr><th>Tech Stack</th><td>$techStackTags</td></tr>
<tr><th>Created</th><td>$createdAtDisplay</td></tr>
<tr><th>Updated</th><td>$updatedAtDisplay ($daysSinceUpdate days ago)</td></tr>
<tr><th>Research Features</th><td>$researchTags</td></tr>
$doiRow
<tr><th>Topics</th><td>$topicTags</td></tr>
</table>
</div>
<div class="panel">
<h2>Activity Overview</h2>
<div id="activityChart" class="chart"></div>
</div>
</div>
<div class="row">
<div class="panel">
<h2>Health Indicators</h2>
<table>
<tr><th>Indicator</th><th>Value</th><th>Status</th></tr>
<tr><td>Total Issues</td><td>$totalOpen open / $totalClosed closed</td><td>$issueStatus</td></tr>
<tr><td>PR Merge Rate</td><td>${prMergeRate}%</td><td>$prStatus</td></tr>
<tr><td>Releases</td><td>$releaseCount</td><td>$releaseStatus</td></tr>
<tr><td>CI Pass Rate</td><td>${ciPassRate}% ($ciBuilds builds)</td><td>$ciStatus</td></tr>
<tr><td>Contributors</td><td>$memberCount people</td><td>$memberStatus</td></tr>
<tr><td>Activity</td><td>$daysSinceUpdate days since update</td><td>$activityStatus</td></tr>
</table>
</div>
<div class="panel">
<h2>Hotness Composition</h2>
<div id="hotnessChart" class="chart"></div>
</div>
</div>
</div>
<div class="footer">Generated by GitLink Research Assistant &mdash; $Today</div>
<script>
var hotnessChart = echarts.init(document.getElementById('hotnessChart'));
hotnessChart.setOption({
tooltip: { trigger: 'item' },
legend: { bottom: 0 },
series: [{
type: 'pie',
radius: ['45%', '75%'],
label: { formatter: '{b}\n{d}%' },
data: [
{ name: 'Stars', value: $starsNorm, itemStyle: { color: '#5470c6' } },
{ name: 'Forks', value: $forksNorm, itemStyle: { color: '#91cc75' } },
{ name: 'Issues', value: $issuesActive, itemStyle: { color: '#fac858' } },
{ name: 'PRs', value: $prsActive, itemStyle: { color: '#ee6666' } },
{ name: 'Releases', value: $releasesActive, itemStyle: { color: '#73c0de' } },
{ name: 'Recency', value: $recencyFactor, itemStyle: { color: '#fc8452' } }
]
}]
});
var activityChart = echarts.init(document.getElementById('activityChart'));
activityChart.setOption({
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', data: ['Issues', 'PRs', 'Releases', 'CI Builds'] },
yAxis: { type: 'value' },
series: [
{ name: 'Open/In Progress', type: 'bar', data: [$totalOpen, $totalOpenPrs, 0, 0], itemStyle: { color: '#fac858' } },
{ name: 'Completed', type: 'bar', data: [$totalClosed, $totalMerged, $releaseCount, $ciBuilds], itemStyle: { color: '#91cc75' } }
]
});
</script>
</body>
</html>
"@
if (-not $DryRun) {
$htmlContent | Out-File -FilePath $OutputFile -Encoding UTF8
Log-Ok "HTML report generated: $OutputFile"
} else {
Log-Warn "[DRY RUN] Would generate: $OutputFile"
}
# Summary output
Divider
Write-Host "====== 报告摘要 ======" -ForegroundColor White
Write-Host " 仓库: $Owner/$Repo"
Write-Host " 语言: $repoLang"
Write-Host " 热度评分: $hotness/100"
Write-Host " Issues: $totalOpen 开放 / $totalClosed 关闭"
Write-Host " PR 合并率: ${prMergeRate}%"
Write-Host " 贡献者: $memberCount"
Write-Host "====== Analysis Summary ======" -ForegroundColor White
Write-Host " Repo: $Owner/$Repo"
Write-Host " Language: $repoLang"
Write-Host " Tech Stack: $techStack"
Write-Host " Hotness: $hotness/100 ($hotnessLabel)"
Write-Host " Issues: $totalOpen open / $totalClosed closed"
Write-Host " PR merge: ${prMergeRate}%"
Write-Host " CI pass: ${ciPassRate}%"
Write-Host " Members: $memberCount"
Write-Host " Features: $researchFeatures"
if ($doiFound) { Write-Host " DOI: $doiFound" }
Write-Host " Report: $OutputFile"
Divider
Log-Ok "分析完成"
Log-Ok "Analysis complete"

View File

@ -1,11 +1,11 @@
# GitLink 科研辅助 — 场景 3合规与复现性检查 (PowerShell)
# GitLink Research - Scenario 3: Compliance & Reproducibility Check (PowerShell)
param(
[string]$Owner, [string]$Repo, [string]$LocalPath = ".",
[string]$Output = "", [switch]$NoWiki, [switch]$DryRun
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\lib\common.psm1" -Force
Import-Module "$ScriptDir\..\lib\common.psm1" -Force -WarningAction SilentlyContinue
$ErrorActionPreference = "Continue"
Check-Auth
@ -14,8 +14,16 @@ $Owner = $resolved.Owner; $Repo = $resolved.Repo
$Today = Get-Date -Format "yyyy-MM-dd"
$OutputDir = Join-Path $ScriptDir "..\output"
if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null }
$OutputFile = if ($Output) { $Output } else { Join-Path $OutputDir "reproducibility-${Repo}-${Today}.html" }
Log-Title "GitLink 科研辅助 — 合规与复现性检查"
Log-Title "GitLink Research - Compliance & Reproducibility"
# Get repo metadata for description and DOI detection
Log-Step "Fetching repo metadata..."
$repoJson = Invoke-GLCheck @("repo", "+info", "--owner", $Owner, "--repo", $Repo)
$repoDesc = if ($repoJson.data.description) { $repoJson.data.description } else { "" }
$doiFound = ""
if ($repoDesc -match '10\.\d{4,}/[\w.\-/]+') { $doiFound = $Matches[0] }
# Scoring: 0, 0.5, 1.0 per dimension
$dLicense = @{Score=0; Detail=""}; $dNoSecret = @{Score=0; Detail=""}
@ -23,91 +31,185 @@ $dReadme = @{Score=0; Detail=""}; $dDeps = @{Score=0; Detail=""}
$dBuild = @{Score=0; Detail=""}; $dCI = @{Score=0; Detail=""}
$dTest = @{Score=0; Detail=""}; $dData = @{Score=0; Detail=""}
# -- Helper: ensure local clone of target repo for compliance scan --
function Ensure-LocalClone {
param([string]$Owner, [string]$Repo, [string]$LocalPath)
$result = @{ ScanPath = $null; NeedCleanup = $false }
# Check if current directory is already a clone of the target repo
if (Test-Path (Join-Path $LocalPath ".git")) {
Push-Location $LocalPath
try {
$remoteUrl = git remote get-url origin 2>$null
if ($remoteUrl -and ($remoteUrl -match [regex]::Escape("$Owner/$Repo"))) {
Pop-Location
Log-Info "Local path is already a clone of $Owner/$Repo"
$result.ScanPath = $LocalPath
return $result
}
} catch { }
Pop-Location
}
# Clone target repo to temp directory for compliance scan
$suffix = [System.Guid]::NewGuid().ToString().Substring(0, 8)
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) "gl-compliance-${Repo}-${suffix}"
Log-Info "Cloning $Owner/$Repo to temp directory for compliance scan..."
$cloneUrl = if ($env:GITLINK_TOKEN) {
"https://oauth2:$env:GITLINK_TOKEN@gitlink.org.cn/$Owner/$Repo.git"
} else {
"https://gitlink.org.cn/$Owner/$Repo.git"
}
$cloneOutput = git clone --depth 1 $cloneUrl $tempDir 2>&1
if ($LASTEXITCODE -ne 0) {
Log-Warn "HTTPS clone failed, trying SSH..."
$sshUrl = "git@gitlink.org.cn:$Owner/$Repo.git"
$cloneOutput = git clone --depth 1 $sshUrl $tempDir 2>&1
if ($LASTEXITCODE -ne 0) {
Log-Warn "Clone failed for both HTTPS and SSH. Skipping compliance scan."
Log-Warn "Reason: $($cloneOutput -join '; ')"
return $result
}
}
Log-Ok "Cloned successfully to $tempDir"
$result.ScanPath = $tempDir
$result.NeedCleanup = $true
return $result
}
# 1. Compliance scan
Log-Step "1/7 合规扫描..."
if (Test-Path (Join-Path $LocalPath ".git")) {
Push-Location $LocalPath
Log-Step "1/7 Compliance scan..."
$cloneInfo = Ensure-LocalClone -Owner $Owner -Repo $Repo -LocalPath $LocalPath
if ($cloneInfo.ScanPath -and (Test-Path (Join-Path $cloneInfo.ScanPath ".git"))) {
Push-Location $cloneInfo.ScanPath
$compResult = Invoke-GL @("compliance", "+scan")
Pop-Location
if ($compResult.ok) {
$licenseOk = $compResult.data.license.status ?? ""
if ($licenseOk -match "ok|clean|found") { $dLicense.Score = 1.0; $dLicense.Detail = "检测到合规许可证" }
elseif ($licenseOk -eq "warning") { $dLicense.Score = 0.5; $dLicense.Detail = "有许可证但非标准" }
else { $dLicense.Score = 0; $dLicense.Detail = "未检测到 LICENSE" }
$secCount = @($compResult.data.secrets.findings ?? @()).Count
$piiCount = @($compResult.data.exposure.findings ?? @()).Count
if ($secCount -eq 0 -and $piiCount -eq 0) { $dNoSecret.Score = 1.0; $dNoSecret.Detail = "未发现密钥/PII" }
elseif ($secCount + $piiCount -le 3) { $dNoSecret.Score = 0.5; $dNoSecret.Detail = "发现少量可疑项" }
else { $dNoSecret.Score = 0; $dNoSecret.Detail = "发现多处密钥/PII泄露" }
if ($cloneInfo.NeedCleanup) {
# Git objects are read-only on Windows; strip attributes first
Get-ChildItem -Path $cloneInfo.ScanPath -Recurse -Force -ErrorAction SilentlyContinue |
ForEach-Object { $_.Attributes = 'Normal' }
Remove-Item -Recurse -Force $cloneInfo.ScanPath -ErrorAction SilentlyContinue
if (Test-Path $cloneInfo.ScanPath) {
# Fallback: let cmd handle stubborn files
cmd /c "rd /s /q `"$($cloneInfo.ScanPath)`"" 2>$null
}
if (-not (Test-Path $cloneInfo.ScanPath)) {
Log-Info "Cleaned up temp clone."
} else {
Log-Warn "Could not fully remove temp clone: $($cloneInfo.ScanPath)"
}
}
} else { Log-Warn "本地仓库路径无 .git跳过合规扫描" }
if ($compResult.ok) {
$licenseOk = if ($null -ne $compResult.data.license.status) { $compResult.data.license.status } else { "" }
if ($licenseOk -match "ok|clean|found") { $dLicense.Score = 1.0; $dLicense.Detail = "Licensed (OK)" }
elseif ($licenseOk -eq "warning") { $dLicense.Score = 0.5; $dLicense.Detail = "License non-standard" }
else { $dLicense.Score = 0; $dLicense.Detail = "No LICENSE file" }
# Fix: proper PS5.1 null check instead of "if @()"
$secFindings = if ($compResult.data.secrets.findings) { $compResult.data.secrets.findings } else { @() }
$secCount = if ($secFindings -is [array]) { $secFindings.Count } else { 0 }
$piiFindings = if ($compResult.data.exposure.findings) { $compResult.data.exposure.findings } else { @() }
$piiCount = if ($piiFindings -is [array]) { $piiFindings.Count } else { 0 }
if ($secCount -eq 0 -and $piiCount -eq 0) { $dNoSecret.Score = 1.0; $dNoSecret.Detail = "No secrets/PII found" }
elseif ($secCount + $piiCount -le 3) { $dNoSecret.Score = 0.5; $dNoSecret.Detail = "Few suspicious items found" }
else { $dNoSecret.Score = 0; $dNoSecret.Detail = "Multiple secret/PII leaks" }
}
} else {
Log-Warn "Cannot access repo for compliance scan, skipping this dimension"
$dLicense.Detail = "Not scanned (repo inaccessible)"
$dNoSecret.Detail = "Not scanned (repo inaccessible)"
}
# 2. README
Log-Step "2/7 README 完整性..."
Log-Step "2/7 README completeness..."
try {
$readmeResult = Invoke-GL @("api", "GET", "raw/$Owner/$Repo/master/README.md")
if ($readmeResult.ok) { $readmeText = $readmeResult.data ?? "" } else { $readmeText = "" }
if ($readmeResult.ok) { $readmeText = if ($null -ne $readmeResult.data) { $readmeResult.data } else { "" } } else { $readmeText = "" }
} catch { $readmeText = "" }
$sectionCount = 0
foreach ($kw in @("# ", "## ", "Install", "Usage", "License", "Contribut", "Citation")) {
if ($readmeText -match $kw) { $sectionCount++ }
}
if ($sectionCount -ge 5) { $dReadme.Score = 1.0 }
elseif ($sectionCount -ge 3) { $dReadme.Score = 0.5 }
else { $dReadme.Score = 0 }
$dReadme.Detail = "README 章节数: $sectionCount"
Log-Info " $($dReadme.Detail)"
if ($sectionCount -ge 5) { $dReadme.Score = 1.0; $dReadme.Detail = "README complete, $sectionCount sections" }
elseif ($sectionCount -ge 3) { $dReadme.Score = 0.5; $dReadme.Detail = "README partial, $sectionCount sections" }
else { $dReadme.Score = 0; $dReadme.Detail = "README missing or too short" }
Log-Info " README sections: $sectionCount"
# 3. Dependencies
Log-Step "3/7 依赖声明..."
Log-Step "3/7 Dependency declaration..."
$subResult = Invoke-GL @("api", "GET", "/v1/$Owner/$Repo/sub_entries?ref=master")
$depFiles = 0
if ($subResult.ok) {
$names = @($subResult.data | ForEach-Object { $_.name ?? "" })
foreach ($df in @("package.json","go.mod","requirements.txt","pyproject.toml","Cargo.toml","CMakeLists.txt","pom.xml","build.gradle")) {
if ($names -contains $df) { $depFiles++ }
$depList = ""
$names = @()
if ($subResult.ok -and ($subResult.data -is [array])) {
$names = @($subResult.data | ForEach-Object { if ($null -ne $_.name) { $_.name } else { "" } })
foreach ($df in @("package.json","go.mod","requirements.txt","pyproject.toml","Cargo.toml","CMakeLists.txt","pom.xml","build.gradle","Gemfile","Makefile")) {
if ($names -contains $df) { $depFiles++; $depList += "$df, " }
}
}
if ($depFiles -ge 1) { $dDeps.Score = 1.0 }
elseif ($readmeText -match "dependenc|requirement|依赖|install") { $dDeps.Score = 0.5 }
else { $dDeps.Score = 0 }
$dDeps.Detail = "依赖文件数: $depFiles"
if ($depFiles -ge 1) { $dDeps.Score = 1.0; $dDeps.Detail = "Standard dep file(s): $depList".TrimEnd(', ') }
elseif ($readmeText -match "dependenc|requirement|install") { $dDeps.Score = 0.5; $dDeps.Detail = "Deps mentioned in README" }
else { $dDeps.Score = 0; $dDeps.Detail = "No dependency declaration" }
Log-Info " Dep files: $depFiles"
# 4. Build
Log-Step "4/7 构建说明..."
Log-Step "4/7 Build instructions..."
$buildScore = 0
if ($readmeText -match "build|install|compile|make|构建|安装|编译") { $buildScore++ }
if ($subResult.ok -and (@($subResult.data | Where-Object { $_.name -match "Makefile|Dockerfile" })).Count -gt 0) { $buildScore++ }
if ($buildScore -ge 2) { $dBuild.Score = 1.0 } elseif ($buildScore -ge 1) { $dBuild.Score = 0.5 } else { $dBuild.Score = 0 }
$dBuild.Detail = "构建说明得分: $buildScore/2"
if ($readmeText -match "build|install|compile|make|run") { $buildScore++ }
if ($names | Where-Object { $_ -match "Makefile|Dockerfile|docker-compose" }) { $buildScore++ }
if ($names | Where-Object { $_ -match "\.github/workflows|\.gitlab-ci|Jenkinsfile" }) { $buildScore++ }
if ($buildScore -ge 3) { $dBuild.Score = 1.0; $dBuild.Detail = "Detailed build docs + automation" }
elseif ($buildScore -ge 1) { $dBuild.Score = 0.5; $dBuild.Detail = "Partial build instructions" }
else { $dBuild.Score = 0; $dBuild.Detail = "No build instructions" }
Log-Info " Build score: $buildScore/3"
# 5. CI
Log-Step "5/7 CI 配置..."
Log-Step "5/7 CI configuration..."
$ciResult = Invoke-GL @("ci", "+builds", "--owner", $Owner, "--repo", $Repo, "--limit", "10")
$ciBuilds = if ($ciResult.ok) { @($ciResult.data).Count } else { 0 }
if ($ciBuilds -gt 0) { $dCI.Score = 1.0; $dCI.Detail = "CI 已配置 ($ciBuilds 次构建)" }
else { $dCI.Score = 0; $dCI.Detail = "无 CI 配置" }
$ciOk = 0
if ($ciResult.ok) {
foreach ($b in @($ciResult.data)) {
$status = if ($b.status) { $b.status } else { "" }
if ($status -eq "success" -or $status -eq "completed") { $ciOk++ }
}
}
if ($ciBuilds -gt 0 -and $ciOk -ge 1) { $dCI.Score = 1.0; $dCI.Detail = "CI configured & passing ($ciOk/$ciBuilds)" }
elseif ($ciBuilds -gt 0) { $dCI.Score = 0.5; $dCI.Detail = "CI exists but failing" }
else { $dCI.Score = 0; $dCI.Detail = "No CI configured" }
Log-Info " CI builds: $ciBuilds"
# 6. Tests
Log-Step "6/7 测试证据..."
Log-Step "6/7 Test evidence..."
$testScore = 0
if ($subResult.ok) {
if (@($subResult.data | Where-Object { $_.name -match "^test/|^tests/|^spec/" }).Count -gt 0) { $testScore++ }
if (@($subResult.data | Where-Object { $_.name -match "_test\.|\.test\.|_spec\." }).Count -gt 0) { $testScore++ }
}
if ($readmeText -match "test|测试|validate") { $testScore++ }
if ($testScore -ge 3) { $dTest.Score = 1.0 } elseif ($testScore -ge 1) { $dTest.Score = 0.5 } else { $dTest.Score = 0 }
$dTest.Detail = "测试证据得分: $testScore/3"
if ($names | Where-Object { $_ -match "^test/|^tests/|^spec/|^__tests__/" }) { $testScore++ }
if ($names | Where-Object { $_ -match "_test\.|\.test\.|_spec\.|\.spec\.|test_" }) { $testScore++ }
if ($readmeText -match "test|validate") { $testScore++ }
if ($testScore -ge 3) { $dTest.Score = 1.0; $dTest.Detail = "Test dir + files + instructions" }
elseif ($testScore -ge 1) { $dTest.Score = 0.5; $dTest.Detail = "Partial test evidence" }
else { $dTest.Score = 0; $dTest.Detail = "No test evidence" }
Log-Info " Test evidence: $testScore/3"
# 7. Data
Log-Step "7/7 数据可用性..."
Log-Step "7/7 Data availability..."
$dataScore = 0
if ($readmeText -match "dataset|data/|数据|zenodo|figshare|kaggle") { $dataScore++ }
if ($readmeText -match "10\.\d{4,}/[\w.\-/]+") { $dataScore++ }
if ($dataScore -ge 2) { $dData.Score = 1.0 } elseif ($dataScore -ge 1) { $dData.Score = 0.5 } else { $dData.Score = 0 }
$dData.Detail = "数据声明得分: $dataScore/2"
$dataEvidence = ""
if ($readmeText -match "dataset|data/|zenodo|figshare|kaggle|huggingface") { $dataScore++; $dataEvidence = "keyword found" }
if ($readmeText -match "https?://[^\s]+(?:zenodo|figshare|data\.|dataset)") { $dataScore++; $dataEvidence += ", data link found" }
if ($doiFound) { $dataScore++; $dataEvidence += ", DOI/article found" }
if ($dataScore -ge 2) { $dData.Score = 1.0; $dData.Detail = "Clear data statement: $dataEvidence" }
elseif ($dataScore -ge 1) { $dData.Score = 0.5; $dData.Detail = "Partial data statement: $dataEvidence" }
else { $dData.Score = 0; $dData.Detail = "No data availability statement" }
Log-Info " Data score: $dataScore/3"
# Total score
$weights = @(0.15, 0.15, 0.15, 0.15, 0.10, 0.10, 0.10, 0.10)
@ -117,15 +219,181 @@ for ($i = 0; $i -lt 8; $i++) { $totalScore += $scores[$i] * $weights[$i] }
$totalScore = [Math]::Round($totalScore * 100, 1)
$grade = if ($totalScore -ge 85) { "A" } elseif ($totalScore -ge 70) { "B" } elseif ($totalScore -ge 55) { "C" } elseif ($totalScore -ge 40) { "D" } else { "F" }
$gradeLabel = if ($grade -eq "A") { "Excellent - highly reproducible" } elseif ($grade -eq "B") { "Good - largely reproducible" } elseif ($grade -eq "C") { "Fair - partially reproducible" } elseif ($grade -eq "D") { "Poor - difficult to reproduce" } else { "Fail - barely reproducible" }
$gradeColor = if ($grade -eq "A") { "#2e7d32" } elseif ($grade -eq "B") { "#558b2f" } elseif ($grade -eq "C") { "#f57c00" } elseif ($grade -eq "D") { "#e65100" } else { "#c62828" }
Divider
Write-Host "====== 复现性评分卡 ======" -ForegroundColor White
Write-Host " 综合评分: $totalScore/100 — $grade"
$dims = @("许可证","无密钥/PII","README","依赖","构建","CI","测试","数据")
# Build recommendation strings
$recLicense = if ($dLicense.Score -ne 1.0) { "Add MIT/Apache-2.0/GPL-3.0 license file" } else { "-" }
$recSecret = if ($dNoSecret.Score -ne 1.0) { "Remove leaked secrets, use environment variables" } else { "-" }
$recReadme = if ($dReadme.Score -ne 1.0) { "Add purpose, install, usage, license, citation sections" } else { "-" }
$recDeps = if ($dDeps.Score -ne 1.0) { "Add package.json/go.mod/requirements.txt etc." } else { "-" }
$recBuild = if ($dBuild.Score -ne 1.0) { "Add Makefile/Dockerfile + build steps in README" } else { "-" }
$recCI = if ($dCI.Score -ne 1.0) { "Configure GitLink CI or GitHub Actions" } else { "-" }
$recTest = if ($dTest.Score -ne 1.0) { "Add unit/integration tests, document test commands" } else { "-" }
$recData = if ($dData.Score -ne 1.0) { "Document dataset sources, provide Zenodo/Figshare link" } else { "-" }
# Icon helpers
function ScoreIcon($s) {
if ($s -eq 1.0) { return "&#9989;" }
elseif ($s -eq 0.5) { return "&#9888;&#65039;" }
else { return "&#10060;" }
}
function ScorePercent($s) { [Math]::Round($s * 100) }
# ===== Generate HTML Report =====
Log-Step "Generating HTML scorecard..."
$dims = @("License","No Secrets/PII","README","Dependencies","Build","CI","Tests","Data")
$dets = @($dLicense, $dNoSecret, $dReadme, $dDeps, $dBuild, $dCI, $dTest, $dData)
$recs = @($recLicense, $recSecret, $recReadme, $recDeps, $recBuild, $recCI, $recTest, $recData)
$pcts = @(0.15, 0.15, 0.15, 0.15, 0.10, 0.10, 0.10, 0.10)
# Build dimension table rows
$dimRows = ""
for ($i = 0; $i -lt 8; $i++) {
$icon = ScoreIcon $scores[$i]
$pct = ScorePercent $scores[$i]
$suggestion = $recs[$i]
$detail = $dets[$i].Detail
$name = $dims[$i]
$dimRows += @"
<tr>
<td>$name</td>
<td>$icon</td>
<td>$detail</td>
<td>$suggestion</td>
</tr>
"@
}
$htmlContent = @"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$Owner/$Repo &mdash;Reproducibility Scorecard</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #333; }
.header { background: linear-gradient(135deg, #1a237e 0%, #3949ab 100%); color: #fff; padding: 40px 30px; }
.header h1 { font-size: 26px; margin-bottom: 6px; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 24px; }
.panel { background: #fff; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.panel h2 { font-size: 18px; margin-bottom: 16px; color: #1a237e; border-bottom: 2px solid #3949ab; padding-bottom: 8px; }
.chart { width: 100%; height: 350px; }
.grade-circle { text-align: center; padding: 20px; }
.grade-letter { font-size: 72px; font-weight: 900; color: $gradeColor; }
.grade-score { font-size: 24px; color: #888; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
th { background: #f5f7fa; color: #555; }
.footer { text-align: center; padding: 24px; color: #999; font-size: 12px; }
@media (max-width: 768px) { .row { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="header">
<h1>$Owner/$Repo &mdash;Research Reproducibility Scorecard</h1>
<div style="opacity:0.8;font-size:14px;">$Today</div>
</div>
<div class="container">
<div class="row">
<div class="panel grade-circle">
<div class="grade-letter">$grade</div>
<div class="grade-score">$totalScore / 100</div>
<div style="margin-top:12px;color:#888;">$gradeLabel</div>
</div>
<div class="panel">
<h2>Radar Chart</h2>
<div id="radarChart" class="chart"></div>
</div>
<div class="panel">
<h2>Dimension Scores</h2>
<table>
<tr><th>Dimension</th><th>Score</th><th>Weight</th></tr>
<tr><td>License</td><td>$(ScorePercent $dLicense.Score)%</td><td>15%</td></tr>
<tr><td>No Secrets/PII</td><td>$(ScorePercent $dNoSecret.Score)%</td><td>15%</td></tr>
<tr><td>README</td><td>$(ScorePercent $dReadme.Score)%</td><td>15%</td></tr>
<tr><td>Dependencies</td><td>$(ScorePercent $dDeps.Score)%</td><td>15%</td></tr>
<tr><td>Build</td><td>$(ScorePercent $dBuild.Score)%</td><td>10%</td></tr>
<tr><td>CI</td><td>$(ScorePercent $dCI.Score)%</td><td>10%</td></tr>
<tr><td>Tests</td><td>$(ScorePercent $dTest.Score)%</td><td>10%</td></tr>
<tr><td>Data</td><td>$(ScorePercent $dData.Score)%</td><td>10%</td></tr>
</table>
</div>
</div>
<div class="panel">
<h2>Detailed Assessment &amp; Recommendations</h2>
<table>
<tr><th>Dimension</th><th>Rating</th><th>Evidence</th><th>Suggestion</th></tr>
$dimRows
</table>
</div>
</div>
<div class="footer">Generated by GitLink Research Assistant &mdash;$Today</div>
<script>
var radarChart = echarts.init(document.getElementById('radarChart'));
radarChart.setOption({
radar: {
indicator: [
{ name: 'License', max: 100 },
{ name: 'No Secrets', max: 100 },
{ name: 'README', max: 100 },
{ name: 'Deps', max: 100 },
{ name: 'Build', max: 100 },
{ name: 'CI', max: 100 },
{ name: 'Tests', max: 100 },
{ name: 'Data', max: 100 }
],
center: ['50%', '55%'],
radius: '70%'
},
series: [{
type: 'radar',
data: [{
value: [
$(ScorePercent $dLicense.Score),
$(ScorePercent $dNoSecret.Score),
$(ScorePercent $dReadme.Score),
$(ScorePercent $dDeps.Score),
$(ScorePercent $dBuild.Score),
$(ScorePercent $dCI.Score),
$(ScorePercent $dTest.Score),
$(ScorePercent $dData.Score)
],
name: 'Reproducibility',
areaStyle: { color: 'rgba(57,73,171,0.3)' },
lineStyle: { color: '#3949ab' }
}]
}]
});
</script>
</body>
</html>
"@
if (-not $DryRun) {
$htmlContent | Out-File -FilePath $OutputFile -Encoding UTF8
Log-Ok "HTML scorecard generated: $OutputFile"
} else {
Log-Warn "[DRY RUN] Would generate: $OutputFile"
}
# Console summary
Divider
Write-Host "====== Reproducibility Scorecard ======" -ForegroundColor White
Write-Host " Total score: $totalScore/100 &mdash;$grade ($gradeLabel)"
$dimNames = @("License","No Secrets/PII","README","Dependencies","Build","CI","Tests","Data")
for ($i = 0; $i -lt 8; $i++) {
$icon = if ($scores[$i] -eq 1.0) { "OK" } elseif ($scores[$i] -eq 0.5) { "~" } else { "!!" }
Write-Host " $icon $($dims[$i]) ($([Math]::Round($scores[$i]*100))%): $($dets[$i].Detail)"
Write-Host " $icon $($dimNames[$i]) ($(ScorePercent $scores[$i])%): $($dets[$i].Detail)"
}
Write-Host " Report: $OutputFile"
Divider
Log-Ok "检查完成"
Log-Ok "Check complete"

View File

@ -1,4 +1,4 @@
# GitLink 科研辅助 — 场景 5进度跟踪与预警 (PowerShell)
# GitLink Research - Scenario 5: Progress Tracking & Alerting (PowerShell)
param(
[string]$Owner, [string]$Repo, [string]$Org = "",
[int]$Weeks = 4, [string]$Output = "",
@ -6,7 +6,7 @@ param(
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\lib\common.psm1" -Force
Import-Module "$ScriptDir\..\lib\common.psm1" -Force -WarningAction SilentlyContinue
$ErrorActionPreference = "Continue"
Check-Auth
@ -15,56 +15,267 @@ else { $resolved = Resolve-OwnerRepo -Owner $Owner -Repo $Repo; $Owner = $resolv
$Today = Get-Date -Format "yyyy-MM-dd"
$OutputDir = Join-Path $ScriptDir "..\output"
if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null }
$OutputFile = if ($Output) { $Output } else { Join-Path $OutputDir "progress-weekly-${Owner}-${Today}.html" }
Log-Title "GitLink 科研辅助 — 进度跟踪与预警"
Log-Title "GitLink Research - Progress Tracking"
# 1. Issues
Log-Step "1/4 Issue 数据..."
Log-Step "1/5 Collecting Issue data..."
$openIssues = Invoke-GL @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "100")
$closedIssues = Invoke-GL @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "closed", "--limit", "100")
$totalOpen = if ($openIssues.ok) { @($openIssues.data.issues ?? $openIssues.data).Count } else { 0 }
$totalClosed = if ($closedIssues.ok) { @($closedIssues.data.issues ?? $closedIssues.data).Count } else { 0 }
$oiData = if ($openIssues.data.issues) { $openIssues.data.issues } else { $openIssues.data }
$totalOpen = if ($openIssues.ok) { @($oiData).Count } else { 0 }
$ciData = if ($closedIssues.data.issues) { $closedIssues.data.issues } else { $closedIssues.data }
$totalClosed = if ($closedIssues.ok) { @($ciData).Count } else { 0 }
Log-Info " Issues: $totalOpen open / $totalClosed closed"
# 2. PRs
Log-Step "2/4 PR 数据..."
Log-Step "2/5 Collecting PR data..."
$mergedPrs = Invoke-GL @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "merged", "--limit", "100")
$openPrs = Invoke-GL @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "50")
$totalMerged = if ($mergedPrs.ok) { @($mergedPrs.data.issues ?? $mergedPrs.data.pulls ?? $mergedPrs.data).Count } else { 0 }
$totalOpenPrs = if ($openPrs.ok) { @($openPrs.data.issues ?? $openPrs.data.pulls ?? $openPrs.data).Count } else { 0 }
$mData = if ($mergedPrs.data.issues) { $mergedPrs.data.issues } elseif ($mergedPrs.data.pulls) { $mergedPrs.data.pulls } else { $mergedPrs.data }
$totalMerged = if ($mergedPrs.ok) { @($mData).Count } else { 0 }
$opData = if ($openPrs.data.issues) { $openPrs.data.issues } elseif ($openPrs.data.pulls) { $openPrs.data.pulls } else { $openPrs.data }
$totalOpenPrs = if ($openPrs.ok) { @($opData).Count } else { 0 }
Log-Info " PRs: $totalOpenPrs open / $totalMerged merged"
# 3. Releases & CI
Log-Step "3/4 Release & CI..."
# 3. Releases
Log-Step "3/5 Collecting Release data..."
$releases = Invoke-GL @("release", "+list", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$releaseCount = if ($releases.ok) { @($releases.data).Count } else { 0 }
$lastReleaseDate = ""
if ($releases.ok -and $releaseCount -gt 0) {
$relData = if ($releases.data.releases) { $releases.data.releases } else { $releases.data }
if ($relData -is [array] -and $relData.Count -gt 0) {
$lastReleaseDate = if ($relData[0].created_at) { $relData[0].created_at } else { "" }
if ($lastReleaseDate.Length -ge 10) { $lastReleaseDate = $lastReleaseDate.Substring(0, 10) }
}
}
Log-Info " Releases: $releaseCount"
# 4. CI
Log-Step "4/5 Collecting CI data..."
$ci = Invoke-GL @("ci", "+builds", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$ciTotal = if ($ci.ok) { @($ci.data).Count } else { 0 }
$ciOk = 0
if ($ci.ok) {
foreach ($b in @($ci.data)) {
$status = if ($b.status) { $b.status } else { "" }
if ($status -eq "success" -or $status -eq "completed") { $ciOk++ }
}
}
Log-Info " CI: $ciOk/$ciTotal passed"
# 4. Health score
Log-Step "4/4 健康评分..."
$iv = [Math]::Min($totalClosed / ($Weeks * 7), 1.0)
$pr = if (($totalMerged + $totalOpenPrs) -gt 0) { $totalMerged / ($totalMerged + $totalOpenPrs) } else { 0 }
# 5. Health score
Log-Step "5/5 Calculating health score and anomaly detection..."
$prevClosed = [Math]::Floor($totalClosed / 2)
# Issue velocity (normalized)
$iv = [Math]::Min($totalClosed / ($Weeks * 7.0), 1.0)
# PR merge rate
$prMR = if (($totalMerged + $totalOpenPrs) -gt 0) { $totalMerged / ($totalMerged + $totalOpenPrs) } else { 0 }
# Release cadence
$rc = if ($releaseCount -ge 3) { 1.0 } elseif ($releaseCount -ge 1) { 0.5 } else { 0.2 }
$health = [Math]::Round(($iv * 0.30 + $pr * 0.25 + $rc * 0.25 + [Math]::Min(($totalClosed * 0.01), 1.0) * 0.10 + 0.5 * 0.10) * 100, 1)
# CI pass rate
$ciScore = if ($ciTotal -gt 0) { $ciOk / $ciTotal } else { 0 }
# Activity trend
$diff = if ($prevClosed -gt 0) { ($totalClosed - $prevClosed) / $prevClosed } else { 0 }
$trend = [Math]::Min([Math]::Max($diff + 0.5, 0.0), 1.0)
$health = [Math]::Round(($iv * 0.30 + $prMR * 0.25 + $rc * 0.25 + $ciScore * 0.10 + $trend * 0.10) * 100, 1)
# Anomalies
$anomalies = @()
if ($totalOpen -gt 20) { $anomalies += "[Warning] 开放 Issue 数量($totalOpen)偏高" }
if ($totalOpenPrs -gt 5) { $anomalies += "[Warning] $totalOpenPrs 个开放 PR 积压" }
if ($releaseCount -eq 0) { $anomalies += "[Info] 无 Release 记录" }
if ($totalOpen -gt $totalClosed) { $anomalies += "[Warning] Issue 积压(开放 > 关闭)" }
if ($totalOpen -gt 20) { $anomalies += @{type="stalled_issue"; severity="Warning"; detail="Open issues ($totalOpen) high, may be stalled"} }
if ($totalOpenPrs -gt 5) { $anomalies += @{type="pr_bottleneck"; severity="Warning"; detail="$totalOpenPrs open PRs backlogged"} }
if ($releaseCount -eq 0) { $anomalies += @{type="no_release"; severity="Info"; detail="No release record"} }
if ($prevClosed -gt 0 -and $totalClosed -lt $prevClosed * 0.5) { $anomalies += @{type="activity_decline"; severity="Warning"; detail="Activity dropped >50%"} }
if ($ciTotal -gt 0 -and $ciOk / $ciTotal -lt 0.5) { $anomalies += @{type="ci_failure"; severity="Warning"; detail="CI pass rate <50%"} }
$anomalyCount = $anomalies.Count
$label = if ($health -ge 80) { "健康" } elseif ($health -ge 60) { "正常" } elseif ($health -ge 40) { "需关注" } else { "风险" }
$healthLabel = if ($health -ge 80) { "Healthy" } elseif ($health -ge 60) { "Normal" } elseif ($health -ge 40) { "Needs Attention" } else { "At Risk" }
$healthColor = if ($health -ge 80) { "#2e7d32" } elseif ($health -ge 60) { "#558b2f" } elseif ($health -ge 40) { "#f57c00" } else { "#c62828" }
Log-Ok "Health score: $health/100 ($healthLabel)"
if ($anomalyCount -gt 0) { Log-Warn "Detected $anomalyCount anomalies" }
# ===== Generate HTML Report =====
Log-Step "Generating weekly HTML report..."
# Build anomaly table rows
$anomalyRows = ""
if ($anomalyCount -gt 0) {
foreach ($a in $anomalies) {
$sevClass = if ($a.severity -eq "Critical") { "sev-Critical" } elseif ($a.severity -eq "Warning") { "sev-Warning" } else { "sev-Info" }
$anomalyRows += "<tr><td>$($a.type)</td><td class=`"$sevClass`">$($a.severity)</td><td>$($a.detail)</td></tr>`n"
}
}
$issueTrend = if ($totalClosed -gt $totalOpen) { "<span class=`"ok`">Improving</span>" } else { "<span class=`"warn`">Backlog growing</span>" }
$issueAdvice = if ($totalOpen -gt $totalClosed) { "Schedule an Issue cleanup day" } else { "-" }
$prTrend = if ($totalOpenPrs -le 5) { "<span class=`"ok`">Normal</span>" } else { "<span class=`"warn`">Backlogged</span>" }
$prAdvice = if ($totalOpenPrs -gt 5) { "Increase code review frequency" } else { "-" }
$releaseTrend = if ($releaseCount -ge 3) { "<span class=`"ok`">Active</span>" } else { "<span class=`"warn`">Inactive</span>" }
$releaseAdvice = if ($releaseCount -eq 0) { "Recommend publishing v0.1.0" } else { "-" }
$ciPassRate = if ($ciTotal -gt 0) { [Math]::Round($ciOk / $ciTotal * 100) } else { 0 }
$ciTrend = if ($ciTotal -gt 0 -and $ciPassRate -ge 80) { "<span class=`"ok`">Stable</span>" } else { "<span class=`"warn`">Needs improvement</span>" }
$ciAdvice = if ($ciTotal -eq 0) { "Configure GitLink CI" } else { "-" }
$lastRelDisplay = if ($lastReleaseDate) { $lastReleaseDate } else { "None" }
$lastRelTrend = if ($lastReleaseDate) { "<span class=`"ok`">Released</span>" } else { "<span class=`"warn`">No record</span>" }
$htmlContent = @"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$Owner/$Repo &mdash;Progress Weekly Report $Today</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #333; }
.header { background: linear-gradient(135deg, #1a237e 0%, #3949ab 100%); color: #fff; padding: 40px 30px; }
.header h1 { font-size: 26px; margin-bottom: 6px; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 24px; }
.card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.08); text-align: center; }
.card.health { background: $healthColor; color: #fff; }
.card .value { font-size: 32px; font-weight: 700; }
.card .label { font-size: 12px; opacity: 0.8; margin-top: 4px; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
.panel { background: #fff; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.panel h2 { font-size: 18px; margin-bottom: 16px; color: #1a237e; border-bottom: 2px solid #3949ab; padding-bottom: 8px; }
.chart { width: 100%; height: 350px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
th { background: #f5f7fa; color: #555; font-weight: 600; }
.sev-Critical { color: #c62828; font-weight: 700; }
.sev-Warning { color: #e65100; font-weight: 600; }
.sev-Info { color: #1565c0; }
.ok { color: #2e7d32; font-weight: 600; }
.warn { color: #e65100; font-weight: 600; }
.footer { text-align: center; padding: 24px; color: #999; font-size: 12px; }
@media (max-width: 768px) { .row { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="header">
<h1>$Owner/$Repo &mdash;Research Progress Weekly</h1>
<div style="opacity:0.8;font-size:14px;">$Weeks week(s) review &mdash; $Today</div>
</div>
<div class="container">
<div class="cards">
<div class="card health">
<div class="value">$health</div>
<div class="label">Health Score / 100 &mdash;$healthLabel</div>
</div>
<div class="card"><div class="value">$totalOpen</div><div class="label">Open Issues</div></div>
<div class="card"><div class="value">$totalOpenPrs</div><div class="label">Open PRs</div></div>
<div class="card"><div class="value">$totalMerged</div><div class="label">Merged PRs</div></div>
<div class="card"><div class="value">$releaseCount</div><div class="label">Releases</div></div>
<div class="card"><div class="value">$anomalyCount</div><div class="label">Anomalies</div></div>
</div>
<div class="row">
<div class="panel">
<h2>Issue / PR Overview</h2>
<div id="overviewChart" class="chart"></div>
</div>
<div class="panel">
<h2>Anomaly Alerts</h2>
"@
if ($anomalyCount -eq 0) {
$htmlContent += "<div style=`"text-align:center;padding:40px;color:#2e7d32;`"><b>No anomalies detected, project is healthy</b></div>`n"
} else {
$htmlContent += "<table><tr><th>Type</th><th>Severity</th><th>Detail</th></tr>$anomalyRows</table>`n"
}
$htmlContent += @"
</div>
</div>
<div class="panel">
<h2>Progress Indicators</h2>
<table>
<tr><th>Indicator</th><th>Value</th><th>Trend</th><th>Suggestion</th></tr>
<tr>
<td>Issue Velocity</td>
<td>$totalOpen open / $totalClosed closed</td>
<td>$issueTrend</td>
<td>$issueAdvice</td>
</tr>
<tr>
<td>PR Merge Rate</td>
<td>$([Math]::Round($prMR * 100))%</td>
<td>$prTrend</td>
<td>$prAdvice</td>
</tr>
<tr>
<td>Release Cadence</td>
<td>$releaseCount release(s)</td>
<td>$releaseTrend</td>
<td>$releaseAdvice</td>
</tr>
<tr>
<td>CI Stability</td>
<td>${ciPassRate}% ($ciOk/$ciTotal)</td>
<td>$ciTrend</td>
<td>$ciAdvice</td>
</tr>
<tr>
<td>Latest Release</td>
<td>$lastRelDisplay</td>
<td>$lastRelTrend</td>
<td>-</td>
</tr>
</table>
</div>
</div>
<div class="footer">Generated by GitLink Research Assistant &mdash;$Today</div>
<script>
var overviewChart = echarts.init(document.getElementById('overviewChart'));
overviewChart.setOption({
tooltip: { trigger: 'axis' },
legend: { data: ['Open', 'Completed'] },
xAxis: { type: 'category', data: ['Issues', 'Pull Requests', 'Releases', 'CI Builds'] },
yAxis: { type: 'value' },
series: [
{ name: 'Open', type: 'bar', data: [$totalOpen, $totalOpenPrs, 0, 0], itemStyle: { color: '#fac858' } },
{ name: 'Completed', type: 'bar', data: [$totalClosed, $totalMerged, $releaseCount, $ciTotal], itemStyle: { color: '#91cc75' } }
]
});
</script>
</body>
</html>
"@
if (-not $DryRun) {
$htmlContent | Out-File -FilePath $OutputFile -Encoding UTF8
Log-Ok "Weekly report generated: $OutputFile"
} else {
Log-Warn "[DRY RUN] Would generate: $OutputFile"
}
# Console summary
Divider
Write-Host "====== 进度周报摘要 ======" -ForegroundColor White
Write-Host " 仓库: $Owner/$Repo"
Write-Host " 健康评分: $health/100 ($label)"
Write-Host " Issues: $totalOpen 开放 / $totalClosed 关闭"
Write-Host " PRs: $totalOpenPrs 开放 / $totalMerged 合并"
Write-Host " Releases: $releaseCount | CI: $ciTotal"
if ($anomalies.Count -gt 0) {
Write-Host " 异常信号 ($($anomalies.Count)):" -ForegroundColor Yellow
foreach ($a in $anomalies) { Write-Host " $a" }
} else { Write-Host " 未检测到异常" -ForegroundColor Green }
Write-Host "====== Weekly Progress Summary ======" -ForegroundColor White
Write-Host " Repo: $Owner/$Repo"
Write-Host " Health: $health/100 ($healthLabel)"
Write-Host " Issues: $totalOpen open / $totalClosed closed"
Write-Host " PRs: $totalOpenPrs open / $totalMerged merged"
Write-Host " Releases: $releaseCount | CI: $ciOk/$ciTotal passed"
if ($anomalyCount -gt 0) {
Write-Host " Anomalies ($anomalyCount):" -ForegroundColor Yellow
foreach ($a in $anomalies) { Write-Host " [$($a.severity)] $($a.detail)" }
} else { Write-Host " No anomalies detected" -ForegroundColor Green }
Write-Host " Report: $OutputFile"
Divider
Log-Ok "分析完成"
Log-Ok "Analysis complete"

View File

@ -1,12 +1,12 @@
# GitLink 科研辅助 — 场景 6一键生成论文引用格式 (PowerShell)
# GitLink Research - Scenario 6: Citation Format Generator (PowerShell)
param(
[string]$Owner, [string]$Repo, [string]$Format = "all",
[string]$Output = "", [switch]$DryRun
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\lib\common.psm1" -Force
Import-Module "$ScriptDir\lib\research-common.psm1" -Force
Import-Module "$ScriptDir\..\lib\common.psm1" -Force -WarningAction SilentlyContinue
Import-Module "$ScriptDir\..\lib\research-common.psm1" -Force -WarningAction SilentlyContinue
$ErrorActionPreference = "Stop"
Check-Auth
@ -14,31 +14,36 @@ $resolved = Resolve-OwnerRepo -Owner $Owner -Repo $Repo
$Owner = $resolved.Owner; $Repo = $resolved.Repo
$Today = Get-DateToday
Log-Title "GitLink 科研辅助 — 论文引用格式生成"
Log-Title "GitLink Research - Citation Generator"
# 1. Fetch repo metadata
Log-Step "获取仓库元数据..."
Log-Step "Fetching repo metadata..."
$repoJson = Invoke-GLCheck @("repo", "+info", "--owner", $Owner, "--repo", $Repo)
$repoName = $repoJson.data.name ?? $repoJson.data.full_name ?? "$Owner/$Repo"
$repoDesc = $repoJson.data.description ?? ""
$updatedAt = $repoJson.data.updated_at ?? ""
$repoName = if ($repoJson.data.name) { $repoJson.data.name } elseif ($repoJson.data.full_name) { $repoJson.data.full_name } else { "$Owner/$Repo" }
$repoDesc = if ($repoJson.data.description) { $repoJson.data.description } else { "" }
$updatedAt = if ($repoJson.data.updated_at) { $repoJson.data.updated_at } else { "" }
# DOI detection
$doi = ""
if ($repoDesc -match '10\.\d{4,}/[\w.\-/]+') { $doi = $Matches[0] }
if ($doi) { Log-Info " DOI detected: $doi" }
# 2. Get latest release
Log-Step "获取最新版本..."
Log-Step "Fetching latest version..."
$releaseJson = Invoke-GL @("release", "+list", "--owner", $Owner, "--repo", $Repo, "--limit", "1")
$version = if ($releaseJson.ok) { $releaseJson.data[0].tag_name ?? "v0.0.0-dev" } else { "v0.0.0-dev" }
$releaseDate = if ($releaseJson.ok) { $releaseJson.data[0].created_at ?? $updatedAt } else { $updatedAt }
$version = if ($releaseJson.ok -and $releaseJson.data[0].tag_name) { $releaseJson.data[0].tag_name } else { "v0.0.0-dev" }
$releaseDate = if ($releaseJson.ok -and $releaseJson.data[0].created_at) { $releaseJson.data[0].created_at } else { $updatedAt }
if ($releaseDate.Length -ge 10) { $releaseDate = $releaseDate.Substring(0, 10) }
$releaseYear = if ($releaseDate.Length -ge 4) { $releaseDate.Substring(0, 4) } else { (Get-Date).Year }
# 3. Get members
Log-Step "获取贡献者列表..."
Log-Step "Fetching contributors..."
$membersJson = Invoke-GL @("repo", "+members", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$authorNames = @()
if ($membersJson.ok) {
$data = if ($membersJson.data.members) { $membersJson.data.members } else { $membersJson.data }
if ($data -is [array]) {
$authorNames = $data | ForEach-Object { $_.name ?? $_.login ?? "" } | Where-Object { $_ }
$authorNames = $data | ForEach-Object { if ($_.name) { $_.name } elseif ($_.login) { $_.login } else { "" } } | Where-Object { $_ }
}
}
if ($authorNames.Count -eq 0) { $authorNames = @($Owner) }
@ -59,48 +64,54 @@ if ($authorNames.Count -gt 1) { $mlaAuthors += ", et al." }
# GB/T 7714
$gbAuthors = ($authorNames | Select-Object -First 3) -join ", "
if ($authorNames.Count -gt 3) { $gbAuthors += "" }
if ($authorNames.Count -gt 3) { $gbAuthors += "et al." }
# Short name for BibTeX key
$shortName = $Repo -replace '[^a-zA-Z0-9_-]', '_'
# Generate output
$output = ""
$citationBody = ""
if ($Format -eq "bibtex" -or $Format -eq "all") {
$output += "@software{$shortName,`n author = {$bibtexAuthors},`n title = {$repoName},`n version = {$version},`n date = {$releaseDate},`n publisher = {GitLink},`n url = {$repoUrl},`n note = {$repoDesc}`n}`n`n"
$citationBody += "@software{$shortName,`n author = {$bibtexAuthors},`n title = {$repoName},`n version = {$version},`n date = {$releaseDate},`n publisher = {GitLink},`n url = {$repoUrl}"
if ($doi) { $citationBody += ",`n doi = {$doi}" }
$citationBody += ",`n note = {$repoDesc}`n}`n`n"
}
if ($Format -eq "apa" -or $Format -eq "all") {
$output += "$apaAuthors ($releaseYear). $repoName (Version $version) [Computer software].`n GitLink. $repoUrl`n`n"
$citationBody += "$apaAuthors ($releaseYear). $repoName (Version $version) [Computer software].`n GitLink. $repoUrl`n`n"
}
if ($Format -eq "mla" -or $Format -eq "all") {
$output += "$mlaAuthors. $repoName. Version $version, GitLink,`n $releaseDate, $repoUrl.`n`n"
$citationBody += "$mlaAuthors. $repoName. Version $version, GitLink,`n $releaseDate, $repoUrl.`n`n"
}
if ($Format -eq "gbt7714" -or $Format -eq "all") {
$output += "[1] $gbAuthors. $repoName[CP/OL]. $version. GitLink,`n $releaseDate[$Today]. $repoUrl.`n`n"
$citationBody += "[1] $gbAuthors. $repoName[CP/OL]. $version. GitLink,`n $releaseDate[$Today]. $repoUrl.`n`n"
}
if ($Format -eq "cff" -or $Format -eq "all") {
$output += "cff-version: 1.2.0`nmessage: `"If you use this software, please cite it as below.`"`nauthors:`n"
$cffDate = if ($releaseDate.Length -ge 10) { $releaseDate.Substring(0, 10) } else { $releaseDate }
$citationBody += "cff-version: 1.2.0`nmessage: `"If you use this software, please cite it as below.`"`nauthors:`n"
foreach ($a in $authorNames) {
if (-not $a) { continue }
$parts = $a -split '\s+'
$output += " - family-names: $($parts[-1])`n given-names: $($parts[0])`n"
$citationBody += " - family-names: $($parts[-1])`n given-names: $($parts[0])`n"
}
$output += "title: `"$repoName`"`nversion: $version`ndate-released: $($releaseDate.Substring(0, 10))`nurl: `"$repoUrl`"`n"
$citationBody += "title: `"$repoName`"`nversion: $version`ndate-released: $cffDate`nurl: `"$repoUrl`"`nrepository-code: `"$repoUrl.git`"`n"
if ($doi) { $citationBody += "doi: $doi`n" }
}
Divider
Write-Host $output
Write-Host $citationBody
Divider
if ($Output) {
if (-not $DryRun) { $output | Out-File -FilePath $Output -Encoding UTF8; Log-Ok "已写入: $Output" }
if (-not $DryRun) { $citationBody | Out-File -FilePath $Output -Encoding UTF8; Log-Ok "Written to: $Output" }
}
Log-Info "仓库: $Owner/$Repo"
Log-Info "版本: $version | 发布日期: $releaseDate | 贡献者: $($authorNames.Count)"
Log-Ok "引用格式生成完成 ($Format)"
Log-Info "Repo: $Owner/$Repo"
Log-Info "Version: $version | Released: $releaseDate | Contributors: $($authorNames.Count)"
if ($doi) { Log-Info "DOI: $doi" }
Log-Info "Format: $Format"
Log-Ok "Citation generation complete"