Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ci): 协议指针必须已发布才放行,并兼容历史悬空指针 (#2059)
fmfsaisaibc4ba62c675d
diff --git a/scripts/__tests__/check-submodule-forward.test.mjs b/scripts/__tests__/check-submodule-forward.test.mjsindex 1be7546768..190d31984d 100644--- a/scripts/__tests__/check-submodule-forward.test.mjs+++ b/scripts/__tests__/check-submodule-forward.test.mjs@@ -5,14 +5,37 @@ import path from 'node:path';import { execFileSync } from 'node:child_process';import test from 'node:test';-import { classifyProtocolRelation } from '../check-submodule-forward.mjs';+import {+ classifyProtocolRelation,+ validatePublishedProtocolHead,+ validateSubmoduleForward,+} from '../check-submodule-forward.mjs';function git(repo, ...args) {return execFileSync('git', args, { cwd: repo, encoding: 'utf-8' }).trim();}+function commitTree(repo, tree, parent, message) {+ const args = ['commit-tree', tree];+ if (parent) args.push('-p', parent);+ return execFileSync('git', args, {+ cwd: repo,+ encoding: 'utf-8',+ input: `${message}\n`,+ env: {+ ...process.env,+ GIT_AUTHOR_NAME: 'Protocol Guard Test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Protocol Guard Test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ }).trim();+}+function fixture() {- const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-protocol-forward-'));+ const repo = fs.mkdtempSync(+ path.join(os.tmpdir(), 'cindy-protocol-forward-'),+ );git(repo, 'init', '-b', 'main');git(repo, 'config', 'user.name', 'Protocol Guard Test');git(repo, 'config', 'user.email', '[email protected]');@@ -31,6 +54,14 @@ function fixture() {return { repo, one, two, fork };}+function setPublishedMain(repo, oid) {+ git(repo, 'update-ref', 'refs/remotes/origin/main', oid);+}++function setPublishedTag(repo, name, oid) {+ git(repo, 'update-ref', `refs/tags/client-baseline-${name}`, oid);+}+test('classifies unchanged, forward, rollback and diverged protocol gitlinks', () => {const f = fixture();try {@@ -42,3 +73,272 @@ test('classifies unchanged, forward, rollback and diverged protocol gitlinks', (fs.rmSync(f.repo, { recursive: true, force: true });}});++test('accepts an unreachable base only for a strict equivalent ancestor', () => {+ const f = fixture();+ try {+ const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);+ const duplicate = commitTree(f.repo, tree, f.one, 'duplicate');+ const head = commitTree(f.repo, tree, duplicate, 'head');+ const baseOid = 'a'.repeat(40);+ const metadata = new Map([[baseOid, { parents: [f.one], tree }]]);+ assert.equal(+ classifyProtocolRelation(f.repo, baseOid, head, {+ unreachableBaseMetadata: metadata,+ }),+ 'forward',+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('accepts an available base with an equivalent head ancestor', () => {+ const f = fixture();+ try {+ const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);+ const duplicate = commitTree(f.repo, tree, null, 'duplicate');+ const head = commitTree(f.repo, tree, duplicate, 'head');+ assert.equal(classifyProtocolRelation(f.repo, f.one, head), 'forward');+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('rejects matching tree when the parent list differs', () => {+ const f = fixture();+ try {+ const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);+ const candidate = commitTree(+ f.repo,+ tree,+ f.one,+ 'same tree, different parent',+ );+ const baseOid = 'b'.repeat(40);+ const metadata = new Map([[baseOid, { parents: [f.two], tree }]]);+ assert.throws(+ () =>+ classifyProtocolRelation(f.repo, baseOid, candidate, {+ unreachableBaseMetadata: metadata,+ }),+ /无法读取协议 base commit/,+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('classifies reachable same-tree different-parent history as diverged', () => {+ const f = fixture();+ try {+ const tree = git(f.repo, 'rev-parse', `${f.two}^{tree}`);+ const duplicate = commitTree(+ f.repo,+ git(f.repo, 'rev-parse', `${f.one}^{tree}`),+ null,+ 'duplicate root',+ );+ const candidate = commitTree(+ f.repo,+ tree,+ duplicate,+ 'same tree, different parent',+ );+ assert.equal(+ classifyProtocolRelation(f.repo, f.two, candidate),+ 'diverged',+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('rejects a feature-only head before ancestry classification', () => {+ const f = fixture();+ try {+ setPublishedMain(f.repo, f.two);+ assert.throws(+ () => validatePublishedProtocolHead(f.repo, f.fork, { ci: false }),+ /未合入协议仓 main,也未打 client-baseline tag/,+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('allows a head published on protocol main', () => {+ const f = fixture();+ try {+ setPublishedMain(f.repo, f.two);+ assert.doesNotThrow(() =>+ validatePublishedProtocolHead(f.repo, f.two, { ci: false }),+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('allows a head published only by a client-baseline tag', () => {+ const f = fixture();+ try {+ setPublishedMain(f.repo, f.one);+ setPublishedTag(f.repo, 'feature', f.fork);+ assert.doesNotThrow(() =>+ validatePublishedProtocolHead(f.repo, f.fork, { ci: false }),+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('fetches a published head missing from the local protocol clone', () => {+ const publisher = fixture();+ const bare = fs.mkdtempSync(+ path.join(os.tmpdir(), 'cindy-protocol-published-'),+ );+ const local = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-protocol-local-'));+ try {+ git(bare, 'init', '--bare');+ git(publisher.repo, 'remote', 'add', 'origin', bare);+ git(publisher.repo, 'push', 'origin', 'main');+ git(local, 'init', '-b', 'main');+ git(local, 'remote', 'add', 'origin', bare);+ git(local, 'fetch', 'origin', publisher.one);+ assert.throws(() =>+ git(local, 'cat-file', '-e', `${publisher.two}^{commit}`),+ );+ assert.doesNotThrow(() =>+ validatePublishedProtocolHead(local, publisher.two, { ci: true }),+ );+ } finally {+ fs.rmSync(publisher.repo, { recursive: true, force: true });+ fs.rmSync(bare, { recursive: true, force: true });+ fs.rmSync(local, { recursive: true, force: true });+ }+});++test('falls back to local origin/main when baseline fetch is unavailable', () => {+ const f = fixture();+ try {+ setPublishedMain(f.repo, f.two);+ git(f.repo, 'remote', 'add', 'origin', '/definitely/missing/protocol.git');+ const warnings = [];+ assert.doesNotThrow(() =>+ validatePublishedProtocolHead(f.repo, f.two, {+ ci: false,+ warn: (message) => warnings.push(message),+ }),+ );+ assert.equal(warnings.length, 1);+ assert.match(warnings[0], /退用本地 origin\/main/);+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('fails closed when an unavailable base cannot be fetched', () => {+ const f = fixture();+ try {+ const baseOid = 'c'.repeat(40);+ assert.throws(+ () => classifyProtocolRelation(f.repo, baseOid, f.two),+ /无法读取协议 base commit/,+ );+ } finally {+ fs.rmSync(f.repo, { recursive: true, force: true });+ }+});++test('validateSubmoduleForward does not treat a failed base fetch as forward', () => {+ const outer = fs.mkdtempSync(+ path.join(os.tmpdir(), 'cindy-protocol-forward-parent-'),+ );+ const protocol = path.join(outer, 'cindy-protocol');+ fs.mkdirSync(protocol);+ try {+ git(outer, 'init', '-b', 'main');+ git(outer, 'config', 'user.name', 'Protocol Guard Test');+ git(outer, 'config', 'user.email', '[email protected]');+ git(protocol, 'init', '-b', 'main');+ git(protocol, 'config', 'user.name', 'Protocol Guard Test');+ git(protocol, 'config', 'user.email', '[email protected]');+ fs.writeFileSync(path.join(protocol, 'protocol.txt'), 'head\n');+ git(protocol, 'add', '.');+ git(protocol, 'commit', '-m', 'head');+ const head = git(protocol, 'rev-parse', 'HEAD');+ setPublishedMain(protocol, head);+ const base = 'd'.repeat(40);+ git(+ outer,+ 'update-index',+ '--add',+ '--cacheinfo',+ `160000,${base},cindy-protocol`,+ );+ git(outer, 'commit', '-m', 'base');+ git(+ outer,+ 'update-index',+ '--add',+ '--cacheinfo',+ `160000,${head},cindy-protocol`,+ );+ git(outer, 'commit', '-m', 'head');+ const warnings = [];+ assert.throws(+ () =>+ validateSubmoduleForward(outer, 'HEAD~1', 'HEAD', {+ ci: false,+ warn: (message) => warnings.push(message),+ }),+ /无法读取协议 base commit/,+ );+ assert.equal(warnings.length, 1);+ } finally {+ fs.rmSync(outer, { recursive: true, force: true });+ }+});++test('allows the unchanged dangling historical baseline without fetching it', () => {+ const outer = fs.mkdtempSync(+ path.join(os.tmpdir(), 'cindy-protocol-unchanged-dangling-'),+ );+ const protocol = path.join(outer, 'cindy-protocol');+ fs.mkdirSync(protocol);+ try {+ git(outer, 'init', '-b', 'main');+ git(outer, 'config', 'user.name', 'Protocol Guard Test');+ git(outer, 'config', 'user.email', '[email protected]');+ git(protocol, 'init', '-b', 'main');+ git(+ protocol,+ 'remote',+ 'add',+ 'origin',+ '/definitely/missing/protocol.git',+ );+ const dangling = '27ef29dcb0df1b0f346c82cb7fbb81e9da536a79';+ assert.throws(() =>+ git(protocol, 'cat-file', '-e', `${dangling}^{commit}`),+ );+ git(+ outer,+ 'update-index',+ '--add',+ '--cacheinfo',+ `160000,${dangling},cindy-protocol`,+ );+ git(outer, 'commit', '-m', 'dangling baseline');++ assert.deepEqual(validateSubmoduleForward(outer, 'HEAD', 'HEAD'), {+ baseRef: 'HEAD',+ headRef: 'HEAD',+ baseOid: dangling,+ headOid: dangling,+ relation: 'unchanged',+ });+ } finally {+ fs.rmSync(outer, { recursive: true, force: true });+ }+});diff --git a/scripts/check-submodule-forward.mjs b/scripts/check-submodule-forward.mjsindex 9c3b345e39..6330ea80af 100644--- a/scripts/check-submodule-forward.mjs+++ b/scripts/check-submodule-forward.mjs@@ -6,6 +6,20 @@ import { fileURLToPath } from 'node:url';const SUBMODULE_PATH = 'cindy-protocol';+// 27ef29d was a historical duplicate of e6c95b0. The published-head guard below+// prevents future gitlinks from depending on unpublished commits, so this map+// must not grow. Keep this one verified entry only to move the already-dangling+// main baseline onto the equivalent published history.+const UNREACHABLE_BASE_COMMITS = new Map([+ [+ '27ef29dcb0df1b0f346c82cb7fbb81e9da536a79',+ {+ parents: ['0cb87cb52427fbebd8a3d85a271847d06bfb2ac6'],+ tree: '2b38c6510e36f5c95de9b58b683e0e9c3c896b94',+ },+ ],+]);+function git(cwd, args, { allowFailure = false } = {}) {const result = spawnSync('git', args, {cwd,@@ -14,14 +28,18 @@ function git(cwd, args, { allowFailure = false } = {}) {});if (!allowFailure && result.status !== 0) {const detail = (result.stderr || result.stdout || '').trim();- throw new Error(`git ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`);+ throw new Error(+ `git ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`,+ );}return result;}export function readGitlink(repoRoot, ref, submodulePath = SUBMODULE_PATH) {const result = git(repoRoot, ['ls-tree', ref, '--', submodulePath]);- const match = result.stdout.trim().match(/^160000 commit ([0-9a-f]{40})\t(.+)$/i);+ const match = result.stdout+ .trim()+ .match(/^160000 commit ([0-9a-f]{40})\t(.+)$/i);if (!match || match[2] !== submodulePath) {throw new Error(`${ref} 中缺少合法的 ${submodulePath} gitlink`);}@@ -35,29 +53,232 @@ function isAncestor(repoRoot, older, newer) {if (result.status === 0) return true;if (result.status === 1) return false;const detail = (result.stderr || result.stdout || '').trim();- throw new Error(`无法比较协议历史 ${older.slice(0, 10)}..${newer.slice(0, 10)}${detail ? `: ${detail}` : ''}`);+ throw new Error(+ `无法比较协议历史 ${older.slice(0, 10)}..${newer.slice(0, 10)}${detail ? `: ${detail}` : ''}`,+ );+}++function hasCommit(repoRoot, oid) {+ return (+ git(repoRoot, ['cat-file', '-e', `${oid}^{commit}`], {+ allowFailure: true,+ }).status === 0+ );+}++function hasRef(repoRoot, ref) {+ return (+ git(repoRoot, ['show-ref', '--verify', '--quiet', ref], {+ allowFailure: true,+ }).status === 0+ );+}++function readPublishedBaselineRefs(protocolRepo) {+ const refs = [];+ if (hasRef(protocolRepo, 'refs/remotes/origin/main')) {+ refs.push('refs/remotes/origin/main');+ }+ const tags = git(protocolRepo, [+ 'for-each-ref',+ '--format=%(refname)',+ 'refs/tags/client-baseline-*',+ ])+ .stdout.trim()+ .split('\n')+ .filter(Boolean);+ return refs.concat(tags);+}++function refreshPublishedBaselines(protocolRepo, { ci, warn }) {+ const mainFetch = git(+ protocolRepo,+ ['fetch', '--no-tags', 'origin', 'main:refs/remotes/origin/main'],+ { allowFailure: true },+ );+ const tagFetch = git(+ protocolRepo,+ [+ 'fetch',+ '--no-tags',+ 'origin',+ 'refs/tags/client-baseline-*:refs/tags/client-baseline-*',+ ],+ { allowFailure: true },+ );+ if (mainFetch.status === 0 && tagFetch.status === 0) return;++ const detail = [mainFetch, tagFetch]+ .filter((result) => result.status !== 0)+ .map((result) => (result.stderr || result.stdout || '').trim())+ .filter(Boolean)+ .join('; ');+ if (ci || !hasRef(protocolRepo, 'refs/remotes/origin/main')) {+ throw new Error(`无法刷新协议仓公开基线${detail ? `: ${detail}` : ''}`);+ }+ warn(+ `无法刷新协议仓公开基线,退用本地 origin/main 与已有 client-baseline tags${detail ? `: ${detail}` : ''}`,+ );+}++export function validatePublishedProtocolHead(+ protocolRepo,+ headOid,+ { ci = Boolean(process.env.CI), warn = console.warn } = {},+) {+ refreshPublishedBaselines(protocolRepo, { ci, warn });+ if (!hasCommit(protocolRepo, headOid)) {+ const headFetch = git(+ protocolRepo,+ ['fetch', '--no-tags', 'origin', headOid],+ { allowFailure: true },+ );+ if (!hasCommit(protocolRepo, headOid)) {+ const detail = (headFetch.stderr || headFetch.stdout || '').trim();+ throw new Error(+ `无法读取协议 head commit ${headOid}${detail ? `: ${detail}` : ''}`,+ );+ }+ }+ const baselineRefs = readPublishedBaselineRefs(protocolRepo);+ if (baselineRefs.some((ref) => isAncestor(protocolRepo, headOid, ref))) {+ return;+ }+ throw new Error(+ `协议提交 ${headOid} 未合入协议仓 main,也未打 client-baseline tag;先完成协议仓发布再更新 gitlink`,+ );+}++function parseCommitMetadata(output) {+ const [oid, tree, parents = ''] = output.split('\0');+ return { oid, tree, parents: parents ? parents.split(' ') : [] };+}++function readCommitMetadata(protocolRepo, oid) {+ const result = git(protocolRepo, [+ 'show',+ '-s',+ '--format=%H%x00%T%x00%P%x00',+ oid,+ ]);+ const metadata = parseCommitMetadata(result.stdout.trimEnd());+ return { tree: metadata.tree, parents: metadata.parents };+}++function readAncestorMetadata(protocolRepo, headOid) {+ const result = git(protocolRepo, [+ 'log',+ '--format=%H%x00%T%x00%P%x01',+ headOid,+ ]);+ return result.stdout+ .trimEnd()+ .split('\x01')+ .filter(Boolean)+ .map(parseCommitMetadata);}-export function classifyProtocolRelation(protocolRepo, baseOid, headOid) {+function hasEquivalentAncestor(+ protocolRepo,+ baseOid,+ headOid,+ metadata = UNREACHABLE_BASE_COMMITS,+) {+ const expected =+ git(protocolRepo, ['cat-file', '-e', `${baseOid}^{commit}`], {+ allowFailure: true,+ }).status === 0+ ? readCommitMetadata(protocolRepo, baseOid)+ : metadata.get(baseOid);+ if (!expected) return false;++ return readAncestorMetadata(protocolRepo, headOid).some((candidate) => {+ if (candidate.oid === baseOid) return false;+ return (+ candidate.tree === expected.tree &&+ candidate.parents.length === expected.parents.length &&+ candidate.parents.every(+ (parent, index) => parent === expected.parents[index],+ )+ );+ });+}++export function classifyProtocolRelation(+ protocolRepo,+ baseOid,+ headOid,+ { unreachableBaseMetadata = UNREACHABLE_BASE_COMMITS } = {},+) {if (baseOid === headOid) return 'unchanged';+ const baseAvailable =+ git(protocolRepo, ['cat-file', '-e', `${baseOid}^{commit}`], {+ allowFailure: true,+ }).status === 0;+ if (+ !baseAvailable &&+ hasEquivalentAncestor(+ protocolRepo,+ baseOid,+ headOid,+ unreachableBaseMetadata,+ )+ )+ return 'forward';+ if (!baseAvailable) throw new Error(`无法读取协议 base commit ${baseOid}`);if (isAncestor(protocolRepo, baseOid, headOid)) return 'forward';if (isAncestor(protocolRepo, headOid, baseOid)) return 'rollback';+ if (+ hasEquivalentAncestor(+ protocolRepo,+ baseOid,+ headOid,+ unreachableBaseMetadata,+ )+ )+ return 'forward';return 'diverged';}-function ensureCommit(protocolRepo, oid) {- if (git(protocolRepo, ['cat-file', '-e', `${oid}^{commit}`], { allowFailure: true }).status === 0) {- return;+function ensureCommit(+ protocolRepo,+ oid,+ { allowUnreachableBase = false } = {},+) {+ if (+ git(protocolRepo, ['cat-file', '-e', `${oid}^{commit}`], {+ allowFailure: true,+ }).status === 0+ ) {+ return true;}- git(protocolRepo, ['fetch', '--no-tags', 'origin', oid]);+ if (allowUnreachableBase && UNREACHABLE_BASE_COMMITS.has(oid)) return false;+ return (+ git(protocolRepo, ['fetch', '--no-tags', 'origin', oid], {+ allowFailure: true,+ }).status === 0+ );}-export function validateSubmoduleForward(repoRoot, baseRef, headRef = 'HEAD') {+export function validateSubmoduleForward(+ repoRoot,+ baseRef,+ headRef = 'HEAD',+ options = {},+) {const baseOid = readGitlink(repoRoot, baseRef);const headOid = readGitlink(repoRoot, headRef);const protocolRepo = path.join(repoRoot, SUBMODULE_PATH);- ensureCommit(protocolRepo, baseOid);- ensureCommit(protocolRepo, headOid);+ const unchangedHistoricalBaseline =+ baseOid === headOid && UNREACHABLE_BASE_COMMITS.has(headOid);+ if (unchangedHistoricalBaseline) {+ return { baseRef, headRef, baseOid, headOid, relation: 'unchanged' };+ }+ validatePublishedProtocolHead(protocolRepo, headOid, options);+ ensureCommit(protocolRepo, baseOid, { allowUnreachableBase: true });+ if (!ensureCommit(protocolRepo, headOid)) {+ throw new Error(`无法准备协议 head commit ${headOid}`);+ }const relation = classifyProtocolRelation(protocolRepo, baseOid, headOid);return { baseRef, headRef, baseOid, headOid, relation };}@@ -68,18 +289,27 @@ function main() {const result = validateSubmoduleForward(repoRoot, baseRef);const summary = `${result.baseOid.slice(0, 10)} -> ${result.headOid.slice(0, 10)}`;if (result.relation === 'rollback') {- console.error(`::error file=cindy-protocol::cindy-protocol gitlink 回退: ${summary}`);+ console.error(+ `::error file=cindy-protocol::cindy-protocol gitlink 回退: ${summary}`,+ );process.exitCode = 1;return;}if (result.relation === 'diverged') {- console.error(`::error file=cindy-protocol::cindy-protocol gitlink 与 base 分叉: ${summary}`);+ console.error(+ `::error file=cindy-protocol::cindy-protocol gitlink 与 base 分叉: ${summary}`,+ );process.exitCode = 1;return;}- console.log(`cindy-protocol gitlink ${result.relation === 'forward' ? '前进' : '未变化'}: ${summary}`);+ console.log(+ `cindy-protocol gitlink ${result.relation === 'forward' ? '前进' : '未变化'}: ${summary}`,+ );}-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+if (+ process.argv[1] &&+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)+) {main();}