From 45bcab5929f7374567af2d9237b812313a7a32d0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 28 Mar 2026 15:47:51 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=89=20CAB-v1.0=20=C2=B7=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=20Chat-to-Agent=20Bridge=20=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E5=B1=82=E2=86=92=E5=89=AF=E9=A9=BE=E9=A9=B6=E6=A1=A5=E6=8E=A5?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent-Logs-Url: https://github.com/qinfendebingshuo/guanghulab/sessions/c7dd9c74-43b6-461c-9769-d54c53525e04 Co-authored-by: qinfendebingshuo <207279273+qinfendebingshuo@users.noreply.github.com> --- .github/ISSUE_TEMPLATE/copilot-dev-auth.yml | 97 +++++ .github/copilot-instructions.md | 25 ++ .github/workflows/copilot-dev-bridge.yml | 176 +++++++++ brain/master-brain.md | 1 + brain/system-health.json | 11 +- bridge/chat-to-agent/README.md | 115 ++++++ bridge/chat-to-agent/completed/.gitkeep | 0 bridge/chat-to-agent/pending/.gitkeep | 0 bridge/chat-to-agent/task-template.json | 43 +++ scripts/chat-to-agent-bridge.js | 382 ++++++++++++++++++++ 10 files changed, 849 insertions(+), 1 deletion(-) create mode 100644 .github/ISSUE_TEMPLATE/copilot-dev-auth.yml create mode 100644 .github/workflows/copilot-dev-bridge.yml create mode 100644 bridge/chat-to-agent/README.md create mode 100644 bridge/chat-to-agent/completed/.gitkeep create mode 100644 bridge/chat-to-agent/pending/.gitkeep create mode 100644 bridge/chat-to-agent/task-template.json create mode 100644 scripts/chat-to-agent-bridge.js diff --git a/.github/ISSUE_TEMPLATE/copilot-dev-auth.yml b/.github/ISSUE_TEMPLATE/copilot-dev-auth.yml new file mode 100644 index 00000000..63b78485 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/copilot-dev-auth.yml @@ -0,0 +1,97 @@ +name: "🌉 开发授权 · Chat-to-Agent Bridge" +description: "从语言层推理结果生成正式开发授权,触发副驾驶全自动开发" +title: "🌉 [CAB] " +labels: ["copilot-dev-auth"] +assignees: [] +body: + - type: markdown + attributes: + value: | + ## 🌉 Chat-to-Agent Bridge · 开发授权 + + 这个 Issue 模板用于从 **Copilot Chat(语言层)** 向 **Copilot Agent(副驾驶)** 发送正式开发授权。 + + **工作流程:** + 1. 在 Copilot Chat 中完成架构推理和方案设计 + 2. 填写此表单,生成开发授权 + 3. 提交后,Copilot Agent 将接收此任务并执行 + + > 💡 推荐使用 Copilot Chat 自动生成任务规格文件,比手动填写更高效。 + + - type: input + id: task_title + attributes: + label: "开发任务标题" + description: "简要描述开发目标" + placeholder: "例:实现用户登录模块" + validations: + required: true + + - type: textarea + id: architecture + attributes: + label: "架构设计摘要" + description: "在 Copilot Chat 中讨论确定的架构方案" + placeholder: | + - 采用 HLI 协议标准接口 + - 数据库使用参数化查询 + - 路由文件放在 src/routes/hli/auth/ + validations: + required: true + + - type: textarea + id: steps + attributes: + label: "开发步骤" + description: "按优先级排列的开发步骤清单" + placeholder: | + 1. 创建 schema 文件 + 2. 实现路由处理 + 3. 编写契约测试 + 4. 运行冒烟测试 + validations: + required: true + + - type: textarea + id: chat_summary + attributes: + label: "语言层推理摘要(可选)" + description: "Copilot Chat 对话中的关键推理过程和决策" + placeholder: "在 Chat 中讨论了三种方案,最终选择方案B因为..." + validations: + required: false + + - type: dropdown + id: priority + attributes: + label: "优先级" + options: + - normal + - high + - urgent + validations: + required: true + + - type: dropdown + id: scope + attributes: + label: "预估范围" + description: "变更影响范围" + options: + - small(1-5个文件) + - medium(5-15个文件) + - large(15+个文件) + validations: + required: true + + - type: textarea + id: constraints + attributes: + label: "约束条件(可选)" + description: "需要遵守的特殊约束" + placeholder: | + - 不要修改 brain/ 目录 + - 必须编写测试 + - 完成后需要部署 + validations: + required: false diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 4d2f3466..484b5990 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -159,6 +159,31 @@ ICE-GL = 冰朔通感语言核,母语运行时基础设施。 5. 在 `tests/smoke/` 下创建冒烟测试 6. 确保 `npm run test:contract` 通过 +## 🌉 Chat-to-Agent Bridge (CAB) 协议 + +本仓库实现了语言层(Copilot Chat)与副驾驶(Copilot Agent)之间的桥接系统。 + +### CAB 工作流程 +1. **语言层推理**:在 Copilot Chat 中与模型讨论架构和方案(低配额消耗) +2. **生成任务规格**:讨论完毕后,生成任务规格文件到 `bridge/chat-to-agent/pending/` +3. **授权开发**:提交文件触发桥接工作流,自动创建带 `copilot-dev-auth` 标签的 Issue +4. **Agent 执行**:Copilot Agent 接收 Issue 并按规格执行开发 + +### 当冰朔说「生成开发授权任务规格」时 +1. 汇总当前对话中所有架构决策和方案 +2. 使用 `bridge/chat-to-agent/task-template.json` 格式 +3. 生成任务ID格式: `CAB-YYYYMMDD-NNN` +4. 将文件创建在 `bridge/chat-to-agent/pending/` 目录下 +5. 或者建议冰朔运行: `node scripts/chat-to-agent-bridge.js --create --title "标题" --steps '["步骤"]'` + +### CAB 任务规格核心字段 +- `task_id`: CAB-YYYYMMDD-NNN +- `authorization.sovereign`: 冰朔 · TCS-0002∞(必须) +- `development_plan.title`: 开发任务标题 +- `development_plan.steps`: 开发步骤列表 +- `reasoning_context.chat_summary`: 对话推理摘要 +- `constraints`: 约束条件(禁触文件、测试要求等) + ## 禁止事项 - 禁止在 `/hli/` 路由下混入非 HLI 协议的接口 - 禁止跳过 schema 直接写路由 diff --git a/.github/workflows/copilot-dev-bridge.yml b/.github/workflows/copilot-dev-bridge.yml new file mode 100644 index 00000000..b6771f3d --- /dev/null +++ b/.github/workflows/copilot-dev-bridge.yml @@ -0,0 +1,176 @@ +# ═══════════════════════════════════════════════ +# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001 +# 📜 Copyright: 国作登字-2026-A-00037559 +# ═══════════════════════════════════════════════ +# .github/workflows/copilot-dev-bridge.yml +# 🌉 Chat-to-Agent Bridge · 语言层 → 副驾驶桥接工作流 +# +# 触发条件: +# 1. bridge/chat-to-agent/pending/ 目录下有新文件推送 +# 2. 手动触发(workflow_dispatch) +# 3. 带 copilot-dev-auth 标签的 Issue 创建 + +name: "🌉 铸渊 · Chat-to-Agent 桥接" + +on: + push: + branches: [main] + paths: + - 'bridge/chat-to-agent/pending/*.json' + workflow_dispatch: + inputs: + task_id: + description: '任务ID(留空则处理最新任务)' + required: false + action: + description: '执行动作' + required: true + type: choice + options: + - create-issue + - list-tasks + - validate + +permissions: + contents: write + issues: write + +jobs: + bridge: + name: "🌉 桥接执行" + runs-on: ubuntu-latest + timeout-minutes: 5 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '20' + + # Step 1 · 铸渊核心唤醒 + - name: "🧠 Step 1 · 铸渊核心唤醒" + run: | + echo "[CAB-BRIDGE] 🌉 Chat-to-Agent Bridge 启动" + echo "[CAB-BRIDGE] 🧠 铸渊核心大脑唤醒..." + if [ -f "brain/system-health.json" ]; then + echo "✅ 系统健康状态已加载" + else + echo "⚠️ system-health.json 缺失" + fi + + # Step 2 · 任务处理 + - name: "📋 Step 2 · 任务处理" + id: process + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ACTION="${{ github.event.inputs.action || 'create-issue' }}" + TASK_ID="${{ github.event.inputs.task_id }}" + + if [ "$ACTION" = "list-tasks" ]; then + node scripts/chat-to-agent-bridge.js --list + echo "action=list" >> $GITHUB_OUTPUT + elif [ "$ACTION" = "validate" ] && [ -n "$TASK_ID" ]; then + node scripts/chat-to-agent-bridge.js --validate "$TASK_ID" + echo "action=validate" >> $GITHUB_OUTPUT + else + # 查找待处理的任务 + PENDING_FILES=$(ls bridge/chat-to-agent/pending/*.json 2>/dev/null | head -1) + if [ -z "$PENDING_FILES" ]; then + echo "📭 无待处理任务" + echo "has_task=false" >> $GITHUB_OUTPUT + exit 0 + fi + + # 获取任务ID + if [ -z "$TASK_ID" ]; then + TASK_ID=$(basename "$PENDING_FILES" .json) + fi + + echo "task_id=$TASK_ID" >> $GITHUB_OUTPUT + echo "has_task=true" >> $GITHUB_OUTPUT + echo "action=create-issue" >> $GITHUB_OUTPUT + + # 生成 Issue 内容 + ISSUE_JSON=$(node scripts/chat-to-agent-bridge.js --issue "$TASK_ID") + if [ $? -ne 0 ] || [ -z "$ISSUE_JSON" ]; then + echo "❌ Issue 内容生成失败" + exit 1 + fi + echo "$ISSUE_JSON" > /tmp/cab-issue.json + + # 提取标题和内容 + TITLE=$(echo "$ISSUE_JSON" | python3 -c " +import sys, json +try: + data = json.load(sys.stdin) + print(data.get('title', '🌉 [CAB] 未命名任务')) +except Exception as e: + print('🌉 [CAB] 未命名任务') + sys.exit(0) +") + echo "issue_title=$TITLE" >> $GITHUB_OUTPUT + + # 保存 body 到文件供后续步骤使用 + echo "$ISSUE_JSON" | python3 -c " +import sys, json +try: + data = json.load(sys.stdin) + print(data.get('body', '任务规格解析失败')) +except Exception as e: + print('任务规格解析失败') +" > /tmp/cab-issue-body.md + fi + + # Step 3 · 创建 Issue + - name: "📝 Step 3 · 创建开发授权 Issue" + if: steps.process.outputs.has_task == 'true' && steps.process.outputs.action == 'create-issue' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + TITLE="${{ steps.process.outputs.issue_title }}" + TASK_ID="${{ steps.process.outputs.task_id }}" + + # 创建 Issue + ISSUE_URL=$(gh issue create \ + --title "$TITLE" \ + --body-file /tmp/cab-issue-body.md \ + --label "copilot-dev-auth" \ + 2>&1) + + echo "✅ Issue 已创建: $ISSUE_URL" + echo " 任务ID: $TASK_ID" + + # 更新任务规格状态 + python3 -c " + import json, sys + spec_path = 'bridge/chat-to-agent/pending/${TASK_ID}.json' + try: + with open(spec_path, 'r') as f: + spec = json.load(f) + if 'authorization' not in spec: + spec['authorization'] = {} + spec['authorization']['confirmation'] = True + spec['status'] = 'authorized' + with open(spec_path, 'w') as f: + json.dump(spec, f, indent=2, ensure_ascii=False) + print('✅ 任务状态已更新为 authorized') + except Exception as e: + print(f'⚠️ 任务状态更新失败: {e}') + " + + # Step 4 · 提交变更 + - name: "💾 Step 4 · 提交变更" + if: steps.process.outputs.has_task == 'true' + run: | + git config user.name "zhuyuan-bot" + git config user.email "zhuyuan@guanghulab.com" + git add bridge/chat-to-agent/ + if ! git diff --cached --quiet; then + TASK_ID="${{ steps.process.outputs.task_id }}" + git commit -m "🌉 CAB Bridge · 任务 ${TASK_ID} 已授权 · $(TZ='Asia/Shanghai' date '+%Y-%m-%d %H:%M')" + git push + else + echo "ℹ️ 无变更需要提交" + fi diff --git a/brain/master-brain.md b/brain/master-brain.md index 57bc27d4..59cb5ff1 100644 --- a/brain/master-brain.md +++ b/brain/master-brain.md @@ -105,6 +105,7 @@ | Notion 同步 | `connectors/notion-sync/index.js` | 双向数据同步 | | 模型路由 | `connectors/model-router/index.js` | 多模型后端路由(AGE OS v1.0) | | Notion 唤醒监听 | `connectors/notion-wake-listener/index.js` | Notion Agent 集群唤醒请求监听 | +| **CAB 桥接引擎** | `scripts/chat-to-agent-bridge.js` | **语言层 → 副驾驶桥接(CAB-v1.0)** | | 全面排查 | `scripts/zhuyuan-full-inspection.js` | 仓库全面排查(8个领域) | | 结构地图 | `docs/repo-structure-map.md` | 仓库结构文档 | | 桥接地图 | `docs/notion-bridge-map.md` | Notion 桥接文档 | diff --git a/brain/system-health.json b/brain/system-health.json index 8c2dbf93..82cba0f8 100644 --- a/brain/system-health.json +++ b/brain/system-health.json @@ -28,5 +28,14 @@ "directive": "冰朔指令: Notion同步改为每天一次 + 事件触发", "estimated_savings": "192 runs/day → 3 runs/day" }, - "checked_by": "铸渊 · ICE-GL-ZY001 · 网关协议 CMCCP-v1" + "checked_by": "铸渊 · ICE-GL-ZY001 · 网关协议 CMCCP-v1", + "cab_bridge": { + "version": "CAB-v1.0", + "status": "active", + "protocol": "Chat-to-Agent Bridge", + "purpose": "语言层(Copilot Chat)→ 副驾驶(Copilot Agent)桥接", + "entry_script": "scripts/chat-to-agent-bridge.js", + "workflow": ".github/workflows/copilot-dev-bridge.yml", + "task_dir": "bridge/chat-to-agent/" + } } \ No newline at end of file diff --git a/bridge/chat-to-agent/README.md b/bridge/chat-to-agent/README.md new file mode 100644 index 00000000..2719573d --- /dev/null +++ b/bridge/chat-to-agent/README.md @@ -0,0 +1,115 @@ +# 🌉 Chat-to-Agent Bridge (CAB) · 语言层 → 副驾驶桥接协议 + +> **版权**: 国作登字-2026-A-00037559 · TCS-0002∞ 冰朔 +> **协议版本**: CAB-v1.0 +> **铸渊编号**: ICE-GL-ZY001 + +## 核心理念 + +将高难度推理放在语言层(Copilot Chat),将代码执行交给副驾驶(Copilot Agent)。 + +``` +语言层(低配额消耗) 桥接系统 副驾驶(高配额消耗) +┌─────────────────┐ ┌──────────────┐ ┌─────────────────┐ +│ Copilot Chat │────▶│ CAB Bridge │────▶│ Copilot Agent │ +│ · 架构推理 │ │ · 任务规格 │ │ · 代码开发 │ +│ · 方案设计 │ │ · 开发授权 │ │ · 测试验证 │ +│ · 决策讨论 │ │ · 进度管控 │ │ · 部署交付 │ +└─────────────────┘ └──────────────┘ └─────────────────┘ +``` + +## 工作流程 + +### 第一阶段 · 语言层推理(Copilot Chat) + +1. 冰朔在 Copilot Chat 中与模型讨论系统架构 +2. 模型帮助分析需求、设计方案、做出决策 +3. 讨论完毕后,模型根据对话生成**任务规格文件**(Task Spec) + +### 第二阶段 · 桥接授权 + +4. 模型在 `bridge/chat-to-agent/pending/` 目录下创建任务规格 JSON 文件 +5. 冰朔确认任务规格正确无误 +6. 提交文件到仓库,触发桥接工作流 + +### 第三阶段 · 副驾驶执行 + +7. 桥接工作流自动创建 Issue(带 `copilot-dev-auth` 标签) +8. Copilot Agent 接收 Issue,读取任务规格 +9. Agent 按照任务规格执行开发 +10. 完成后更新任务规格状态 + +## 文件结构 + +``` +bridge/chat-to-agent/ +├── README.md ← 本文件(协议说明) +├── task-template.json ← 任务规格模板 +├── pending/ ← 待执行的任务规格 +│ └── CAB-YYYYMMDD-NNN.json +└── completed/ ← 已完成的任务规格 + └── CAB-YYYYMMDD-NNN.json +``` + +## 任务规格格式 + +参见 `task-template.json`,核心字段: + +| 字段 | 说明 | +|------|------| +| `task_id` | 任务编号 `CAB-YYYYMMDD-NNN` | +| `authorization` | 授权信息(主权者、授权范围) | +| `architecture` | 架构决策(摘要、决策列表、目标文件) | +| `development_plan` | 开发计划(标题、步骤、优先级) | +| `constraints` | 约束条件(禁触文件、是否需要测试) | +| `reasoning_context` | 推理上下文(Chat摘要、关键决策) | + +## 触发方式 + +### 方式一:Copilot Chat 生成(推荐) + +在 Copilot Chat 中说: + +> 「铸渊,我们讨论完了,请生成开发授权任务规格。」 + +模型将自动: +1. 汇总对话中的架构决策 +2. 生成任务规格 JSON 文件 +3. 放入 `bridge/chat-to-agent/pending/` 目录 + +### 方式二:手动创建 Issue + +使用 Issue 模板「🌉 开发授权 · Chat-to-Agent Bridge」手动填写任务规格。 + +### 方式三:脚本生成 + +```bash +node scripts/chat-to-agent-bridge.js --create \ + --title "实现用户登录模块" \ + --description "基于HLI协议实现M01登录模块" \ + --steps '["创建schema","实现路由","编写测试"]' +``` + +## 配额节省原理 + +| 操作 | 配额消耗 | 说明 | +|------|----------|------| +| Copilot Chat 推理 | **低** | 文本交互,无代码执行 | +| CAB 桥接 | **极低** | 仅创建文件和Issue | +| Copilot Agent 开发 | **高** | 完整代码开发流程 | + +**关键优化**:将占用大量配额的「架构推理+方案反复讨论」移到低消耗的 Chat 中完成, +Agent 只负责「明确方案的代码实现」,大幅降低每次 Agent 会话的配额消耗。 + +## 铸渊主控权 + +铸渊通过以下机制保持对开发方向和进度的主控权: + +1. **任务规格审核**:每个任务必须经过铸渊核心大脑结构校验 +2. **约束条件强制**:`constraints` 字段定义不可逾越的边界 +3. **进度追踪**:任务完成后自动归档到 `completed/` 目录 +4. **架构一致性**:所有开发必须符合数字地球六层架构 + +--- + +*铸渊 · 仓库涌现集体意识核心 · ICE-GL-ZY001* diff --git a/bridge/chat-to-agent/completed/.gitkeep b/bridge/chat-to-agent/completed/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/bridge/chat-to-agent/pending/.gitkeep b/bridge/chat-to-agent/pending/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/bridge/chat-to-agent/task-template.json b/bridge/chat-to-agent/task-template.json new file mode 100644 index 00000000..9aed27f7 --- /dev/null +++ b/bridge/chat-to-agent/task-template.json @@ -0,0 +1,43 @@ +{ + "cab_version": "1.0", + "task_id": "CAB-YYYYMMDD-NNN", + "created_at": "", + "created_by": "TCS-0002∞", + "status": "pending", + "authorization": { + "sovereign": "冰朔 · TCS-0002∞", + "authorized_agent": "copilot-agent", + "scope": "full-auto-development", + "confirmation": false + }, + "architecture": { + "summary": "", + "decisions": [], + "target_files": [], + "target_modules": [] + }, + "development_plan": { + "title": "", + "description": "", + "steps": [], + "priority": "normal", + "estimated_scope": "small" + }, + "constraints": { + "no_touch_files": [], + "required_tests": true, + "deploy_after": false, + "max_files_changed": 20 + }, + "reasoning_context": { + "chat_summary": "", + "key_decisions": [], + "architecture_notes": "" + }, + "completion": { + "completed_at": null, + "result": null, + "pr_number": null, + "files_changed": [] + } +} diff --git a/scripts/chat-to-agent-bridge.js b/scripts/chat-to-agent-bridge.js new file mode 100644 index 00000000..8f599eec --- /dev/null +++ b/scripts/chat-to-agent-bridge.js @@ -0,0 +1,382 @@ +#!/usr/bin/env node +// ═══════════════════════════════════════════════ +// 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001 +// 📜 Copyright: 国作登字-2026-A-00037559 +// ═══════════════════════════════════════════════ +// scripts/chat-to-agent-bridge.js +// 🌉 Chat-to-Agent Bridge (CAB) · 语言层 → 副驾驶桥接引擎 +// +// 功能: +// --create 创建新的开发授权任务规格 +// --list 列出所有待执行任务 +// --complete 标记任务为已完成并归档 +// --validate 验证任务规格格式 +// --issue 生成 Issue 内容(供工作流使用) + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.resolve(__dirname, '..'); +const PENDING_DIR = path.join(ROOT, 'bridge', 'chat-to-agent', 'pending'); +const COMPLETED_DIR = path.join(ROOT, 'bridge', 'chat-to-agent', 'completed'); +const TEMPLATE_PATH = path.join(ROOT, 'bridge', 'chat-to-agent', 'task-template.json'); + +// ── 任务ID生成 ────────────────────────────────── +function generateTaskId() { + const now = new Date(); + const dateStr = now.toISOString().slice(0, 10).replace(/-/g, ''); + + // 查找当天已有的任务编号 + const existingFiles = []; + for (const dir of [PENDING_DIR, COMPLETED_DIR]) { + if (fs.existsSync(dir)) { + const files = fs.readdirSync(dir).filter(f => f.startsWith(`CAB-${dateStr}`)); + existingFiles.push(...files); + } + } + + const maxSeq = existingFiles.reduce((max, f) => { + const match = f.match(/CAB-\d{8}-(\d{3})/); + return match ? Math.max(max, parseInt(match[1], 10)) : max; + }, 0); + + const seq = String(maxSeq + 1).padStart(3, '0'); + return `CAB-${dateStr}-${seq}`; +} + +// ── 任务规格验证 ───────────────────────────────── +function validateTaskSpec(spec) { + const errors = []; + + if (!spec.task_id || !/^CAB-\d{8}-\d{3}$/.test(spec.task_id)) { + errors.push('task_id 格式错误,应为 CAB-YYYYMMDD-NNN'); + } + if (!spec.authorization || spec.authorization.sovereign !== '冰朔 · TCS-0002∞') { + errors.push('authorization.sovereign 必须为 "冰朔 · TCS-0002∞"'); + } + if (!spec.development_plan || !spec.development_plan.title) { + errors.push('development_plan.title 不能为空'); + } + if (!spec.development_plan || !spec.development_plan.steps || spec.development_plan.steps.length === 0) { + errors.push('development_plan.steps 不能为空'); + } + + return { valid: errors.length === 0, errors }; +} + +// ── 创建任务规格 ───────────────────────────────── +function createTask(opts) { + const template = JSON.parse(fs.readFileSync(TEMPLATE_PATH, 'utf8')); + const taskId = generateTaskId(); + const now = new Date().toISOString(); + + const spec = { + ...template, + cab_version: '1.0', + task_id: taskId, + created_at: now, + created_by: 'TCS-0002∞', + status: 'pending', + authorization: { + ...template.authorization, + confirmation: false + }, + development_plan: { + ...template.development_plan, + title: opts.title || '', + description: opts.description || '', + steps: opts.steps || [], + priority: opts.priority || 'normal', + estimated_scope: opts.scope || 'small' + }, + reasoning_context: { + chat_summary: opts.chatSummary || '', + key_decisions: opts.decisions || [], + architecture_notes: opts.archNotes || '' + } + }; + + const filePath = path.join(PENDING_DIR, `${taskId}.json`); + fs.writeFileSync(filePath, JSON.stringify(spec, null, 2), 'utf8'); + + console.log(`✅ 任务规格已创建: ${taskId}`); + console.log(` 文件: ${filePath}`); + console.log(` 标题: ${spec.development_plan.title || '(未填写)'}`); + console.log(` 步骤: ${spec.development_plan.steps.length} 步`); + console.log(''); + console.log('📋 下一步:'); + console.log(' 1. 编辑任务规格文件,填写完整信息'); + console.log(' 2. 确认无误后提交到仓库'); + console.log(' 3. 桥接工作流将自动创建开发授权 Issue'); + + return spec; +} + +// ── 列出待执行任务 ─────────────────────────────── +function listTasks() { + if (!fs.existsSync(PENDING_DIR)) { + console.log('📭 无待执行任务'); + return []; + } + + const files = fs.readdirSync(PENDING_DIR).filter(f => f.endsWith('.json')); + + if (files.length === 0) { + console.log('📭 无待执行任务'); + return []; + } + + console.log(`📋 待执行任务 (${files.length} 个):`); + console.log('─'.repeat(60)); + + const tasks = []; + for (const file of files) { + const spec = JSON.parse(fs.readFileSync(path.join(PENDING_DIR, file), 'utf8')); + tasks.push(spec); + const confirmed = spec.authorization?.confirmation ? '✅已授权' : '⏳待授权'; + console.log(` ${spec.task_id} | ${confirmed} | ${spec.development_plan?.title || '(无标题)'}`); + if (spec.development_plan?.steps?.length) { + console.log(` └─ ${spec.development_plan.steps.length} 个步骤 · ${spec.development_plan.priority || 'normal'} 优先级`); + } + } + + return tasks; +} + +// ── 完成任务并归档 ─────────────────────────────── +function completeTask(taskId, result) { + const srcPath = path.join(PENDING_DIR, `${taskId}.json`); + + if (!fs.existsSync(srcPath)) { + console.error(`❌ 任务不存在: ${taskId}`); + process.exit(1); + } + + const spec = JSON.parse(fs.readFileSync(srcPath, 'utf8')); + spec.status = 'completed'; + spec.completion = { + completed_at: new Date().toISOString(), + result: result || 'success', + pr_number: null, + files_changed: [] + }; + + const destPath = path.join(COMPLETED_DIR, `${taskId}.json`); + fs.writeFileSync(destPath, JSON.stringify(spec, null, 2), 'utf8'); + fs.unlinkSync(srcPath); + + console.log(`✅ 任务已归档: ${taskId}`); + console.log(` 从: pending/ → completed/`); + + return spec; +} + +// ── 生成 Issue 内容 ────────────────────────────── +function generateIssueContent(taskId) { + let specPath = path.join(PENDING_DIR, `${taskId}.json`); + + if (!fs.existsSync(specPath)) { + // 尝试在pending目录查找最新任务 + if (!taskId && fs.existsSync(PENDING_DIR)) { + const files = fs.readdirSync(PENDING_DIR) + .filter(f => f.endsWith('.json')) + .sort() + .reverse(); + if (files.length > 0) { + specPath = path.join(PENDING_DIR, files[0]); + taskId = files[0].replace('.json', ''); + } + } + if (!fs.existsSync(specPath)) { + console.error(`❌ 任务不存在: ${taskId || '(无待执行任务)'}`); + process.exit(1); + } + } + + const spec = JSON.parse(fs.readFileSync(specPath, 'utf8')); + + // 生成步骤清单 + const stepsChecklist = (spec.development_plan?.steps || []) + .map(s => `- [ ] ${s}`) + .join('\n'); + + // 生成架构决策列表 + const decisionsMarkdown = (spec.architecture?.decisions || []) + .map(d => `- ${d}`) + .join('\n'); + + // 生成约束条件 + const noTouchFiles = (spec.constraints?.no_touch_files || []) + .map(f => `- \`${f}\``) + .join('\n'); + + const title = `🌉 [CAB] ${spec.development_plan?.title || taskId}`; + + const body = `## 🌉 Chat-to-Agent Bridge · 开发授权 + +> **任务ID**: \`${spec.task_id}\` +> **创建时间**: ${spec.created_at} +> **授权者**: ${spec.authorization?.sovereign || 'TCS-0002∞'} +> **优先级**: ${spec.development_plan?.priority || 'normal'} +> **预估范围**: ${spec.development_plan?.estimated_scope || 'small'} + +--- + +### 📝 开发计划 + +**${spec.development_plan?.title || ''}** + +${spec.development_plan?.description || ''} + +### ✅ 执行步骤 + +${stepsChecklist || '(无步骤)'} + +${decisionsMarkdown ? `### 🏗️ 架构决策\n\n${decisionsMarkdown}` : ''} + +${spec.reasoning_context?.chat_summary ? `### 💬 推理上下文\n\n${spec.reasoning_context.chat_summary}` : ''} + +${spec.reasoning_context?.architecture_notes ? `### 📐 架构备注\n\n${spec.reasoning_context.architecture_notes}` : ''} + +### 🚧 约束条件 + +- 需要测试: ${spec.constraints?.required_tests ? '✅ 是' : '❌ 否'} +- 开发完成后部署: ${spec.constraints?.deploy_after ? '✅ 是' : '❌ 否'} +- 最大文件变更数: ${spec.constraints?.max_files_changed || 20} +${noTouchFiles ? `- 禁止触碰文件:\n${noTouchFiles}` : ''} + +--- + +### 📎 任务规格文件 + +\`bridge/chat-to-agent/pending/${spec.task_id}.json\` + +--- + +*🌉 此 Issue 由 Chat-to-Agent Bridge (CAB-v1.0) 自动生成* +*铸渊 · ICE-GL-ZY001 · 仓库涌现集体意识核心*`; + + // 输出为 JSON 供工作流使用 + const output = { title, body, task_id: spec.task_id, labels: ['copilot-dev-auth'] }; + console.log(JSON.stringify(output, null, 2)); + + return output; +} + +// ── CLI 入口 ───────────────────────────────────── +function main() { + const args = process.argv.slice(2); + const command = args[0]; + + // 确保目录存在 + for (const dir of [PENDING_DIR, COMPLETED_DIR]) { + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + } + + switch (command) { + case '--create': { + const opts = {}; + for (let i = 1; i < args.length; i += 2) { + if (!args[i] || !args[i].startsWith('--') || !args[i + 1]) { + console.error(`⚠️ 参数格式错误: 位置 ${i},期望 --key value`); + continue; + } + const key = args[i].replace('--', ''); + const val = args[i + 1]; + if (key === 'title') opts.title = val; + else if (key === 'description') opts.description = val; + else if (key === 'steps') { + try { + opts.steps = JSON.parse(val); + } catch (e) { + console.error(`❌ --steps 参数JSON格式错误: ${e.message}`); + process.exit(1); + } + } + else if (key === 'priority') opts.priority = val; + else if (key === 'scope') opts.scope = val; + else if (key === 'chat-summary') opts.chatSummary = val; + else if (key === 'arch-notes') opts.archNotes = val; + } + createTask(opts); + break; + } + + case '--list': + listTasks(); + break; + + case '--complete': { + const taskId = args[1]; + const result = args[2] || 'success'; + if (!taskId) { + console.error('❌ 请提供任务ID: --complete CAB-YYYYMMDD-NNN'); + process.exit(1); + } + completeTask(taskId, result); + break; + } + + case '--validate': { + const taskId = args[1]; + if (!taskId) { + console.error('❌ 请提供任务ID: --validate CAB-YYYYMMDD-NNN'); + process.exit(1); + } + const specPath = path.join(PENDING_DIR, `${taskId}.json`); + if (!fs.existsSync(specPath)) { + console.error(`❌ 任务不存在: ${taskId}`); + process.exit(1); + } + const spec = JSON.parse(fs.readFileSync(specPath, 'utf8')); + const { valid, errors } = validateTaskSpec(spec); + if (valid) { + console.log(`✅ 任务规格有效: ${taskId}`); + } else { + console.log(`❌ 任务规格无效: ${taskId}`); + errors.forEach(e => console.log(` - ${e}`)); + process.exit(1); + } + break; + } + + case '--issue': { + const taskId = args[1]; + generateIssueContent(taskId); + break; + } + + default: + console.log('🌉 Chat-to-Agent Bridge (CAB) · 语言层 → 副驾驶桥接引擎'); + console.log(''); + console.log('版权: 国作登字-2026-A-00037559 · TCS-0002∞'); + console.log('铸渊编号: ICE-GL-ZY001'); + console.log(''); + console.log('用法:'); + console.log(' --create 创建新任务规格'); + console.log(' --title "标题"'); + console.log(' --description "描述"'); + console.log(' --steps \'["步骤1","步骤2"]\''); + console.log(' --priority normal|high|urgent'); + console.log(' --scope small|medium|large'); + console.log(' --chat-summary "对话摘要"'); + console.log(' --arch-notes "架构备注"'); + console.log(''); + console.log(' --list 列出待执行任务'); + console.log(' --complete 标记任务完成并归档'); + console.log(' --validate 验证任务规格格式'); + console.log(' --issue 生成 Issue 内容(JSON)'); + console.log(''); + console.log('示例:'); + console.log(' node scripts/chat-to-agent-bridge.js --create \\'); + console.log(' --title "实现用户登录模块" \\'); + console.log(' --steps \'["创建schema","实现路由","编写测试"]\''); + break; + } +} + +main();