From 27d0ddff518e037bd15313c3cb19953ca2054aa6 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 21 May 2026 10:25:40 +0000 Subject: [PATCH] feat: add gh board-row upsert --- docs/reference/cli.md | 2 +- scripts/gh-cli-issue-guard-contract-test.ts | 218 ++++++++ scripts/src/gh.ts | 556 +++++++++++++++++++- 3 files changed, 763 insertions(+), 13 deletions(-) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 42788405..a777c6ff 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -36,7 +36,7 @@ CLI 可以从 `master` 快速演进,但必须兼容 `deploy.json` 固定的 CI - `gh issue update --mode replace|append --body-file ` 是正文更新主入口,`edit` 保留为兼容别名。`replace` 用文件正文替换现有 body;`append` 先读取当前 body,再按 UTF-8 文件字节追加,保留真实换行、反引号和 Markdown 表格。更新默认拒绝字面量 `null`、空白正文和过短正文;只有真实需要写短正文时才允许显式加 `--allow-short-body`,返回 JSON 会报告该风险。#20 总看板和指挥简报类 issue 是长期 body-only issue,`--body-profile auto` 会按 issue number 自动启用 #20/#24 legacy guard:#20 必须包含 `## 看板(OPEN)`,#24 legacy 指挥简报必须包含 `## 常驻观察与长期建议`。显式 `--body-profile commander-brief` 不再固定 #24;#24 仍兼容,标题为 `YYYY-MM-DD 指挥简报(北京时间)` 或既有正文首行/关键 heading 表明为每日滚动指挥简报的 issue 也合法,并仍必须包含 `## 常驻观察与长期建议`。对非简报 issue 显式使用 `commander-brief` 会结构化失败为 `profile-issue-mismatch`。`--dry-run` 不 PATCH GitHub,输出新正文长度、SHA、关键标题检查结果、字面量 `\n`、反引号、Markdown 表格和 shell 污染信号;若环境里有 `GH_TOKEN` 或 `GITHUB_TOKEN`,dry-run 还会只读抓取旧正文长度、SHA 和 `updatedAt` 作为更新前对照。正式写入可带 `--expect-updated-at ` 或 `--expect-body-sha `,CLI 会先读当前 issue,匹配后才 PATCH,防止旧缓存覆盖新正文。 - `gh issue edit 24 --body-file --notify-claudeqq-brief-diff [--dry-run]` 是 legacy #24 指挥简报的通知入口。正式执行会先读取 GitHub 上 #24 旧正文并通过 #24 body profile guard,再从 `--body-file` 读取新正文;随后先 PATCH issue 主体,再把本次新增的 `## 更新 YYYY-MM-DD HH:MM 北京时间` 段落发送给 ClaudeQQ,ClaudeQQ 失败不会回滚 issue 正文,失败只体现在返回 JSON 的 `claudeqq.ok=false` 和结构化 `degradedReason`。每日滚动简报 issue 可用普通 `gh issue update --body-profile commander-brief --dry-run` 和并发 guard 更新,但此通知 helper 仍只支持 #24。带通知 flag 的 `--dry-run` 不 PATCH、不发送;它按新正文做发送预览,并在输出中标明非 dry-run 才会读取旧正文做可靠 diff。默认 ClaudeQQ 目标是私聊 `645275593`,默认 base URL 是 UniDesk 受控入口 `http://backend-core:8080/api/microservices/claudeqq/proxy`,可用 `UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_ENABLED`、`UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_BASE_URL`、`UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_TARGET_TYPE`、`UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_USER_ID`、`UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_GROUP_ID` 和 `UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_TIMEOUT_MS` 覆盖。 - `gh issue board-audit [--repo owner/name] [--board-issue 20] [--limit N] [--known-meta-issue N[,N...]] [--ignore-issue N[,N...]] [--dry-run]` 是 #20 长期总看板只读覆盖审计入口,默认 repo 为 `pikasTech/unidesk`、board issue 为 `20`、输出 JSON 且不 PATCH/POST/DELETE GitHub。它读取 board body、GitHub open issue 列表和 closed issue 列表,对比 OPEN/CLOSED Markdown 表格并输出 `missingOpenIssues`、`closedInOpenRows`、`missingClosedRows`、`openInClosedRows`、`rowValidationWarnings`、`ignoredIssues` 和 `recommendedActions`。当表格里存在 Issue 列时,row.issueNumber 优先取 Issue cell 中第一个指向 `/issues/` 的 Markdown link,找不到时取开头的 `#N`;同一 Issue cell 里主引用后面的标题说明引用(例如 `#20 总看板`、`基于 #4`)不触发 `multiple-issue-references`。没有 Issue 列的旧表格仍回退到整行 issue 提取,并保留多 issue 引用告警。`相关 Code Queue 任务`/`relatedTask` 列允许 `—`、`-`、`n/a`、`无任务` 等无关联任务占位表示 closed 历史/治理项没有 Code Queue task;这个放宽不适用于 branch、acceptance 或 progress。默认把 #20 和 #24 作为 `known-meta` 治理/简报 issue 忽略;标题匹配 `YYYY-MM-DD 指挥简报(北京时间)` 的每日滚动简报由 #20 顶部指挥简报索引管理,不进入 OPEN/CLOSED 覆盖审计,并在 `ignoredIssues` 中标记 `reason=brief-index-managed`。需要扩展治理项用 `--known-meta-issue`,临时排除业务 issue 用 `--ignore-issue`。指挥官发现总看板可能漏行时,应先跑 board audit 获取结构化结果,再决定是否人工编辑 #20,而不是只靠 grep。 -- `gh issue board-row list --board-issue 20 [--state open|closed|all] [--dry-run]`、`gh issue board-row get --board-issue 20` 和 `gh issue board-row update --board-issue 20 --field progress|status|validation|branch|tasks|focus --value [--dry-run] [--expect-updated-at ts|--expect-body-sha sha256]` 是 #20 看板表格单行结构化入口。list/get 复用 board-audit parser,只读返回 row、cells、fields、section、lineNumber、bodySha 和 rowValidationWarnings。update 只替换命中的一行里一个单元格,返回 old/new row、old/new body SHA、body guard、request plan 和 parser 结果;默认没有并发期望时即使不写 `--dry-run` 也只做 dry-run,正式 PATCH 必须带 `--expect-body-sha` 或 `--expect-updated-at`。字段映射固定为:`branch` -> Branch,`progress` -> 进度,`status`/`validation` -> 验收状态,`tasks` -> 相关 Code Queue 任务,`focus` -> 当前关注点。单元格值中的 Markdown 表格管道会转义为 `\|`,真实换行会折叠为空格,避免新增字面量 `\n` 污染。`gh issue board-row add --board-issue 20 --section open|closed --row-file [--dry-run] [--expect-body-sha|--expect-updated-at]`、`move --board-issue 20 --to open|closed [--status OPEN|CLOSED] [--dry-run] [--expect-body-sha|--expect-updated-at]` 和 `delete --board-issue 20 [--dry-run] [--expect-body-sha|--expect-updated-at]` 是 row-scoped #20 结构化写入口。add 校验一行 `--row-file` 的 Issue 列、列数和 GitHub 状态列与目标 section 一致;move 允许跨 OPEN/CLOSED 表迁移并在需要时同步 GitHub 状态列;delete 仅删除匹配行。三者默认 dry-run,非 dry-run 必须带 `--expect-body-sha` 或 `--expect-updated-at`,并返回 old/new row、body SHA、line/section 计划和 parser 结果。 +- `gh issue board-row list --board-issue 20 [--state open|closed|all] [--dry-run]`、`gh issue board-row get --board-issue 20` 和 `gh issue board-row update --board-issue 20 --field progress|status|validation|branch|tasks|focus --value [--dry-run] [--expect-updated-at ts|--expect-body-sha sha256]` 是 #20 看板表格单行结构化入口。list/get 复用 board-audit parser,只读返回 row、cells、fields、section、lineNumber、bodySha 和 rowValidationWarnings。update 只替换命中的一行里一个单元格,返回 old/new row、old/new body SHA、body guard、request plan 和 parser 结果;默认没有并发期望时即使不写 `--dry-run` 也只做 dry-run,正式 PATCH 必须带 `--expect-body-sha` 或 `--expect-updated-at`。字段映射固定为:`branch` -> Branch,`progress` -> 进度,`status`/`validation` -> 验收状态,`tasks` -> 相关 Code Queue 任务,`focus` -> 当前关注点。单元格值中的 Markdown 表格管道会转义为 `\|`,真实换行会折叠为空格,避免新增字面量 `\n` 污染。`gh issue board-row upsert --board-issue 20 --section open|closed [--category text] --branch --tasks --summary --focus --validation --progress [--status OPEN|CLOSED] [--dry-run] [--expect-body-sha|--expect-updated-at]` 是行级补齐入口:若 issue 已存在则只更新传入字段并返回 `operation=update`,未传字段保留原值;若不存在则按目标 section 表头生成完整行并返回 `operation=add`。新增时 `--section` 必需,且目标表头中的 category/branch/tasks/summary/focus/validation/progress 列都必须有对应值;若表没有独立 Summary/摘要列,`--summary` 会并入 Issue 单元格。upsert 不关闭、不删除、不重开 GitHub issue,也不做 OPEN/CLOSED 迁移;已存在行的 `--section` 或 `--status` 与当前 section 冲突时会结构化失败并提示使用 `board-row move`。`gh issue board-row add --board-issue 20 --section open|closed --row-file [--dry-run] [--expect-body-sha|--expect-updated-at]`、`move --board-issue 20 --to open|closed [--status OPEN|CLOSED] [--dry-run] [--expect-body-sha|--expect-updated-at]` 和 `delete --board-issue 20 [--dry-run] [--expect-body-sha|--expect-updated-at]` 是 row-scoped #20 结构化写入口。add 校验一行 `--row-file` 的 Issue 列、列数和 GitHub 状态列与目标 section 一致;move 允许跨 OPEN/CLOSED 表迁移并在需要时同步 GitHub 状态列;delete 仅删除匹配行。四类写入口默认 dry-run,非 dry-run 必须带 `--expect-body-sha` 或 `--expect-updated-at`,并返回 old/new row、body SHA、line/section 计划和 parser 结果;duplicate/ambiguous row、列数不匹配、缺少新增必填字段、section/status 冲突或 body SHA 不匹配都会结构化失败,不会 fallback 到整篇 body 手工替换。 - `gh issue scan-escape [--repo owner/name] [--limit N] [--dry-run]` 只读扫描 issue 主体和 comments 中的字面量 `\n`、可疑 `\t`、shell newline escape、escaped backtick、ANSI escape 字符串、短 body、blank body 和 null body。输出固定 JSON,`findings` 会带 `bodyKind=issue-body|comment-body`、`issueNumber`、`issueId`、`commentId`、`lineNumber`、`column`、`kind`、`snippet` 和 `classification=suspected-pollution|explanatory-mention|risk`,用于区分说明性提到 `\n` 和疑似污染;`cleanupSuggestions` 只给 dry-run 清理建议、body/comment 定位和 diff-like preview,不 PATCH、不 DELETE、不真实清理历史 comment。`gh issue cleanup-plan` 是同一只读能力的别名,默认 `dryRun=true`。`gh pr list|read|view [--json ...]` 提供 REST 列表和详情,PR 字段白名单是 `body,title,state,number,url,author,head,base,draft,createdAt,updatedAt`。`gh pr create --title --body-file <file>|--body <text> --base <branch> --head <branch> [--draft] [--dry-run]`、`gh pr update <number> --mode replace|append --body-file <file>|--body <text> [--title ...] [--dry-run]`、`gh pr comment create <number> --body-file <file>|--body <text> [--dry-run]`、`gh pr comment delete <commentId> [--dry-run]`、`gh pr close|reopen <number> [--dry-run]` 是 PR CRUD/生命周期入口。`pr create --dry-run` 只输出 planned operation,不访问 GitHub;非 dry-run 创建前会校验 repo、base、head 和 compare ahead 状态,成功时返回 PR number/url。`pr update --mode append` 会先读取当前 PR body 再追加正文。`gh pr delete <number>` 和 `gh pr merge` 本阶段不开放,始终结构化返回 `unsupported-command`;PR 生命周期删除语义请使用 `close`。 - PR dry-run/probe 的最小手动序列是:`bun scripts/cli.ts gh auth status --repo pikasTech/unidesk` 只读检查 token 来源、GitHub REST egress、repo 可见性和 issue read;`bun scripts/cli.ts gh pr create --repo pikasTech/unidesk --title <title> --body-file <file> --base master --head <head> --dry-run` 检查创建计划;`bun scripts/cli.ts gh pr list --repo pikasTech/unidesk --limit 5 --json number,title,state,url,head,base` 和 `bun scripts/cli.ts gh pr read <number> --repo pikasTech/unidesk --json body,title,state,head,base` 做只读 PR 观察;`bun scripts/cli.ts gh pr comment <number> --repo pikasTech/unidesk --body-file <file> --dry-run` 检查评论计划;`bun scripts/cli.ts gh pr merge <number> --repo pikasTech/unidesk` 必须失败并返回结构化 `unsupported-command`。Code Queue runner 可用 `bun scripts/code-queue-pr-preflight-example.ts --repo pikasTech/unidesk --base master --head <head> --comment-pr <number>` 一次性跑只读 auth status 与 PR create/comment dry-run;该脚本不得输出 token 值,也不会创建、评论或 merge PR。 - `ci install|status|run|publish-backend-core|publish-user-service|run-dev-e2e|logs` 管理 D601 原生 k3s 上的 Tekton CI。`run` 手动创建每 commit 检查和 Code Queue 只读性能门禁;`publish-backend-core` 与 `publish-user-service` 从 pushed Git commit 构建并发布 `127.0.0.1:5000/unidesk/<service>:<commit>` commit-pinned artifacts,输出 `artifactSummary`(含 `serviceId`、`sourceCommit`、`sourceRepo`、`dockerfile`、`imageRef`、`tag`、`digest`、`digestRef`),但不部署生产;`run-dev-e2e` 的 Git 控制 runner、短 launcher、host fetch 边界、临时 smoke namespace 和 no-CD 规则只在 `docs/reference/dev-ci-runner.md` 定义;Tekton CI 通用规则见 `docs/reference/ci.md`。 diff --git a/scripts/gh-cli-issue-guard-contract-test.ts b/scripts/gh-cli-issue-guard-contract-test.ts index 9269a9f0..e39f3698 100644 --- a/scripts/gh-cli-issue-guard-contract-test.ts +++ b/scripts/gh-cli-issue-guard-contract-test.ts @@ -109,6 +109,40 @@ async function startMockGitHub(): Promise<{ baseUrl: string; requests: MockReque ].join("\n"); let boardIssueBody = boardIssueBodyInitial; let boardIssueUpdatedAt = "2026-05-20T01:00:00Z"; + const upsertBoardIssueBodyInitial = [ + "# Upsert Board", + "", + "## 看板(OPEN)", + "", + "| Issue | GitHub 状态 | Category | Branch | Summary | 验收状态 | 相关 Code Queue 任务 | 当前关注点 | 进度 |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", + "| #70 | OPEN | cli | master | existing summary | pass | cq-70 | existing focus | doing |", + "| #72 | OPEN | cli | master | duplicate open | pass | cq-72 | duplicate open | doing |", + "| #79 | OPEN | defect | master | bad row | pass | cq-79 | missing progress |", + "", + "## 看板(CLOSED)", + "", + "| Issue | GitHub 状态 | Category | Branch | Summary | 验收状态 | 相关 Code Queue 任务 | 当前关注点 | 进度 |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", + "| #71 | CLOSED | ops | master | closed summary | pass | — | archived focus | done |", + "| #72 | CLOSED | ops | master | duplicate closed | pass | — | duplicate closed | done |", + "", + "## 更新 2026-05-21 10:00 北京时间", + "", + "- 表后的更新段落必须保留。", + "", + ].join("\n"); + let upsertBoardIssueBody = upsertBoardIssueBodyInitial; + let upsertBoardIssueUpdatedAt = "2026-05-20T01:30:00Z"; + const upsertBoardIssue = { + ...issue, + id: 2062, + number: 62, + title: "Upsert board fixture", + body: upsertBoardIssueBody, + html_url: "https://github.com/pikasTech/unidesk/issues/62", + updated_at: upsertBoardIssueUpdatedAt, + }; const legacyBoardIssue = { ...issue, id: 2600, @@ -413,6 +447,10 @@ async function startMockGitHub(): Promise<{ baseUrl: string; requests: MockReque sendJson(res, 200, legacyBoardIssue); return; } + if (req.method === "GET" && req.url === "/repos/pikasTech/unidesk/issues/62") { + sendJson(res, 200, { ...upsertBoardIssue, body: upsertBoardIssueBody, updated_at: upsertBoardIssueUpdatedAt }); + return; + } if (req.method === "GET" && req.url === "/repos/pikasTech/unidesk/issues/20/comments?per_page=100") { sendJson(res, 200, comments); return; @@ -466,6 +504,13 @@ async function startMockGitHub(): Promise<{ baseUrl: string; requests: MockReque sendJson(res, 200, { ...issue, body: boardIssueBody, updated_at: boardIssueUpdatedAt }); return; } + if (req.method === "PATCH" && req.url === "/repos/pikasTech/unidesk/issues/62") { + const parsed = JSON.parse(body) as JsonRecord; + upsertBoardIssueBody = String(parsed.body ?? upsertBoardIssueBody); + upsertBoardIssueUpdatedAt = "2026-05-20T01:35:00Z"; + sendJson(res, 200, { ...upsertBoardIssue, body: upsertBoardIssueBody, updated_at: upsertBoardIssueUpdatedAt }); + return; + } if (req.method === "POST" && req.url === "/repos/pikasTech/unidesk/issues/20/comments") { const parsed = JSON.parse(body) as JsonRecord; sendJson(res, 201, { id: 9001, body: String(parsed.body ?? ""), html_url: "https://github.com/pikasTech/unidesk/issues/20#issuecomment-9001", user: { login: "tester" }, created_at: "2026-05-20T06:00:00Z", updated_at: "2026-05-20T06:00:00Z" }); @@ -528,11 +573,13 @@ export async function runGhCliIssueGuardContract(): Promise<JsonRecord> { assertCondition(usage.some((line) => line.includes("gh issue board-row list")), "gh help should list board-row list", { usage }); assertCondition(usage.some((line) => line.includes("gh issue board-row update")), "gh help should list board-row update", { usage }); assertCondition(usage.some((line) => line.includes("gh issue board-row add")), "gh help should list board-row add", { usage }); + assertCondition(usage.some((line) => line.includes("gh issue board-row upsert")), "gh help should list board-row upsert", { usage }); assertCondition(usage.some((line) => line.includes("gh issue board-row move")), "gh help should list board-row move", { usage }); assertCondition(usage.some((line) => line.includes("gh issue board-row delete")), "gh help should list board-row delete", { usage }); assertCondition(notes.some((line) => line.includes("canonical read path")), "gh help should state issue read is canonical", { notes }); assertCondition(notes.some((line) => line.includes("compatibility alias")), "gh help should state issue view is alias", { notes }); assertCondition(notes.some((line) => line.includes("board-row update changes one table cell")), "gh help should describe board-row update safety", { notes }); + assertCondition(notes.some((line) => line.includes("board-row upsert updates an existing row")), "gh help should describe board-row upsert safety", { notes }); assertCondition(notes.some((line) => line.includes("board-row add/move/delete are row-scoped")), "gh help should describe board-row row mutation safety", { notes }); const mock = await startMockGitHub(); @@ -658,6 +705,176 @@ export async function runGhCliIssueGuardContract(): Promise<JsonRecord> { assertCondition(Array.isArray(boardRowGetRow.cells) && boardRowGetRow.cells[1] === "OPEN", "board-row get should expose the GitHub status column", boardRowGetRow); assertCondition(boardRowGetFields.branch === "master" && boardRowGetFields.status === "pass" && boardRowGetFields.validation === "pass" && boardRowGetFields.tasks === "cq-35" && String(boardRowGetFields.focus ?? "").includes("当前关注点"), "board-row get should expose canonical field aliases", boardRowGetFields); + const boardRowUpsertUpdateRequestCountBefore = mock.requests.length; + const boardRowUpsertUpdate = await runCli([ + "gh", "issue", "board-row", "upsert", "70", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--summary", "中文 `code` [#20](https://github.com/pikasTech/unidesk/issues/20) A | B\nsecond line", + "--focus", "焦点 A | B\n下一行", + "--validation", "manual pass", + "--progress", "reviewing", + "--dry-run", + ], env); + assertCondition(boardRowUpsertUpdate.status === 0, "board-row upsert existing row should dry-run update", boardRowUpsertUpdate.json ?? { stdout: boardRowUpsertUpdate.stdout, stderr: boardRowUpsertUpdate.stderr }); + const boardRowUpsertUpdateData = dataOf(boardRowUpsertUpdate.json ?? {}); + assertCondition(boardRowUpsertUpdateData.command === "issue board-row upsert" && boardRowUpsertUpdateData.operation === "update" && boardRowUpsertUpdateData.dryRun === true && boardRowUpsertUpdateData.planned === true, "upsert existing row should report update operation", boardRowUpsertUpdateData); + const boardRowUpsertUpdatePlan = boardRowUpsertUpdateData.upsert as JsonRecord; + assertCondition(boardRowUpsertUpdatePlan.operation === "update" && boardRowUpsertUpdatePlan.section === "open", "upsert update plan should stay in existing section", boardRowUpsertUpdatePlan); + assertCondition(boardRowUpsertUpdatePlan.oldRow === "| #70 | OPEN | cli | master | existing summary | pass | cq-70 | existing focus | doing |", "upsert update should expose old row", boardRowUpsertUpdatePlan); + assertCondition(boardRowUpsertUpdatePlan.newRow === "| #70 | OPEN | cli | master | 中文 `code` [#20](https://github.com/pikasTech/unidesk/issues/20) A \\| B second line | manual pass | cq-70 | 焦点 A \\| B 下一行 | reviewing |", "upsert update should escape pipes, preserve backticks/link text, and fold real newlines", boardRowUpsertUpdatePlan); + const boardRowUpsertUpdateSafety = boardRowUpsertUpdateData.bodyOnlySafety as JsonRecord; + const boardRowUpsertUpdateNewBody = boardRowUpsertUpdateSafety.newBody as JsonRecord; + assertCondition(boardRowUpsertUpdateNewBody.containsLiteralBackslashN === false && boardRowUpsertUpdateNewBody.containsBackticks === true && boardRowUpsertUpdateNewBody.containsMarkdownTable === true, "upsert update should preserve markdown safety signals", boardRowUpsertUpdateNewBody); + const boardRowUpsertUpdateWriteCount = mock.requests.slice(boardRowUpsertUpdateRequestCountBefore).filter((request) => request.method === "PATCH").length; + assertCondition(boardRowUpsertUpdateWriteCount === 0, "board-row upsert update dry-run must not PATCH GitHub", { requests: mock.requests.slice(boardRowUpsertUpdateRequestCountBefore) }); + + const boardRowUpsertAddRequestCountBefore = mock.requests.length; + const boardRowUpsertAdd = await runCli([ + "gh", "issue", "board-row", "upsert", "73", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--category", "cli", + "--branch", "master", + "--tasks", "cq-73", + "--summary", "新增中文 `code` [#20](https://github.com/pikasTech/unidesk/issues/20) A | B\n真实换行", + "--focus", "关注 | 重点\nnext", + "--validation", "pending", + "--progress", "queued", + "--dry-run", + ], env); + assertCondition(boardRowUpsertAdd.status === 0, "board-row upsert missing row should dry-run add", boardRowUpsertAdd.json ?? { stdout: boardRowUpsertAdd.stdout, stderr: boardRowUpsertAdd.stderr }); + const boardRowUpsertAddData = dataOf(boardRowUpsertAdd.json ?? {}); + assertCondition(boardRowUpsertAddData.command === "issue board-row upsert" && boardRowUpsertAddData.operation === "add" && boardRowUpsertAddData.dryRun === true && boardRowUpsertAddData.planned === true, "upsert missing row should report add operation", boardRowUpsertAddData); + const boardRowUpsertAddPlan = boardRowUpsertAddData.upsert as JsonRecord; + assertCondition(boardRowUpsertAddPlan.operation === "add" && boardRowUpsertAddPlan.section === "open" && Number(boardRowUpsertAddPlan.insertAfterLine ?? 0) > 0, "upsert add should expose insertion plan", boardRowUpsertAddPlan); + assertCondition(boardRowUpsertAddPlan.newRow === "| #73 | OPEN | cli | master | 新增中文 `code` [#20](https://github.com/pikasTech/unidesk/issues/20) A \\| B 真实换行 | pending | cq-73 | 关注 \\| 重点 next | queued |", "upsert add should generate a full escaped row", boardRowUpsertAddPlan); + const boardRowUpsertAddNewBody = ((boardRowUpsertAddData.bodyOnlySafety as JsonRecord).newBody as JsonRecord); + assertCondition(boardRowUpsertAddNewBody.containsLiteralBackslashN === false && boardRowUpsertAddNewBody.containsBackticks === true, "upsert add should not introduce literal backslash-n", boardRowUpsertAddNewBody); + const boardRowUpsertAddWriteCount = mock.requests.slice(boardRowUpsertAddRequestCountBefore).filter((request) => request.method === "PATCH").length; + assertCondition(boardRowUpsertAddWriteCount === 0, "board-row upsert add dry-run must not PATCH GitHub", { requests: mock.requests.slice(boardRowUpsertAddRequestCountBefore) }); + + const boardRowUpsertNoGuardRequestCountBefore = mock.requests.length; + const boardRowUpsertNoGuard = await runCli([ + "gh", "issue", "board-row", "upsert", "74", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--category", "cli", + "--branch", "master", + "--tasks", "cq-74", + "--summary", "formal write omitted guard", + "--focus", "focus", + "--validation", "pending", + "--progress", "queued", + ], env); + assertCondition(boardRowUpsertNoGuard.status === 0, "board-row upsert without guard should stay on the dry-run path", boardRowUpsertNoGuard.json ?? { stdout: boardRowUpsertNoGuard.stdout, stderr: boardRowUpsertNoGuard.stderr }); + const boardRowUpsertNoGuardData = dataOf(boardRowUpsertNoGuard.json ?? {}); + assertCondition(boardRowUpsertNoGuardData.dryRun === true && boardRowUpsertNoGuardData.planned === true && boardRowUpsertNoGuardData.operation === "add", "upsert without guard should not PATCH GitHub", boardRowUpsertNoGuardData); + const boardRowUpsertNoGuardWriteCount = mock.requests.slice(boardRowUpsertNoGuardRequestCountBefore).filter((request) => request.method === "PATCH").length; + assertCondition(boardRowUpsertNoGuardWriteCount === 0, "board-row upsert without guard must not PATCH GitHub", { requests: mock.requests.slice(boardRowUpsertNoGuardRequestCountBefore) }); + + const boardRowUpsertListBeforeWrite = await runCli(["gh", "issue", "board-row", "list", "--repo", "pikasTech/unidesk", "--board-issue", "62", "--state", "all"], env); + assertCondition(boardRowUpsertListBeforeWrite.status === 0, "upsert board list before guarded write should succeed", boardRowUpsertListBeforeWrite.json ?? { stdout: boardRowUpsertListBeforeWrite.stdout, stderr: boardRowUpsertListBeforeWrite.stderr }); + const boardRowUpsertBoardSha = String((dataOf(boardRowUpsertListBeforeWrite.json ?? {}).boardIssue as JsonRecord).bodySha ?? ""); + const boardRowUpsertWriteRequestCountBefore = mock.requests.length; + const boardRowUpsertWrite = await runCli([ + "gh", "issue", "board-row", "upsert", "73", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--category", "cli", + "--branch", "master", + "--tasks", "cq-73", + "--summary", "guarded add keeps table trailer", + "--focus", "focus", + "--validation", "pending", + "--progress", "queued", + "--expect-body-sha", boardRowUpsertBoardSha, + ], env); + assertCondition(boardRowUpsertWrite.status === 0, "board-row upsert with expect body sha should PATCH", boardRowUpsertWrite.json ?? { stdout: boardRowUpsertWrite.stdout, stderr: boardRowUpsertWrite.stderr }); + const boardRowUpsertWriteData = dataOf(boardRowUpsertWrite.json ?? {}); + assertCondition(boardRowUpsertWriteData.dryRun === false && boardRowUpsertWriteData.rest === true && boardRowUpsertWriteData.operation === "add", "upsert guarded write should report real add", boardRowUpsertWriteData); + const boardRowUpsertWriteRequests = mock.requests.slice(boardRowUpsertWriteRequestCountBefore).filter((request) => request.method === "PATCH" && request.url === "/repos/pikasTech/unidesk/issues/62"); + assertCondition(boardRowUpsertWriteRequests.length === 1, "board-row upsert should send exactly one PATCH", { requests: mock.requests.slice(boardRowUpsertWriteRequestCountBefore) }); + const boardRowUpsertWritePayload = JSON.parse(boardRowUpsertWriteRequests[0]?.body ?? "{}") as JsonRecord; + const boardRowUpsertWrittenBody = String(boardRowUpsertWritePayload.body ?? ""); + assertCondition(boardRowUpsertWrittenBody.includes("| #73 | OPEN | cli | master | guarded add keeps table trailer | pending | cq-73 | focus | queued |"), "upsert write payload should include generated row", boardRowUpsertWritePayload); + assertCondition(boardRowUpsertWrittenBody.includes("## 看板(CLOSED)") && boardRowUpsertWrittenBody.includes("## 更新 2026-05-21 10:00 北京时间") && boardRowUpsertWrittenBody.includes("- 表后的更新段落必须保留。"), "upsert write should preserve CLOSED table and post-table update section", boardRowUpsertWritePayload); + + const boardRowUpsertStale = await runCli([ + "gh", "issue", "board-row", "upsert", "76", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--category", "cli", + "--branch", "master", + "--tasks", "cq-76", + "--summary", "stale guard must fail", + "--focus", "focus", + "--validation", "pending", + "--progress", "queued", + "--expect-body-sha", boardRowUpsertBoardSha, + ], env); + assertCondition(boardRowUpsertStale.status !== 0, "stale board-row upsert should fail structurally", boardRowUpsertStale.json ?? { stdout: boardRowUpsertStale.stdout, stderr: boardRowUpsertStale.stderr }); + const boardRowUpsertStaleData = failedDataOf(boardRowUpsertStale.json ?? {}); + assertCondition(boardRowUpsertStaleData.degradedReason === "validation-failed" && boardRowUpsertStaleData.command === "issue board-row upsert", "stale board-row upsert should be validation-failed", boardRowUpsertStaleData); + + const boardRowUpsertDuplicate = await runCli([ + "gh", "issue", "board-row", "upsert", "72", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--focus", "duplicate should fail", + "--dry-run", + ], env); + assertCondition(boardRowUpsertDuplicate.status !== 0, "duplicate board-row upsert should fail structurally", boardRowUpsertDuplicate.json ?? { stdout: boardRowUpsertDuplicate.stdout, stderr: boardRowUpsertDuplicate.stderr }); + const boardRowUpsertDuplicateData = failedDataOf(boardRowUpsertDuplicate.json ?? {}); + assertCondition(String((boardRowUpsertDuplicateData.details as JsonRecord).message ?? "").includes("ambiguous"), "duplicate upsert should report ambiguous row", boardRowUpsertDuplicateData); + + const boardRowUpsertSectionConflict = await runCli([ + "gh", "issue", "board-row", "upsert", "70", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "closed", + "--focus", "migration belongs to move", + "--dry-run", + ], env); + assertCondition(boardRowUpsertSectionConflict.status !== 0, "upsert section conflict should fail structurally", boardRowUpsertSectionConflict.json ?? { stdout: boardRowUpsertSectionConflict.stdout, stderr: boardRowUpsertSectionConflict.stderr }); + const boardRowUpsertSectionConflictData = failedDataOf(boardRowUpsertSectionConflict.json ?? {}); + assertCondition(String((boardRowUpsertSectionConflictData.details as JsonRecord).message ?? "").includes("use gh issue board-row move"), "upsert section conflict should point to move", boardRowUpsertSectionConflictData); + + const boardRowUpsertMissingField = await runCli([ + "gh", "issue", "board-row", "upsert", "75", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--section", "open", + "--category", "cli", + "--branch", "master", + "--tasks", "cq-75", + "--summary", "missing progress field", + "--focus", "focus", + "--validation", "pending", + "--dry-run", + ], env); + assertCondition(boardRowUpsertMissingField.status !== 0, "upsert add missing required generated cell should fail", boardRowUpsertMissingField.json ?? { stdout: boardRowUpsertMissingField.stdout, stderr: boardRowUpsertMissingField.stderr }); + const boardRowUpsertMissingFieldData = failedDataOf(boardRowUpsertMissingField.json ?? {}); + const boardRowUpsertMissingFieldDetails = boardRowUpsertMissingFieldData.details as JsonRecord; + assertCondition(String(boardRowUpsertMissingFieldDetails.message ?? "").includes("requires values") && Array.isArray(boardRowUpsertMissingFieldData.missingFields) && (boardRowUpsertMissingFieldData.missingFields as unknown[]).includes("progress"), "upsert missing field should be structured", boardRowUpsertMissingFieldData); + + const boardRowUpsertColumnMismatch = await runCli([ + "gh", "issue", "board-row", "upsert", "79", + "--repo", "pikasTech/unidesk", + "--board-issue", "62", + "--focus", "bad existing row", + "--dry-run", + ], env); + assertCondition(boardRowUpsertColumnMismatch.status !== 0, "upsert existing row with column mismatch should fail", boardRowUpsertColumnMismatch.json ?? { stdout: boardRowUpsertColumnMismatch.stdout, stderr: boardRowUpsertColumnMismatch.stderr }); + const boardRowUpsertColumnMismatchData = failedDataOf(boardRowUpsertColumnMismatch.json ?? {}); + assertCondition(String((boardRowUpsertColumnMismatchData.details as JsonRecord).message ?? "").includes("column count"), "upsert column mismatch should be structured", boardRowUpsertColumnMismatchData); + const boardRowDryRunRequestCountBefore = mock.requests.length; const boardRowDryRun = await runCli(["gh", "issue", "board-row", "update", "35", "--repo", "pikasTech/unidesk", "--board-issue", "20", "--field", "focus", "--value", "复核 A | B\nsecond line"], env); assertCondition(boardRowDryRun.status === 0, "board-row update should default to dry-run without concurrency expectation", boardRowDryRun.json ?? { stdout: boardRowDryRun.stdout, stderr: boardRowDryRun.stderr }); @@ -1078,6 +1295,7 @@ export async function runGhCliIssueGuardContract(): Promise<JsonRecord> { "issue cleanup-plan remains dry-run with body/comment cleanup suggestions", "issue board-audit reports missing open rows, closed/open section mismatches, missing closed rows, meta/brief-index ignores, and row validation warnings without writes", "issue board-row list/get expose parsed #20 rows without writes", + "issue board-row upsert updates existing rows, adds missing rows, reports operation, preserves table trailers, rejects ambiguous rows, blocks stale body SHA writes, and stays dry-run without concurrency guards", "issue board-row add/delete without guard stay on dry-run and do not PATCH", "issue board-row update defaults to dry-run, reports old/new row, body SHA, guard result, and does not introduce literal backslash-n", "issue board-row update rejects literal backslash-n cell values", diff --git a/scripts/src/gh.ts b/scripts/src/gh.ts index 6b52b96b..8e221b20 100644 --- a/scripts/src/gh.ts +++ b/scripts/src/gh.ts @@ -16,6 +16,7 @@ const COMMANDER_BRIEF_TARGET_ISSUE = 24; const DEFAULT_BOARD_KNOWN_META_ISSUES = [CODE_QUEUE_BOARD_TARGET_ISSUE, COMMANDER_BRIEF_TARGET_ISSUE] as const; const BOARD_AUDIT_REQUIRED_COLUMNS = ["branch", "acceptance", "relatedTask", "progress"] as const; const BOARD_ROW_FIELDS = ["progress", "status", "validation", "branch", "tasks", "focus"] as const; +const BOARD_ROW_UPSERT_TEXT_FIELDS = ["category", "branch", "tasks", "summary", "focus", "validation", "progress"] as const; const ISSUE_VIEW_JSON_FIELDS = ["body", "title", "state", "comments", "number", "url", "author", "createdAt", "updatedAt"] as const; const ISSUE_LIST_JSON_FIELDS = ["number", "title", "state", "url", "updatedAt", "createdAt", "author", "labels"] as const; const PR_JSON_FIELDS = ["body", "title", "state", "number", "url", "author", "head", "base", "draft", "createdAt", "updatedAt"] as const; @@ -56,8 +57,10 @@ type EscapeBodyKind = "issue-body" | "comment-body"; type CleanupSuggestionAction = "rewrite-issue-body-with-body-file" | "review-comment-manually" | "review-body-length" | "no-cleanup-needed"; type BoardSectionKind = "open" | "closed"; type BoardRequiredColumn = typeof BOARD_AUDIT_REQUIRED_COLUMNS[number]; -type BoardColumnKind = BoardRequiredColumn | "focus" | "githubStatus"; +type BoardColumnKind = BoardRequiredColumn | "focus" | "githubStatus" | "category" | "summary"; type BoardRowField = typeof BOARD_ROW_FIELDS[number]; +type BoardRowUpsertTextField = typeof BOARD_ROW_UPSERT_TEXT_FIELDS[number]; +type BoardRowUpsertField = BoardRowUpsertTextField | "status"; type BoardIgnoreReason = "known-meta" | "ignored" | "brief-index-managed"; type GitHubDegradedReason = @@ -255,6 +258,17 @@ interface BoardRowMutationPlanResult { newBody: string; } +interface BoardRowUpsertValues { + category?: string; + branch?: string; + tasks?: string; + summary?: string; + focus?: string; + validation?: string; + progress?: string; + status?: BoardGithubStatus; +} + interface GitHubCommandResult { ok: boolean; repo: string; @@ -305,6 +319,7 @@ interface GitHubOptions { boardSection?: BoardMutationSection; boardMoveTo?: BoardMutationSection; boardGithubStatus?: BoardGithubStatus; + boardRowUpsertValues: BoardRowUpsertValues; } interface IssueProfileValidationContext { @@ -548,8 +563,21 @@ function parseBoardRowField(args: string[]): BoardRowField | undefined { return validateEnumValue("--field", raw, BOARD_ROW_FIELDS); } +function parseBoardRowUpsertValues(args: string[]): BoardRowUpsertValues { + return { + category: optionValue(args, "--category"), + branch: optionValue(args, "--branch"), + tasks: optionValue(args, "--tasks"), + summary: optionValue(args, "--summary"), + focus: optionValue(args, "--focus"), + validation: optionValue(args, "--validation"), + progress: optionValue(args, "--progress"), + status: parseBoardGithubStatus(args), + }; +} + function validateKnownOptions(args: string[]): void { - const valueOptions = new Set(["--repo", "--limit", "--board-issue", "--known-meta-issue", "--ignore-issue", "--title", "--body-file", "--body", "--base", "--head", "--json", "--state", "--mode", "--expect-updated-at", "--expect-body-sha", "--body-profile", "--label", "--field", "--value", "--section", "--to", "--status", "--row-file"]); + const valueOptions = new Set(["--repo", "--limit", "--board-issue", "--known-meta-issue", "--ignore-issue", "--title", "--body-file", "--body", "--base", "--head", "--json", "--state", "--mode", "--expect-updated-at", "--expect-body-sha", "--body-profile", "--label", "--field", "--value", "--section", "--to", "--status", "--row-file", "--category", "--branch", "--tasks", "--summary", "--focus", "--validation", "--progress"]); const flagOptions = new Set(["--dry-run", "--draft", "--notify-claudeqq-brief-diff", "--allow-short-body"]); for (let index = 0; index < args.length; index += 1) { const arg = args[index]; @@ -597,6 +625,7 @@ function parseOptions(args: string[]): GitHubOptions { boardSection: parseBoardMutationSection(args, "--section"), boardMoveTo: parseBoardMutationSection(args, "--to"), boardGithubStatus: parseBoardGithubStatus(args), + boardRowUpsertValues: parseBoardRowUpsertValues(args), }; } @@ -1312,10 +1341,12 @@ function normalizeBoardHeader(header: string): string { function boardHeaderColumnKind(header: string): BoardColumnKind | null { const normalized = normalizeBoardHeader(header); + if (["category", "类别", "分类", "类型", "任务类型"].includes(normalized)) return "category"; if (["branch", "分支", "目标分支", "工作分支"].includes(normalized)) return "branch"; if (["acceptance", "验收", "验收状态", "验收结果", "验收标准"].includes(normalized)) return "acceptance"; if (["relatedtask", "task", "codequeue", "codequeuetask", "相关任务", "任务", "codequeue任务", "cq任务", "相关codequeue任务", "相关codequeuetask"].includes(normalized)) return "relatedTask"; if (["githubstatus", "githubstate", "github状态", "githubissue状态", "issuestate", "issue状态", "issuegithub状态", "开闭状态", "openclosed", "openclosed状态"].includes(normalized)) return "githubStatus"; + if (["summary", "摘要", "概述", "任务摘要", "任务概述", "标题"].includes(normalized)) return "summary"; if (["focus", "currentfocus", "关注点", "当前关注点", "当前focus"].includes(normalized)) return "focus"; if (["progress", "进度", "状态", "当前进度"].includes(normalized)) return "progress"; return null; @@ -1602,6 +1633,25 @@ function boardRowFieldValues(section: BoardTableSection, row: BoardTableRow): Re }; } +function boardRowUpsertFieldValues(section: BoardTableSection, row: BoardTableRow): Record<BoardRowUpsertField, string | null> { + const columnMap = boardColumnIndexMap(section.headers); + const valueFor = (kind: BoardColumnKind): string | null => { + const index = columnMap.get(kind); + return index === undefined ? null : row.cells[index] ?? ""; + }; + const acceptance = valueFor("acceptance"); + return { + category: valueFor("category"), + branch: valueFor("branch"), + tasks: valueFor("relatedTask"), + summary: valueFor("summary"), + focus: valueFor("focus"), + validation: acceptance, + progress: valueFor("progress"), + status: valueFor("githubStatus"), + }; +} + function boardRowSummary(section: BoardTableSection, row: BoardTableRow): Record<string, unknown> { return { issueNumber: row.issueNumber, @@ -1617,6 +1667,13 @@ function boardRowSummary(section: BoardTableSection, row: BoardTableRow): Record }; } +function boardRowsExactMatch( + sections: BoardTableSection[], + issueNumber: number, +): Array<{ section: BoardTableSection; row: BoardTableRow }> { + return boardRowsForState(sections, "all").filter(({ row }) => row.issueNumber === issueNumber); +} + function boardRowsForState(sections: BoardTableSection[], state: IssueListState): Array<{ section: BoardTableSection; row: BoardTableRow }> { return sections .filter((section) => state === "all" || section.kind === state) @@ -1922,6 +1979,456 @@ function boardRowStatusConsistency( return { ok: true, githubStatusColumnIndex, actualStatus, expectedStatus }; } +function boardRowUpsertValueEntries(values: BoardRowUpsertValues): Array<{ field: BoardRowUpsertField; value: string }> { + const entries: Array<{ field: BoardRowUpsertField; value: string }> = []; + for (const field of BOARD_ROW_UPSERT_TEXT_FIELDS) { + const value = values[field]; + if (value !== undefined) entries.push({ field, value }); + } + if (values.status !== undefined) entries.push({ field: "status", value: values.status }); + return entries; +} + +function boardColumnKindForUpsertField(field: BoardRowUpsertField): BoardColumnKind { + if (field === "category") return "category"; + if (field === "branch") return "branch"; + if (field === "tasks") return "relatedTask"; + if (field === "summary") return "summary"; + if (field === "focus") return "focus"; + if (field === "validation") return "acceptance"; + if (field === "status") return "githubStatus"; + return "progress"; +} + +function renderBoardIssueCell(repo: string, issueNumber: number, summary: string | undefined): string { + const trimmed = (summary ?? "").trim(); + if (trimmed.length === 0) return `#${issueNumber}`; + const targetHref = `https://github.com/${repo}/issues/${issueNumber}`; + const firstMarkdownIssue = /^\s*\[[^\]]*\]\(([^)]*)\)/u.exec(trimmed)?.[1] ?? ""; + if (new RegExp(`/issues/${issueNumber}(?:\\b|$)`, "u").test(firstMarkdownIssue)) return trimmed; + return `[#${issueNumber}](${targetHref}) ${trimmed}`; +} + +function boardRowUpsertTargetColumn( + repo: string, + commandName: string, + section: BoardTableSection, + issueNumber: number, + field: BoardRowUpsertField, +): { ok: true; columnIndex: number; targetColumn: BoardColumnKind | "issue"; usesIssueCell: boolean } | GitHubCommandFailure { + const columnMap = boardColumnIndexMap(section.headers); + if (field === "summary") { + const summaryIndex = columnMap.get("summary"); + if (summaryIndex !== undefined) return { ok: true, columnIndex: summaryIndex, targetColumn: "summary", usesIssueCell: false }; + const issueColumnIndex = boardIssueColumnIndex(section.headers); + if (issueColumnIndex !== null) return { ok: true, columnIndex: issueColumnIndex, targetColumn: "issue", usesIssueCell: true }; + } + const targetColumn = boardColumnKindForUpsertField(field); + const columnIndex = columnMap.get(targetColumn); + if (columnIndex === undefined) { + return validationError(commandName, repo, `board table does not contain a column for --${field}`, { + issueNumber, + field, + targetColumn, + section: section.kind, + headers: section.headers, + }) as GitHubCommandFailure; + } + return { ok: true, columnIndex, targetColumn, usesIssueCell: false }; +} + +function boardRowUpsertRenderedValue( + repo: string, + issueNumber: number, + field: BoardRowUpsertField, + value: string, + targetColumn: BoardColumnKind | "issue", +): string { + if (field === "summary" && targetColumn === "issue") return renderBoardIssueCell(repo, issueNumber, value); + return value; +} + +function boardRowUpsertPollutionFailure( + repo: string, + commandName: string, + issueNumber: number, + values: BoardRowUpsertValues, +): GitHubCommandFailure | null { + const findings = BOARD_ROW_UPSERT_TEXT_FIELDS + .map((field) => { + const value = values[field]; + if (value === undefined) return null; + const evidence = boardRowValuePollutionEvidence(value); + return evidence.length === 0 ? null : { field, valuePreview: preview(value), evidence }; + }) + .filter((item): item is { field: BoardRowUpsertTextField; valuePreview: string; evidence: string[] } => item !== null); + if (findings.length === 0) return null; + return validationError(commandName, repo, "issue board-row upsert field value contains literal shell escape text that would pollute a board cell; pass real newlines or plain text instead", { + issueNumber, + shellPollution: { suspected: true, findings }, + }) as GitHubCommandFailure; +} + +function boardRowUpsertUpdatePlan( + repo: string, + boardIssue: GitHubIssue, + issueNumber: number, + found: { section: BoardTableSection; row: BoardTableRow }, + values: BoardRowUpsertValues, + requestedSection: BoardMutationSection | undefined, + parsed: { sections: BoardTableSection[]; warnings: BoardRowValidationWarning[] }, +): BoardRowMutationPlanResult | GitHubCommandFailure { + const commandName = "issue board-row upsert"; + const { section, row } = found; + if (requestedSection !== undefined && requestedSection !== section.kind) { + return validationError(commandName, repo, `--section ${requestedSection} conflicts with existing row in ${section.kind}; use gh issue board-row move for section migration`, { + issueNumber, + requestedSection, + existingSection: section.kind, + moveCommand: `bun scripts/cli.ts gh issue board-row move ${issueNumber} --board-issue ${boardIssue.number} --to ${requestedSection}`, + }) as GitHubCommandFailure; + } + if (values.status !== undefined) { + const expectedStatus = expectedBoardGithubStatus(section.kind); + if (values.status !== expectedStatus) { + return validationError(commandName, repo, `--status ${values.status} conflicts with existing ${section.kind.toUpperCase()} section; use gh issue board-row move for section migration`, { + issueNumber, + existingSection: section.kind, + requestedStatus: values.status, + expectedStatus, + moveCommand: `bun scripts/cli.ts gh issue board-row move ${issueNumber} --board-issue ${boardIssue.number} --to ${values.status === "OPEN" ? "open" : "closed"} --status ${values.status}`, + }) as GitHubCommandFailure; + } + } + const entries = boardRowUpsertValueEntries(values); + if (entries.length === 0) { + return validationError(commandName, repo, "issue board-row upsert found an existing row but no upsert fields were provided", { + issueNumber, + existingSection: section.kind, + supportedFields: ["--category", "--branch", "--tasks", "--summary", "--focus", "--validation", "--progress", "--status"], + }) as GitHubCommandFailure; + } + if (row.cells.length !== section.headers.length) { + return validationError(commandName, repo, "existing row column count does not match the board table header", { + issueNumber, + section: section.kind, + expectedColumns: section.headers.length, + actualColumns: row.cells.length, + headers: section.headers, + lineNumber: row.lineNumber, + rowPreview: preview(row.raw), + }) as GitHubCommandFailure; + } + const oldCells = row.cells.slice(); + const newCells = oldCells.slice(); + const changedFields: Record<string, unknown>[] = []; + for (const entry of entries) { + const target = boardRowUpsertTargetColumn(repo, commandName, section, issueNumber, entry.field); + if (target.ok === false) return target; + const newValue = boardRowUpsertRenderedValue(repo, issueNumber, entry.field, entry.value, target.targetColumn); + const oldValue = oldCells[target.columnIndex] ?? ""; + newCells[target.columnIndex] = newValue; + changedFields.push({ + field: entry.field, + targetColumn: target.targetColumn, + targetColumnIndex: target.columnIndex, + requestedValue: entry.value, + oldValue, + newValue, + changed: oldValue !== newValue, + }); + } + const newRow = renderMarkdownTableRow(newCells); + const oldBody = boardIssue.body ?? ""; + let newBody: string; + try { + newBody = replaceBoardBodyLine(oldBody, row.lineNumber, newRow); + } catch (error) { + return validationError(commandName, repo, error instanceof Error ? error.message : String(error), { + issueNumber, + lineNumber: row.lineNumber, + }) as GitHubCommandFailure; + } + return { + ok: true, + newBody, + plan: { + repo, + boardIssue: boardIssue.number, + issueNumber, + operation: "update", + action: "update", + section: section.kind, + lineNumber: row.lineNumber, + requestedSection: requestedSection ?? null, + providedFields: entries.map((entry) => entry.field), + changedFields, + oldRow: row.raw, + newRow, + oldCells, + newCells, + row: { + old: boardRowSummary(section, row), + new: { + ...boardRowSummary(section, { ...row, raw: newRow, cells: newCells }), + upsertFields: boardRowUpsertFieldValues(section, { ...row, raw: newRow, cells: newCells }), + }, + }, + linePlan: { + action: "replace", + section: section.kind, + lineNumber: row.lineNumber, + }, + sectionPlan: { + kind: section.kind, + heading: section.heading, + headerLine: section.headerLine, + rowCount: section.rows.length, + }, + body: { + oldBodyChars: oldBody.length, + oldBodySha: bodySha(oldBody), + newBodyChars: newBody.length, + newBodySha: bodySha(newBody), + changed: oldBody !== newBody, + }, + tableParser: { + reused: "parseBoardTables", + rowValidationWarnings: parsed.warnings.length, + }, + request: { + method: "PATCH", + path: `/repos/{owner}/{repo}/issues/${boardIssue.number}`, + body: { bodyChars: newBody.length }, + }, + }, + }; +} + +function boardRowUpsertAddPlan( + repo: string, + boardIssue: GitHubIssue, + issueNumber: number, + sectionKind: BoardMutationSection, + values: BoardRowUpsertValues, + parsed: { sections: BoardTableSection[]; warnings: BoardRowValidationWarning[] }, +): BoardRowMutationPlanResult | GitHubCommandFailure { + const commandName = "issue board-row upsert"; + const targetLookup = targetBoardSection(repo, parsed.sections, sectionKind, commandName); + if (targetLookup.ok === false) return targetLookup; + const target = targetLookup.section; + const issueColumnIndex = boardIssueColumnIndex(target.headers); + if (issueColumnIndex === null) { + return validationError(commandName, repo, "board table does not contain an Issue column required for generated upsert rows", { + boardIssue: boardIssue.number, + section: sectionKind, + headers: target.headers, + }) as GitHubCommandFailure; + } + const columnMap = boardColumnIndexMap(target.headers); + const githubStatusColumnIndex = columnMap.get("githubStatus"); + if (githubStatusColumnIndex === undefined) { + return validationError(commandName, repo, "board table does not contain a GitHub 状态 column required for generated upsert rows", { + boardIssue: boardIssue.number, + section: sectionKind, + headers: target.headers, + }) as GitHubCommandFailure; + } + const expectedStatus = expectedBoardGithubStatus(sectionKind); + const requestedStatus = values.status ?? expectedStatus; + if (requestedStatus !== expectedStatus) { + return validationError(commandName, repo, `--status ${requestedStatus} conflicts with --section ${sectionKind}; expected ${expectedStatus}`, { + issueNumber, + section: sectionKind, + requestedStatus, + expectedStatus, + }) as GitHubCommandFailure; + } + const appliedFields = new Set<BoardRowUpsertField>(); + const missingFields: BoardRowUpsertTextField[] = []; + const unsupportedColumns: Array<{ index: number; header: string }> = []; + const summaryColumnIndex = columnMap.get("summary"); + const cells = target.headers.map((header, index) => { + if (index === issueColumnIndex) { + if (summaryColumnIndex === undefined && values.summary !== undefined) appliedFields.add("summary"); + return summaryColumnIndex === undefined ? renderBoardIssueCell(repo, issueNumber, values.summary) : `#${issueNumber}`; + } + const kind = boardHeaderColumnKind(header); + if (kind === "githubStatus") { + if (values.status !== undefined) appliedFields.add("status"); + return requestedStatus; + } + const valueFor = (field: BoardRowUpsertTextField, value: string | undefined): string => { + if (value === undefined) { + missingFields.push(field); + return ""; + } + appliedFields.add(field); + return value; + }; + if (kind === "category") return valueFor("category", values.category); + if (kind === "branch") return valueFor("branch", values.branch); + if (kind === "relatedTask") return valueFor("tasks", values.tasks); + if (kind === "summary") return valueFor("summary", values.summary); + if (kind === "focus") return valueFor("focus", values.focus); + if (kind === "acceptance") return valueFor("validation", values.validation); + if (kind === "progress") return valueFor("progress", values.progress); + unsupportedColumns.push({ index, header }); + return ""; + }); + if (unsupportedColumns.length > 0) { + return validationError(commandName, repo, "target board table contains unsupported column(s) for generated upsert rows", { + issueNumber, + section: sectionKind, + unsupportedColumns, + headers: target.headers, + }) as GitHubCommandFailure; + } + const unappliedFields = boardRowUpsertValueEntries(values) + .map((entry) => entry.field) + .filter((field) => !appliedFields.has(field)); + if (unappliedFields.length > 0) { + return validationError(commandName, repo, "target board table does not contain column(s) for supplied upsert field(s)", { + issueNumber, + section: sectionKind, + unappliedFields, + headers: target.headers, + }) as GitHubCommandFailure; + } + const uniqueMissingFields = Array.from(new Set(missingFields)); + if (uniqueMissingFields.length > 0) { + return validationError(commandName, repo, "issue board-row upsert add requires values for every generated row column", { + issueNumber, + section: sectionKind, + missingFields: uniqueMissingFields, + requiredOptions: uniqueMissingFields.map((field) => `--${field}`), + headers: target.headers, + }) as GitHubCommandFailure; + } + const newRow = renderMarkdownTableRow(cells); + const row = boardRowFromCells(target, newRow, cells, 0); + if (row.issueNumber !== issueNumber) { + return validationError(commandName, repo, "generated Issue column does not match the requested issue number", { + issueNumber, + issueColumnIndex, + issueCell: cells[issueColumnIndex] ?? "", + detectedIssueNumber: row.issueNumber, + rowPreview: preview(newRow), + }) as GitHubCommandFailure; + } + const actualStatus = normalizeBoardGithubStatusCell(cells[githubStatusColumnIndex]); + if (actualStatus !== expectedStatus) { + return validationError(commandName, repo, "generated GitHub 状态 column does not match the target section", { + issueNumber, + section: sectionKind, + expectedStatus, + actualStatus, + statusColumnIndex: githubStatusColumnIndex, + statusCell: cells[githubStatusColumnIndex] ?? "", + rowPreview: preview(newRow), + }) as GitHubCommandFailure; + } + const oldBody = boardIssue.body ?? ""; + const insertAfterLine = boardSectionInsertAfterLine(target); + let newBody: string; + try { + newBody = insertBoardBodyLineAfter(oldBody, insertAfterLine, newRow); + } catch (error) { + return validationError(commandName, repo, error instanceof Error ? error.message : String(error), { + issueNumber, + section: sectionKind, + insertAfterLine, + }) as GitHubCommandFailure; + } + return { + ok: true, + newBody, + plan: { + repo, + boardIssue: boardIssue.number, + issueNumber, + operation: "add", + action: "add", + section: sectionKind, + insertAfterLine, + providedFields: boardRowUpsertValueEntries(values).map((entry) => entry.field), + newRow, + newCells: cells, + row: { + old: null, + new: { + ...boardRowSummary(target, { ...row, lineNumber: insertAfterLine + 1 }), + upsertFields: boardRowUpsertFieldValues(target, { ...row, lineNumber: insertAfterLine + 1 }), + }, + }, + linePlan: { + action: "insert", + section: sectionKind, + insertAfterLine, + newLineNumber: insertAfterLine + 1, + }, + sectionPlan: { + kind: sectionKind, + heading: target.heading, + headerLine: target.headerLine, + rowCount: target.rows.length, + }, + validation: { + issueColumnIndex, + githubStatusColumnIndex, + expectedStatus, + actualStatus, + columnCount: cells.length, + }, + body: { + oldBodyChars: oldBody.length, + oldBodySha: bodySha(oldBody), + newBodyChars: newBody.length, + newBodySha: bodySha(newBody), + changed: oldBody !== newBody, + }, + tableParser: { + reused: "parseBoardTables", + rowValidationWarnings: parsed.warnings.length, + }, + request: { + method: "PATCH", + path: `/repos/{owner}/{repo}/issues/${boardIssue.number}`, + body: { bodyChars: newBody.length }, + }, + }, + }; +} + +function boardRowUpsertPlan( + repo: string, + boardIssue: GitHubIssue, + issueNumber: number, + options: GitHubOptions, + parsed: { sections: BoardTableSection[]; warnings: BoardRowValidationWarning[] }, +): BoardRowMutationPlanResult | GitHubCommandFailure { + const commandName = "issue board-row upsert"; + const pollutionFailure = boardRowUpsertPollutionFailure(repo, commandName, issueNumber, options.boardRowUpsertValues); + if (pollutionFailure !== null) return pollutionFailure; + const matches = boardRowsExactMatch(parsed.sections, issueNumber); + if (matches.length > 1) { + return validationError(commandName, repo, `board row for issue #${issueNumber} is ambiguous; refusing upsert`, { + issueNumber, + matches: matches.map(({ section, row }) => ({ section: section.kind, lineNumber: row.lineNumber, rowPreview: preview(row.raw) })), + }) as GitHubCommandFailure; + } + if (matches.length === 1) { + return boardRowUpsertUpdatePlan(repo, boardIssue, issueNumber, matches[0], options.boardRowUpsertValues, options.boardSection, parsed); + } + if (options.boardSection === undefined) { + return validationError(commandName, repo, "issue board-row upsert add requires --section open|closed when the row does not already exist", { + issueNumber, + supportedSections: BOARD_MUTATION_SECTIONS.slice(), + }) as GitHubCommandFailure; + } + return boardRowUpsertAddPlan(repo, boardIssue, issueNumber, options.boardSection, options.boardRowUpsertValues, parsed); +} + function boardRowAddPlan( repo: string, boardIssue: GitHubIssue, @@ -2260,8 +2767,8 @@ async function issueBoardRowMutation( token: string, issueNumber: number, options: GitHubOptions, - commandName: "issue board-row add" | "issue board-row move" | "issue board-row delete", - mutationKey: "add" | "move" | "delete", + commandName: "issue board-row add" | "issue board-row move" | "issue board-row delete" | "issue board-row upsert", + mutationKey: "add" | "move" | "delete" | "upsert", buildPlan: (boardIssue: GitHubIssue, parsed: { sections: BoardTableSection[]; warnings: BoardRowValidationWarning[] }) => BoardRowMutationPlanResult | GitHubCommandFailure, ): Promise<GitHubCommandResult> { const concurrencyOptionError = assertConcurrencyOptions(options, commandName); @@ -2289,6 +2796,7 @@ async function issueBoardRowMutation( updatedAt: boardIssue.updated_at ?? null, }, issueNumber, + operation: typeof planned.plan.operation === "string" ? planned.plan.operation : mutationKey, dryRun: effectiveDryRun, planned: true, [mutationKey]: planned.plan, @@ -2519,6 +3027,19 @@ async function issueBoardRowAdd(repo: string, token: string, issueNumber: number ); } +async function issueBoardRowUpsert(repo: string, token: string, issueNumber: number, options: GitHubOptions): Promise<GitHubCommandResult> { + const commandName = "issue board-row upsert"; + return issueBoardRowMutation( + repo, + token, + issueNumber, + options, + commandName, + "upsert", + (boardIssue, parsed) => boardRowUpsertPlan(repo, boardIssue, issueNumber, options, parsed), + ); +} + async function issueBoardRowMove(repo: string, token: string, issueNumber: number, options: GitHubOptions): Promise<GitHubCommandResult> { const commandName = "issue board-row move"; if (options.boardMoveTo === undefined) return validationError(commandName, repo, "issue board-row move requires --to open|closed", { issueNumber, supportedTargets: BOARD_MUTATION_SECTIONS.slice() }); @@ -4071,6 +4592,7 @@ export function ghHelp(): unknown { "bun scripts/cli.ts gh issue board-row get <issueNumber> [--repo owner/name] --board-issue 20", "bun scripts/cli.ts gh issue board-row update <issueNumber> [--repo owner/name] --board-issue 20 --field progress|status|validation|branch|tasks|focus --value <text> [--dry-run] [--expect-updated-at ts|--expect-body-sha sha256]", "bun scripts/cli.ts gh issue board-row add <issueNumber> [--repo owner/name] --board-issue 20 --section open|closed --row-file <markdown-row-file> [--dry-run] [--expect-body-sha sha256]", + "bun scripts/cli.ts gh issue board-row upsert <issueNumber> [--repo owner/name] --board-issue 20 --section open|closed [--category text] --branch <branch> --tasks <task> --summary <text> --focus <text> --validation <text> --progress <text> [--status OPEN|CLOSED] [--dry-run] [--expect-updated-at ts|--expect-body-sha sha256]", "bun scripts/cli.ts gh issue board-row move <issueNumber> [--repo owner/name] --board-issue 20 --to open|closed [--status OPEN|CLOSED] [--dry-run] [--expect-body-sha sha256]", "bun scripts/cli.ts gh issue board-row delete <issueNumber> [--repo owner/name] --board-issue 20 [--dry-run] [--expect-body-sha sha256]", "bun scripts/cli.ts gh pr list [--repo owner/name] [--limit N] [--json number,title,state,url,updatedAt,createdAt,author,head,base,draft]", @@ -4101,6 +4623,7 @@ export function ghHelp(): unknown { "issue scan-escape classifies literal \\n findings as suspected-pollution, explanatory-mention, or risk, and emits cleanupSuggestions with body/comment ids plus diff-like previews. cleanup-plan is an alias that remains dry-run/read-only.", "issue board-audit is read-only and defaults to repo pikasTech/unidesk plus board issue #20. It compares GitHub open/closed issue lists with the board OPEN/CLOSED tables and reports missingOpenIssues, closedInOpenRows, missingClosedRows, rowValidationWarnings, ignoredIssues, and recommendedActions. When an Issue column exists, row.issueNumber is taken from that column; #20 and #24 are known meta issues by default. Daily rolling brief issues titled YYYY-MM-DD 指挥简报(北京时间) are managed by #20's brief index and appear in ignoredIssues with reason=brief-index-managed instead of missingOpenIssues.", "issue board-row list/get reuse the board-audit table parser and are read-only. board-row update changes one table cell by issue number, returns old/new row, body SHA, body guard and request plan, and defaults to dry-run unless --expect-updated-at or --expect-body-sha is supplied for the guarded PATCH. Field aliases map status and validation to the 验收状态 column, tasks to 相关 Code Queue 任务, and focus to 当前关注点.", + "issue board-row upsert updates an existing row when the issue is already present, or generates a complete row in --section open|closed when missing. It returns operation=update or operation=add, defaults to dry-run, requires --expect-body-sha or --expect-updated-at before PATCH, and refuses section migration; use board-row move for OPEN/CLOSED migration.", "issue board-row add/move/delete are row-scoped #20 table mutations. add validates a one-line --row-file against the target table column count, Issue column, and GitHub 状态 column; move refuses duplicate/ambiguous rows and can update GitHub 状态 via --status; delete removes only the matched row. All three default to dry-run and require --expect-body-sha or --expect-updated-at before PATCH. add/move/delete return old/new row, body SHA, and line/section plan details for the parsed table mutation.", "issue edit 24 --notify-claudeqq-brief-diff remains the legacy #24 notification helper: it reads the old issue body, PATCHes the new body, and sends only newly added '## 更新 ... 北京时间' sections to ClaudeQQ; ClaudeQQ failure does not roll back GitHub.", "Commander brief ClaudeQQ defaults to private target 645275593 through backend-core /api/microservices/claudeqq/proxy; UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_* env vars can override target, base URL, timeout, and enabled state.", @@ -4142,9 +4665,9 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh"; return validationError(command, options.repo, "--mode is only supported by gh issue update/edit and gh pr update"); } - if ((options.allowShortBody || options.expectUpdatedAt !== undefined || options.expectBodySha !== undefined || optionWasProvided(args, "--body-profile")) && !(top === "issue" && (sub === "edit" || sub === "update" || sub === "board-row" && ["update", "add", "move", "delete"].includes(third ?? "")))) { + if ((options.allowShortBody || options.expectUpdatedAt !== undefined || options.expectBodySha !== undefined || optionWasProvided(args, "--body-profile")) && !(top === "issue" && (sub === "edit" || sub === "update" || sub === "board-row" && ["update", "add", "move", "delete", "upsert"].includes(third ?? "")))) { const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh"; - return validationError(command, options.repo, "--allow-short-body, --expect-updated-at, --expect-body-sha, and --body-profile are only supported by gh issue update/edit and gh issue board-row update/add/move/delete"); + return validationError(command, options.repo, "--allow-short-body, --expect-updated-at, --expect-body-sha, and --body-profile are only supported by gh issue update/edit and gh issue board-row update/add/move/delete/upsert"); } if ((optionWasProvided(args, "--board-issue") || optionWasProvided(args, "--known-meta-issue") || optionWasProvided(args, "--ignore-issue")) && !(top === "issue" && (sub === "board-audit" || sub === "board-row"))) { const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh"; @@ -4162,13 +4685,21 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult const command = [top, sub, third].filter((value): value is string => value !== undefined).join(" ") || "gh"; return validationError(command, options.repo, "--row-file is only supported by gh issue board-row add"); } - if (optionWasProvided(args, "--section") && !(top === "issue" && sub === "board-row" && third === "add")) { + if (optionWasProvided(args, "--section") && !(top === "issue" && sub === "board-row" && (third === "add" || third === "upsert"))) { const command = [top, sub, third].filter((value): value is string => value !== undefined).join(" ") || "gh"; - return validationError(command, options.repo, "--section is only supported by gh issue board-row add"); + return validationError(command, options.repo, "--section is only supported by gh issue board-row add/upsert"); } - if ((optionWasProvided(args, "--to") || optionWasProvided(args, "--status")) && !(top === "issue" && sub === "board-row" && third === "move")) { + if (optionWasProvided(args, "--to") && !(top === "issue" && sub === "board-row" && third === "move")) { const command = [top, sub, third].filter((value): value is string => value !== undefined).join(" ") || "gh"; - return validationError(command, options.repo, "--to and --status are only supported by gh issue board-row move"); + return validationError(command, options.repo, "--to is only supported by gh issue board-row move"); + } + if (optionWasProvided(args, "--status") && !(top === "issue" && sub === "board-row" && (third === "move" || third === "upsert"))) { + const command = [top, sub, third].filter((value): value is string => value !== undefined).join(" ") || "gh"; + return validationError(command, options.repo, "--status is only supported by gh issue board-row move/upsert"); + } + if ((optionWasProvided(args, "--category") || optionWasProvided(args, "--branch") || optionWasProvided(args, "--tasks") || optionWasProvided(args, "--summary") || optionWasProvided(args, "--focus") || optionWasProvided(args, "--validation") || optionWasProvided(args, "--progress")) && !(top === "issue" && sub === "board-row" && third === "upsert")) { + const command = [top, sub, third].filter((value): value is string => value !== undefined).join(" ") || "gh"; + return validationError(command, options.repo, "--category, --branch, --tasks, --summary, --focus, --validation, and --progress are only supported by gh issue board-row upsert"); } if (optionWasProvided(args, "--label") && !(top === "issue" && sub === "create")) { const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh"; @@ -4213,8 +4744,8 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult if (sub === "board-row") { const action = third; const commandName = `issue board-row ${action ?? ""}`.trim(); - if (action !== "list" && action !== "get" && action !== "update" && action !== "add" && action !== "move" && action !== "delete") { - return unsupportedCommand(commandName, options.repo, "board-row supported commands are list, get, update, add, move, and delete."); + if (action !== "list" && action !== "get" && action !== "update" && action !== "add" && action !== "move" && action !== "delete" && action !== "upsert") { + return unsupportedCommand(commandName, options.repo, "board-row supported commands are list, get, update, add, move, delete, and upsert."); } const { token, probe } = resolveToken(true); const missing = authRequired(options.repo, commandName, probe); @@ -4225,6 +4756,7 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult if (action === "get") return issueBoardRowGet(options.repo, token, issueNumber, options); if (action === "update") return issueBoardRowUpdate(options.repo, token, issueNumber, options); if (action === "add") return issueBoardRowAdd(options.repo, token, issueNumber, options); + if (action === "upsert") return issueBoardRowUpsert(options.repo, token, issueNumber, options); if (action === "move") return issueBoardRowMove(options.repo, token, issueNumber, options); return issueBoardRowDelete(options.repo, token, issueNumber, options); }