Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): digest-pin Pi runtime cache, skip Pi in help oneShot / usage analyzer, fix Pi model fallback

Chris08be0a20ceee
diff --git a/apps/desktop/src/main/__tests__/helpRouting.test.ts b/apps/desktop/src/main/__tests__/helpRouting.test.ts
index b66fd9937c..17dabdb0b9 100644
--- a/apps/desktop/src/main/__tests__/helpRouting.test.ts
+++ b/apps/desktop/src/main/__tests__/helpRouting.test.ts
@@ -10,9 +10,10 @@ vi.mock('electron', () => ({
safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
}));
-import { buildRouterPrompt, parseRouterOutput } from '../maker-ipc/help';
+import { buildRouterPrompt, parseRouterOutput, pickHelpAgent } from '../maker-ipc/help';
import { HELP_KNOWLEDGE } from '../maker-ipc/helpKnowledge.generated';
import type { HelpMessage } from '../../shared/helpTypes';
+import type { AgentKind } from '@cindy/maker-core';
const KNOWN = new Set(HELP_KNOWLEDGE.map((d) => d.id));
@@ -40,6 +41,31 @@ describe('parseRouterOutput', () => {
});
});
+describe('pickHelpAgent', () => {
+ const makeMaker = (available: AgentKind[], authed: AgentKind[]) => ({
+ listAvailableAgents: () => available,
+ getAgentAuthState: async (kind: AgentKind) => ({ authenticated: authed.includes(kind) }),
+ }) as unknown as Parameters<typeof pickHelpAgent>[0];
+
+ it('never selects Pi for the help oneShot even when it is the most recent / only-authed agent', async () => {
+ // PiAgent 未实现 oneShot;选中它会让 HELP_ASK 抛 not-implemented 而 no-answer。
+ // 即便 Pi 是最近会话(preferred)且已鉴权,只要 Claude/Codex 兜底可用就应选它们。
+ await expect(
+ pickHelpAgent(makeMaker(['pi', 'codex'], ['pi', 'codex']), 'pi'),
+ ).resolves.toBe('codex');
+ // 机器上只有 Pi(且已鉴权)时,宁可返回 null 走 no-answer,也不选会抛错的 Pi。
+ await expect(
+ pickHelpAgent(makeMaker(['pi'], ['pi']), 'pi'),
+ ).resolves.toBeNull();
+ });
+
+ it('still honors a supported preferred agent over the static priority', async () => {
+ await expect(
+ pickHelpAgent(makeMaker(['claude-code', 'codex'], ['claude-code', 'codex']), 'codex'),
+ ).resolves.toBe('codex');
+ });
+});
+
describe('buildRouterPrompt', () => {
it('lists every topic id and includes the conversation', () => {
const history: HelpMessage[] = [{ role: 'user', content: 'how do I connect slack?' }];
diff --git a/apps/desktop/src/main/maker-ipc/help.ts b/apps/desktop/src/main/maker-ipc/help.ts
index 40f33dc4fc..9aec2a07da 100644
--- a/apps/desktop/src/main/maker-ipc/help.ts
+++ b/apps/desktop/src/main/maker-ipc/help.ts
@@ -254,13 +254,19 @@ async function getMostRecentSessionAgent(): Promise<AgentKind | null> {
}
}
-async function pickHelpAgent(
+// help 兜底走 maker.oneShot;目前仅 claude-code / codex 实现了它,PiAgent 继承 BaseAgent
+// 的 not-implemented。选中不支持 oneShot 的 agent 会让 HELP_ASK / 置顶摘要抛错并直接
+// no-answer,即便其它 agent 兜底仍可用。Pi 实现 oneShot 前从候选里剔除(实现后加回即可)。
+const HELP_ONESHOT_CAPABLE_AGENTS: ReadonlySet<AgentKind> = new Set(['claude-code', 'codex']);
+
+export async function pickHelpAgent(
maker: Maker,
preferredAgent: AgentKind | null,
): Promise<AgentKind | null> {
- const ordered: AgentKind[] = preferredAgent
+ const candidates: AgentKind[] = preferredAgent
? [...new Set<AgentKind>([preferredAgent, 'claude-code', 'codex', 'pi'])]
: ['claude-code', 'codex', 'pi'];
+ const ordered = candidates.filter((agentKind) => HELP_ONESHOT_CAPABLE_AGENTS.has(agentKind));
const available = new Set(maker.listAvailableAgents());
for (const agentKind of ordered) {
if (!available.has(agentKind)) continue;
diff --git a/apps/desktop/src/main/skillhub/__tests__/usageAnalyzer.test.ts b/apps/desktop/src/main/skillhub/__tests__/usageAnalyzer.test.ts
index 7b5bcdf0d3..4161de50e1 100644
--- a/apps/desktop/src/main/skillhub/__tests__/usageAnalyzer.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/usageAnalyzer.test.ts
@@ -284,6 +284,35 @@ describe('analyzeSkillUsageTranscript', () => {
});
});
+ it('does not mis-parse a Pi transcript as Codex (Pi is explicitly skipped, no exposures)', () => {
+ // Pi 原生转录格式与 Codex 不同;分析器不得把 agentKind:'pi' 回落到 Codex 解析器,
+ // 否则会静默产出错误归属的 exposure。喂一条 Codex 会识别为技能注入的行,agentKind
+ // 设为 pi → 必须 0 exposure(显式跳过,而非误当 Codex)。
+ const document = skillDocument('code-discipline', 'Use local patterns before editing.');
+ const result = analyzeSkillUsageTranscript({
+ agentKind: 'pi',
+ sessionId: 'pi-local',
+ sdkSessionId: '019ed673-c614-7ac1-8d22-c0ddc81f9cf0',
+ rawFilePath: '/agent-transcripts/pi/2026/06/18/skip.jsonl',
+ lines: [
+ codexLine({
+ type: 'response_item',
+ payload: {
+ type: 'message',
+ role: 'user',
+ content: [
+ {
+ type: 'input_text',
+ text: codexSkillInjection('code-discipline', '/agent-skill-roots/pi/code-discipline', document),
+ },
+ ],
+ },
+ }),
+ ],
+ });
+ expect(result.exposures).toEqual([]);
+ });
+
it('counts repeated tool calls only inside the active exposure window', () => {
const firstDocument = skillDocument('code-discipline', 'Use local patterns before editing.');
const secondDocument = skillDocument('systematic-debugging', 'Find the root cause first.');
diff --git a/apps/desktop/src/main/skillhub/usageAnalyzer.ts b/apps/desktop/src/main/skillhub/usageAnalyzer.ts
index a890b20845..8b1f1374f6 100644
--- a/apps/desktop/src/main/skillhub/usageAnalyzer.ts
+++ b/apps/desktop/src/main/skillhub/usageAnalyzer.ts
@@ -140,7 +140,7 @@ export function analyzeSkillUsageTranscript(input: SkillUsageTranscriptInput): S
pendingSkillReads,
repeatedToolSignaturesByExposureId: () => activeRepeatedToolSignatures,
});
- } else {
+ } else if (input.agentKind === 'codex') {
handleCodexRecord(obj, lineNo, timestamp, {
addExposure,
activeExposures: () => activeExposures,
@@ -149,6 +149,10 @@ export function analyzeSkillUsageTranscript(input: SkillUsageTranscriptInput): S
repeatedToolSignaturesByExposureId: () => activeRepeatedToolSignatures,
});
}
+ // Pi 原生转录用 `type:'message'` + `message.role` 的 entry 格式,与 Codex 的
+ // `event_msg`/payload 完全不同;没有专用解析器时**显式跳过**,而不是回落
+ // handleCodexRecord 误当 Codex 解析(会静默产出错误归属的 exposure)。Pi 使用分析
+ // (发现 pi-agent-home/sessions + 按 Pi 格式解析)是独立的后续工作。
}
return { exposures };
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index d8e338c567..82e6b58aaf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -2702,12 +2702,16 @@ export function CCAgentSessionView({
if (getSessionDeviceId(sessionId)) return;
const agent = displayAgentKind;
if (!shouldFallbackVendorModel(providers, sessionModel, agent)) return;
- const defaultModel = getDefaultModelForVendor(isCodex ? 'codex' : 'cc');
+ // 用三值化后的 agent 映射选默认模型:Pi 会话必须回退到 Pi 目录默认,而不是被
+ // `isCodex ? 'codex' : 'cc'` 误写成 CC 首选(可能是更贵的 Opus)(codex review)。
+ const defaultModel = getDefaultModelForVendor(
+ agent === 'pi' ? 'pi' : agent === 'codex' ? 'codex' : 'cc',
+ );
sessionService
.update(sessionId, { model: defaultModel.id })
.then(() => refreshServerSession())
.catch((err) => log.warn('vendor fallback patch failed:', err));
- }, [isCodex, providers, refreshServerSession, sessionAgentKind, sessionId, sessionModel]);
+ }, [displayAgentKind, providers, refreshServerSession, sessionAgentKind, sessionId, sessionModel]);
// 远程协同交接被 app 关闭打断时的兜底:把上次没能发出去的正文回填到输入框。
// 只回填、不自动补发(理由见 pendingFirstMessage 的「可恢复副本」注释)。
diff --git a/scripts/__tests__/pi-update-layout.test.mjs b/scripts/__tests__/pi-update-layout.test.mjs
index 3ec5b66963..8ad99ea9fa 100644
--- a/scripts/__tests__/pi-update-layout.test.mjs
+++ b/scripts/__tests__/pi-update-layout.test.mjs
@@ -4,7 +4,12 @@ import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
-import { assertPinnedRuntimeAsset, flattenExtractedDir } from '../../tools/pi/update.mjs';
+import {
+ assertPinnedRuntimeAsset,
+ assetDigestMatchesUpstream,
+ flattenExtractedDir,
+ readCachedAssetDigest,
+} from '../../tools/pi/update.mjs';
function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-pi-layout-'));
@@ -44,6 +49,25 @@ test('Pi release pin covers every supported desktop architecture', () => {
]);
});
+test('Pi updater re-verifies same-tag asset digest so a swapped upstream asset is not promoted from stale cache', (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const digest = 'c'.repeat(64);
+ fs.writeFileSync(path.join(dir, '.asset-digest.bin'), `sha256:${digest}\n`);
+
+ // 读回归一化(容忍 sha256: 前缀 / 大小写 / 结尾换行)。
+ assert.equal(readCachedAssetDigest(dir), digest);
+ assert.equal(readCachedAssetDigest(tempDir()), null); // 无标记(旧缓存)→ null
+
+ const asset = { digest: `sha256:${digest}` };
+ assert.equal(assetDigestMatchesUpstream(readCachedAssetDigest(dir), asset), true);
+ // 同 tag 资产被替换:上游 digest 变 → 不匹配,快速路径/跳过分支据此重下。
+ assert.equal(assetDigestMatchesUpstream(readCachedAssetDigest(dir), { digest: `sha256:${'d'.repeat(64)}` }), false);
+ // 缓存无标记 或 上游无 digest → 一律 false(fail-closed,重下核验)。
+ assert.equal(assetDigestMatchesUpstream(null, asset), false);
+ assert.equal(assetDigestMatchesUpstream(digest, { digest: undefined }), false);
+});
+
test('Pi updater rejects mutable release metadata that differs from the reviewed pin', () => {
const cache = {
version: '1.2.3',
diff --git a/tools/pi/update.mjs b/tools/pi/update.mjs
index 9423083e5a..e17745a783 100644
--- a/tools/pi/update.mjs
+++ b/tools/pi/update.mjs
@@ -42,6 +42,12 @@ const CACHE_FILE = path.join(__dirname, 'latest.json');
const UPDATES_DIR = path.join(__dirname, 'updates');
const BIN_DIR = path.join(PROJECT_ROOT, 'apps', 'pi-bin');
+// 每个平台缓存目录记录“产出该缓存的归档 digest”(归一 64-hex)。上游若在同一 tag 下替换
+// 资产(digest 变、版本号不变),快速路径与 downloadAsset 跳过分支据此重新核验并重下 ——
+// 否则会 promote 出与随后写入的 digest pin 不一致的旧缓存(codex review)。缺该标记(旧
+// 缓存)按“需重新核验”处理,重下一次即自愈。随 .sha256.bin 一起进目录清单。
+const ASSET_DIGEST_FILE = '.asset-digest.bin';
+
// 平台 → GitHub Release 资产文件名 + 归档内主执行文件名
const PLATFORMS = [
{ key: 'darwin-arm64', asset: 'pi-darwin-arm64.tar.gz', binFile: 'pi' },
@@ -136,6 +142,33 @@ function formatMB(bytes) {
return (bytes / 1024 / 1024).toFixed(1) + ' MB';
}
+/** 读取平台缓存目录记录的归档 digest(归一 64-hex);缺失/非法 → null。 */
+export function readCachedAssetDigest(destDir) {
+ try {
+ return normalizeExpectedSha256(fs.readFileSync(path.join(destDir, ASSET_DIGEST_FILE), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+/** 纯比较:缓存记录的归档 digest 是否与上游 release 资产 digest 一致(任一缺失即 false)。 */
+export function assetDigestMatchesUpstream(recordedDigest, asset) {
+ const upstream = normalizeExpectedSha256(asset?.digest);
+ const recorded = normalizeExpectedSha256(recordedDigest);
+ return !!upstream && !!recorded && recorded === upstream;
+}
+
+/** 所有目标平台缓存记录的归档 digest 都与上游一致(同 tag 资产被替换时会不一致)。 */
+function targetsMatchUpstreamDigest(meta, version, targets) {
+ return targets.every(({ key, asset: assetName }) => {
+ const asset = (meta.assets || []).find((candidate) => candidate.name === assetName);
+ return assetDigestMatchesUpstream(
+ readCachedAssetDigest(path.join(UPDATES_DIR, version, key)),
+ asset,
+ );
+ });
+}
+
const LFS_POINTER_HEADER = 'version https://git-lfs.github.com/spec/v1';
function isUsableCache(filePath) {
@@ -223,14 +256,20 @@ async function downloadAsset(meta, version, platformKey, assetName, finalBinName
// native prebuild 等旁侧资产(磁盘损坏/被误删),主二进制仍在也不能跳过 —— 否则
// promote 会把残缺目录打进安装包,且事后从残缺目录生成的 manifest 反而“自洽通过”
// (codex review)。这里对提取期写入的完整清单校验整目录,任一资产缺失即重下。
- if (fs.existsSync(sha256Path) && verifyDirDistManifest(destDir)) {
+ // 除主二进制自哈希 + 目录清单外,还须核验缓存记录的归档 digest 与当前上游一致:同 tag
+ // 资产被替换(digest 变、版本号不变)时,缓存对自身自洽却与上游 pin 不符,不能跳过。
+ if (
+ fs.existsSync(sha256Path)
+ && verifyDirDistManifest(destDir)
+ && assetDigestMatchesUpstream(readCachedAssetDigest(destDir), asset)
+ ) {
const storedHash = fs.readFileSync(sha256Path, 'utf8').trim();
verifyFileSha256OrRemove(finalBinPath, storedHash, `pi ${platformKey} binary v${version} (cached)`);
const size = fs.statSync(finalBinPath).size;
- console.log(` [${platformKey}] skip (cached, sha256 ok, manifest complete, ${formatMB(size)})`);
+ console.log(` [${platformKey}] skip (cached, sha256 ok, manifest complete, digest pinned, ${formatMB(size)})`);
return;
}
- console.log(` [${platformKey}] cache missing sha256 marker or incomplete asset manifest, re-downloading for verification...`);
+ console.log(` [${platformKey}] cache stale (missing sha256 marker / incomplete manifest / upstream digest changed), re-downloading for verification...`);
}
// 目录形态:重下前清空平台目录,避免旧版本资产残留混入新版本。
@@ -260,12 +299,18 @@ async function downloadAsset(meta, version, platformKey, assetName, finalBinName
}
try {
- verifyFileSha256OrRemove(tmpArchive, expectedDigest, `pi ${platformKey} asset ${assetName}@${version}`);
+ const verifiedDigest = verifyFileSha256OrRemove(
+ tmpArchive,
+ expectedDigest,
+ `pi ${platformKey} asset ${assetName}@${version}`,
+ );
console.log(` [${platformKey}] sha256 ok`);
await extractArchive(tmpArchive, destDir);
flattenExtractedDir(destDir, finalBinName);
fs.writeFileSync(finalBinPath + '.sha256.bin', sha256File(finalBinPath) + '\n');
+ // 记录产出该缓存的归档 digest,供后续快速路径 / 跳过分支对上游同 tag 资产替换做核验。
+ fs.writeFileSync(path.join(destDir, ASSET_DIGEST_FILE), verifiedDigest + '\n');
// 提取期(刚从已校验 digest 的归档解出、目录必然完整)写入清单,作为后续“缓存
// 是否完整”的权威基线;事后 promote 从残缺缓存再生成的清单不能当完整性依据。
writeDirDistManifest(destDir);
@@ -400,7 +445,15 @@ async function main() {
console.log(` Latest: ${latestVersion} (${meta.tag_name})`);
console.log(` Cached: ${cachedVersion ?? '(none)'}`);
- if (cachedVersion === latestVersion && !force && targetsExist(latestVersion, targets)) {
+ // 版本号相同还不够:同 tag 资产被替换(digest 变)时,缓存对自身自洽却与上游 pin 不符,
+ // 直接 promote 会打进与随后写入的 digest pin 不一致的旧 runtime。故快速路径额外要求每个
+ // 平台缓存记录的归档 digest 与当前上游一致,否则落到下载分支按新 digest 重下。
+ if (
+ cachedVersion === latestVersion
+ && !force
+ && targetsExist(latestVersion, targets)
+ && targetsMatchUpstreamDigest(meta, latestVersion, targets)
+ ) {
saveCache(meta, latestVersion);
promoteToVendorBin(latestVersion, targets);
console.log('==> Already up to date.');