Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): bound background diagnostics and polling memory (#4759)
DavidShenXD500ca7e7b875
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.tsindex 5423006ab6..bc010c7ca0 100644--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts@@ -238,7 +238,7 @@ describe('passive shared-userData instance auth isolation', () => {expect(bootstrapSource).not.toContain('await prepareSharedGlobalSkillLinks();');expect(bootstrapSource).not.toContain('refreshBuiltInSharedSkillLinks');- const start = authAdapterSource.indexOf('private async runEnsureSharedGlobalSkills():');+ const start = authAdapterSource.indexOf('private async runEnsureSharedGlobalSkills(ownerId:');const end = authAdapterSource.indexOf('\n async getState(', start);const body = authAdapterSource.slice(start, end);const ownerBoundary = body.indexOf('withSharedGlobalSkillProjectionMutation(ownerId');diff --git a/apps/desktop/src/main/__tests__/boundedLogWriter.test.ts b/apps/desktop/src/main/__tests__/boundedLogWriter.test.tsnew file mode 100644index 0000000000..445231e47b--- /dev/null+++ b/apps/desktop/src/main/__tests__/boundedLogWriter.test.ts@@ -0,0 +1,47 @@+import { Writable } from 'node:stream';+import { describe, expect, it } from 'vitest';+import { BoundedLogWriter } from '../bounded-log-writer.js';++describe('log output budgets', () => {+ it('honors drain rather than interpreting false as a rejected write', async () => {+ let complete!: () => void;+ const stream = new Writable({ highWaterMark: 4, write(_chunk, _encoding, cb) { complete = cb; } });+ const writer = new BoundedLogWriter(16);+ expect(writer.write(stream, '1234')).toBe(true);+ expect(writer.write(stream, '5678')).toBe(false);+ expect(stream.writableLength).toBe(4);+ complete();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(writer.write(stream, '5678')).toBe(true);+ complete(); stream.destroy();+ });++ it('shares its byte budget with retired streams and releases it on completion', async () => {+ let complete!: () => void;+ const retired = new Writable({ write(_chunk, _encoding, cb) { complete = cb; } });+ const current = new Writable({ write(_chunk, _encoding, cb) { cb(); } });+ const writer = new BoundedLogWriter(8);+ expect(writer.write(retired, '12345678')).toBe(true);+ retired.end();+ expect(writer.write(current, 'next')).toBe(false);+ complete();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(writer.write(current, 'next')).toBe(true);+ current.destroy();+ });++ it('also bounds tiny pending records and accounts for failed writes', async () => {+ const completions: Array<(error?: Error | null) => void> = [];+ const streams = Array.from({ length: 3 }, () => new Writable({+ write(_chunk, _encoding, cb) { completions.push(cb); },+ }).on('error', () => undefined));+ const writer = new BoundedLogWriter(1024, 2);+ expect(writer.write(streams[0], 'x')).toBe(true);+ expect(writer.write(streams[1], 'x')).toBe(true);+ expect(writer.write(streams[2], 'x')).toBe(false);+ completions[0](new Error('disk failed'));+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(writer.write(streams[2], 'x')).toBe(true);+ for (const stream of streams) stream.destroy();+ });+});diff --git a/apps/desktop/src/main/__tests__/ccDebugRawTailer.test.ts b/apps/desktop/src/main/__tests__/ccDebugRawTailer.test.tsnew file mode 100644index 0000000000..220f766b4c--- /dev/null+++ b/apps/desktop/src/main/__tests__/ccDebugRawTailer.test.ts@@ -0,0 +1,143 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { CcDebugRawTailer } from '../cc-debug-raw-tailer.js';++let root: string;+let sequence = 0;+beforeAll(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-raw-tail-')); });+afterAll(() => { fs.rmSync(root, { recursive: true, force: true }); });+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });+function file(initial = ''): string {+ const name = path.join(root, `${sequence++}.log`);+ fs.writeFileSync(name, initial);+ return name;+}++describe('bounded raw diagnostics', () => {+ it('skips historical bytes but captures the first append before the first poll', () => {+ const name = file('old\n');+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write);+ tailer.register(name, 'session');+ fs.appendFileSync(name, 'first\npartial');+ tailer.pollNow();+ fs.appendFileSync(name, ' line\n');+ tailer.pollNow();+ expect(write.mock.calls).toEqual([['first', 'session'], ['partial line', 'session']]);+ });++ it('does not enumerate history and stops disk polling when disabled', () => {+ vi.useFakeTimers();+ const name = file();+ const tailer = new CcDebugRawTailer(() => true);+ tailer.register(name, 'session');+ const open = vi.spyOn(fs, 'openSync');+ const readdir = vi.spyOn(fs, 'readdirSync');+ vi.advanceTimersByTime(10_000);+ expect(open).not.toHaveBeenCalled();+ tailer.setEnabled(true);+ vi.advanceTimersByTime(2_000);+ expect(open).toHaveBeenCalledTimes(1);+ tailer.setEnabled(false);+ vi.advanceTimersByTime(10_000);+ expect(open).toHaveBeenCalledTimes(1);+ expect(readdir).not.toHaveBeenCalled();+ });++ it('shares a round budget fairly across files and bounds the allocation for a huge append', () => {+ const a = file(); const b = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write, 8);+ tailer.register(a, 'a'); tailer.register(b, 'b');+ fs.appendFileSync(a, 'aaa\naaa\n'.repeat(1000));+ fs.appendFileSync(b, 'bbb\n');+ const alloc = vi.spyOn(Buffer, 'allocUnsafe');+ tailer.pollNow();+ expect(write.mock.calls.every((call) => call[1] === 'a')).toBe(true);+ tailer.pollNow();+ expect(write).toHaveBeenCalledWith('bbb', 'b');+ expect(Math.max(...alloc.mock.calls.map(([bytes]) => bytes))).toBeLessThanOrEqual(8);+ });++ it('fragments an unterminated line instead of keeping its entire history', () => {+ const name = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write);+ tailer.register(name, 's');+ for (let i = 0; i < 20; i++) {+ fs.appendFileSync(name, 'x'.repeat(64 * 1024));+ tailer.pollNow();+ }+ expect(write).toHaveBeenCalledTimes(20);+ expect(write.mock.calls.every(([line]) => line.length < 65_600)).toBe(true);+ });++ it('pauses reads behind the writer and retries without dropping or duplicating lines', () => {+ const name = file();+ let ready = false;+ const lines: string[] = [];+ const tailer = new CcDebugRawTailer((line) => { if (!ready) return false; lines.push(line); return true; });+ tailer.register(name, 's');+ fs.appendFileSync(name, 'one\ntwo\n');+ tailer.pollNow();+ const read = vi.spyOn(fs, 'readSync');+ tailer.pollNow();+ expect(read).not.toHaveBeenCalled();+ ready = true;+ tailer.pollNow();+ tailer.pollNow();+ expect(lines).toEqual(['one', 'two']);+ });++ it('decodes multibyte characters split across polls', () => {+ const name = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write, 2);+ tailer.register(name, 's');+ fs.appendFileSync(name, '你好\n');+ for (let i = 0; i < 5; i++) tailer.pollNow();+ expect(write).toHaveBeenCalledExactlyOnceWith('你好', 's');+ });++ it('keeps shared writers until the last release and then forgets the file', () => {+ const name = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write);+ const releaseA = tailer.register(name, 's');+ const releaseB = tailer.register(name, 's');+ releaseA(); releaseA();+ fs.appendFileSync(name, 'live\n');+ tailer.pollNow();+ expect(write).toHaveBeenCalledWith('live', 's');+ releaseB();+ const open = vi.spyOn(fs, 'openSync');+ tailer.pollNow();+ expect(open).not.toHaveBeenCalled();+ });++ it('clears partial text when a file disappears and follows its replacement from zero', () => {+ const name = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write);+ tailer.register(name, 's');+ fs.appendFileSync(name, 'partial'); tailer.pollNow();+ fs.unlinkSync(name); tailer.pollNow();+ fs.writeFileSync(name, 'replacement\n'); tailer.pollNow();+ expect(write.mock.calls).toEqual([['replacement', 's']]);+ });++ it('handles truncate and isolates one read failure from other writers', () => {+ const a = file('old data'); const b = file();+ const write = vi.fn((_line: string, _sessionId: string) => true);+ const tailer = new CcDebugRawTailer(write);+ tailer.register(a, 'a'); tailer.register(b, 'b');+ fs.writeFileSync(a, 'a\n'); fs.appendFileSync(b, 'b\n');+ vi.spyOn(fs, 'readSync').mockImplementationOnce(() => { throw new Error('read failed'); });+ expect(() => tailer.pollNow()).not.toThrow();+ tailer.pollNow();+ expect(write).toHaveBeenCalledWith('a', 'a');+ expect(write).toHaveBeenCalledWith('b', 'b');+ });+});diff --git a/apps/desktop/src/main/__tests__/loggerBackpressure.test.ts b/apps/desktop/src/main/__tests__/loggerBackpressure.test.tsnew file mode 100644index 0000000000..40a6fd886b--- /dev/null+++ b/apps/desktop/src/main/__tests__/loggerBackpressure.test.ts@@ -0,0 +1,54 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { Writable } from 'node:stream';+import { expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ app: { isPackaged: true, getVersion: () => 'test', getPath: () => '' },+}));++import { createLogger, initLogger, writeCcDebugLine } from '../logger.js';++it('bounds outstanding writes across session eviction and stops opening streams while saturated', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-log-backpressure-'));+ const streams: Writable[] = [];+ const completions: Array<() => void> = [];+ const records: string[] = [];+ const open = vi.spyOn(fs, 'createWriteStream').mockImplementation((file) => {+ const agent = String(file).endsWith('.ndjson');+ const stream = new Writable({+ write(chunk, _encoding, done) {+ if (agent) { records.push(String(chunk)); completions.push(done); }+ else done();+ },+ });+ streams.push(stream);+ return stream as fs.WriteStream;+ });+ try {+ initLogger({ isDev: false, level: 'trace', logDir: root });+ const line = 'x'.repeat(32 * 1024);+ let accepted = 0;+ for (let i = 0; i < 256; i++) {+ if (writeCcDebugLine(line, `session-${i}`)) accepted++;+ }+ expect(accepted).toBeGreaterThan(32); // Includes streams retired from the LRU.+ expect(accepted).toBeLessThan(128);+ expect(records.reduce((sum, record) => sum + Buffer.byteLength(record), 0)).toBeLessThanOrEqual(4 * 1024 * 1024);+ const opened = open.mock.calls.length;+ for (let i = 0; i < 256; i++) expect(writeCcDebugLine(line, `more-${i}`)).toBe(false);+ expect(open).toHaveBeenCalledTimes(opened);+ // Synchronous producers cannot retry; the next accepted record reports loss.+ createLogger('maker').info(line);+ for (const complete of completions.splice(0)) complete();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(writeCcDebugLine('recovered', 'recovery')).toBe(true);+ expect(JSON.parse(records.at(-1)!)).toMatchObject({ msg: 'recovered', droppedRecords: 1 });+ } finally {+ for (const complete of completions.splice(0)) complete();+ for (const stream of streams) stream.destroy();+ open.mockRestore();+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex d29f83903c..0c5d2a4ecc 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1530,7 +1530,7 @@ import {keepRecentSync,keepRecentSessionCcDebugSync,createLogger,- writeCcDebugLine,+ setCcDebugTailingEnabled,type LogLevel,} from './logger.js';initLogger();@@ -5482,87 +5482,12 @@ const registerIpcHandlers = () => {}// per-session raw (sessions/<id>/cc-debug.raw.log) 同样在启动期砍头保尾 —— 它不经 emit,// 平时只靠 cleanupOldSessions 30 天整目录删, 期间一个开着 NODE_DEBUG 的活跃 session 能把单个- // raw 写爆磁盘。内容已被下面的 tailer 汇入 <date>.ndjson, raw 只是中转, 砍掉旧头不丢有效信息。+ // raw 写爆磁盘。tailer 尽量汇入 <date>.ndjson;背压或进程退出时未汇入的部分仍留在 raw。keepRecentSessionCcDebugSync();- // cc-debug.raw.log → 统一 agent 流 (agent-<date>.ndjson, source=cc-debug):- // cc 子进程通过 SDK debugFile 直接 fopen 写 raw, 不经 logger; 这里轮询读增量,- // 逐行调 writeCcDebugLine() 解析行首 UTC-ISO 时间戳后归一化写入当天 agent 流,- // 跟 maker / proxy 两源合并、共用按天 rotate + 保留策略。- //- // - 轮询 2s: cc-debug 不是高频热点, 不需要 fs.watch 的实时性 (排序按解析出的 ts,- // 不受 2s 轮询延迟影响, 延迟只影响"多久可见")- // - cc 持有 fd 期间我们 rotate 不掉 raw 文件 (Windows rename 失败, Linux truncate- // 留稀疏空洞, 都不安全), 所以反向走 ─ 读出内容汇入 agent 流, raw 仅启动期 trim- // - 检测到文件 size 倒退 (truncate / 启动 rename), 重置 read offset 从 0 开始- // - 跨读保留尾部不完整行, 跟下一段拼起来再切, 不切坏 multi-line 信息- // - timer.unref() 防止进程关闭时被卡住- // per-file tail 状态: filePath → { offset, leftover }。同时 tail 全局 fallback raw- // (无 sessionId 的 cc, 罕见) + 各 sessions/<id>/cc-debug.raw.log; sessionId 从路径- // 提取后传给 writeCcDebugLine, 让 cc 网络 debug 归到对应 session 的 <date>.ndjson。- const ccLogRootDir = path.dirname(ccDebugLogPath);- const ccTailState = new Map<string, { offset: number; leftover: string }>();-- function tailOneCcFile(filePath: string, sessionId: string): void {- let stat: fs.Stats;- try {- stat = fs.statSync(filePath);- } catch {- return;- }- const st = ccTailState.get(filePath);- if (!st) {- // 首次发现: 从当前末尾开始, 跳过已有内容 (避免 app 重启后把旧 session 的 raw 重复- // 灌进 ndjson)。代价是漏掉文件被发现前 ≤ 轮询间隔 的几行初始 cc 日志, 可接受。- ccTailState.set(filePath, { offset: stat.size, leftover: '' });- return;- }- if (stat.size < st.offset) {- st.offset = 0;- st.leftover = '';- }- if (stat.size === st.offset) return;- let fd: number;- try {- fd = fs.openSync(filePath, 'r');- } catch {- return;- }- try {- const len = stat.size - st.offset;- const buf = Buffer.alloc(len);- fs.readSync(fd, buf, 0, len, st.offset);- st.offset = stat.size;- st.leftover += buf.toString('utf8');- const lines = st.leftover.split('\n');- st.leftover = lines.pop() ?? '';- for (const line of lines) {- if (line.length > 0) writeCcDebugLine(line, sessionId);- }- } finally {- try {- fs.closeSync(fd);- } catch {- /* ignore */- }- }- }-- function tailCcDebugOnce(): void {- tailOneCcFile(ccDebugLogPath, ''); // 全局 fallback (无 sessionId 的 cc)- const sessionsBase = path.join(ccLogRootDir, 'sessions');- let dirs: fs.Dirent[];- try {- dirs = fs.readdirSync(sessionsBase, { withFileTypes: true });- } catch {- return;- }- for (const d of dirs) {- if (!d.isDirectory()) continue;- tailOneCcFile(path.join(sessionsBase, d.name, 'cc-debug.raw.log'), d.name);- }- }- setInterval(tailCcDebugOnce, 2000).unref();+ // Current-process CC writers register on spawn and release on exit.+ // The tailer has a shared read budget and pauses behind the NDJSON writer.+ setCcDebugTailingEnabled(process.env.XDT_CC_DEBUG_NET === '1');// dev 模式不再启动期硬开(2026-07-11 Lizi 定案):NODE_DEBUG=http,https,net,tls// 会顺着 cc 子进程继承进 agent 的 Bash 子命令——所有命令输出被调试日志刷屏,@@ -5596,6 +5521,7 @@ const registerIpcHandlers = () => {levelBeforeDebugNet = null;}}+ setCcDebugTailingEnabled(enabled);ccDebugNetLog.info(`set ${enabled ? 'on' : 'off'} via renderer`);return { ok: true };});diff --git a/apps/desktop/src/main/bounded-log-writer.ts b/apps/desktop/src/main/bounded-log-writer.tsnew file mode 100644index 0000000000..5f8a4c9ad2--- /dev/null+++ b/apps/desktop/src/main/bounded-log-writer.ts@@ -0,0 +1,35 @@+import type { Writable } from 'node:stream';++/** Accounts for outstanding writes, including streams already evicted by the slot LRU. */+export class BoundedLogWriter {+ private bytes = 0;+ private records = 0;++ constructor(private readonly maxBytes = 4 * 1024 * 1024, private readonly maxRecords = 4096) {}++ canAccept(line: string): boolean {+ return this.bytes + Buffer.byteLength(line) <= this.maxBytes && this.records < this.maxRecords;+ }++ write(stream: Writable, line: string): boolean {+ const bytes = Buffer.byteLength(line);+ if (stream.destroyed || stream.writableEnded || stream.writableNeedDrain+ || !this.canAccept(line)) return false;+ this.bytes += bytes;+ this.records++;+ let settled = false;+ const release = (): void => {+ if (settled) return;+ settled = true;+ this.bytes -= bytes;+ this.records--;+ };+ try {+ stream.write(line, release);+ return true; // false from Writable.write means accepted, but pause subsequent writes.+ } catch {+ release();+ return false;+ }+ }+}diff --git a/apps/desktop/src/main/cc-debug-raw-tailer.ts b/apps/desktop/src/main/cc-debug-raw-tailer.tsnew file mode 100644index 0000000000..8ec5340148--- /dev/null+++ b/apps/desktop/src/main/cc-debug-raw-tailer.ts@@ -0,0 +1,144 @@+import fs from 'node:fs';+import { StringDecoder } from 'node:string_decoder';++const CHUNK_BYTES = 64 * 1024;+const FILE_BYTES_PER_POLL = 256 * 1024;+const MAX_LINE_CHARS = 64 * 1024;++/** A registration belongs to a live CC process, not to retained task history. */+interface Target {+ sessionId: string;+ references: number;+ offset: number;+ identity: string | null;+ pending: string;+ decoder: StringDecoder;+}++/** Reads a bounded, fair slice of explicitly registered files; false means retry the line. */+export class CcDebugRawTailer {+ private readonly targets = new Map<string, Target>();+ private timer: ReturnType<typeof setInterval> | null = null;++ constructor(+ private readonly writeLine: (line: string, sessionId: string) => boolean,+ private readonly bytesPerPoll = 1024 * 1024,+ ) {}++ register(file: string, sessionId: string): () => void {+ let target = this.targets.get(file);+ if (target) {+ target.references++;+ } else {+ target = { sessionId, references: 1, offset: 0, identity: null, pending: '', decoder: new StringDecoder('utf8') };+ // Capture EOF at registration, before the first poll; a not-yet-created+ // file starts at zero so its first diagnostics are not skipped.+ try {+ const stat = fs.statSync(file);+ target.offset = stat.size;+ target.identity = `${stat.dev}:${stat.ino}`;+ } catch { /* file will be created by CC */ }+ this.targets.set(file, target);+ }+ const registered = target;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ if (--registered.references > 0) return;+ // One bounded final read. Any backlog remains in the original raw file,+ // never in an immortal in-memory queue after its writer has exited.+ if (this.timer) this.read(file, registered, CHUNK_BYTES);+ this.flush(registered, true);+ this.targets.delete(file);+ };+ }++ setEnabled(enabled: boolean): void {+ if (enabled && !this.timer) {+ this.timer = setInterval(() => this.pollNow(), 2_000);+ this.timer.unref?.();+ } else if (!enabled && this.timer) {+ clearInterval(this.timer);+ this.timer = null;+ for (const target of this.targets.values()) {+ target.pending = '';+ target.decoder = new StringDecoder('utf8');+ }+ }+ }++ pollNow(): void {+ let remaining = this.bytesPerPoll;+ // Rotate visited entries without copying the whole registry. The original+ // count prevents Map reinsertion from visiting an entry twice this round.+ const count = Math.min(this.targets.size, 64);+ const iterator = this.targets.entries();+ for (let i = 0; i < count && remaining > 0; i++) {+ const entry = iterator.next().value;+ if (!entry) break;+ const [file, target] = entry;+ this.targets.delete(file);+ this.targets.set(file, target);+ remaining -= this.read(file, target, Math.min(FILE_BYTES_PER_POLL, remaining));+ // Stat-only targets still consume a scheduling slot.+ remaining -= 1;+ }+ }++ private read(file: string, target: Target, budget: number): number {+ if (!this.flush(target)) return 0;+ let fd: number | undefined;+ let consumed = 0;+ try {+ fd = fs.openSync(file, 'r');+ const stat = fs.fstatSync(fd);+ if (!stat.isFile()) return 0;+ const identity = `${stat.dev}:${stat.ino}`;+ if ((target.identity !== null && target.identity !== identity) || stat.size < target.offset) {+ target.offset = 0;+ target.pending = '';+ target.decoder = new StringDecoder('utf8');+ }+ target.identity = identity;+ while (consumed < budget && target.offset < stat.size) {+ const wanted = Math.min(CHUNK_BYTES, budget - consumed, stat.size - target.offset);+ const buffer = Buffer.allocUnsafe(wanted);+ const bytes = fs.readSync(fd, buffer, 0, wanted, target.offset);+ if (bytes === 0) break;+ target.offset += bytes;+ consumed += bytes;+ target.pending += target.decoder.write(buffer.subarray(0, bytes));+ if (!this.flush(target)) break;+ }+ return consumed;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ target.offset = 0;+ target.identity = null;+ target.pending = '';+ target.decoder = new StringDecoder('utf8');+ }+ return consumed;+ } finally {+ if (fd !== undefined) {+ try { fs.closeSync(fd); } catch { /* best effort */ }+ }+ }+ }++ private flush(target: Target, final = false): boolean {+ while (target.pending.length > 0) {+ const newline = target.pending.indexOf('\n');+ const fragment = newline < 0 ? target.pending.length >= MAX_LINE_CHARS : newline > MAX_LINE_CHARS;+ if (newline < 0 && !fragment && !final) return true;+ let length = fragment ? MAX_LINE_CHARS : newline < 0 ? target.pending.length : newline;+ if (fragment && target.pending.charCodeAt(length - 1) >= 0xd800+ && target.pending.charCodeAt(length - 1) <= 0xdbff) length--;+ const line = target.pending.slice(0, length);+ if (line && !this.writeLine(fragment ? `${line} [cc-debug line continued]` : line, target.sessionId)) return false;+ target.pending = target.pending.slice(length + (!fragment && newline >= 0 ? 1 : 0));+ }+ return true;+ }+}diff --git a/apps/desktop/src/main/logger.ts b/apps/desktop/src/main/logger.tsindex a825d22532..b87121e03c 100644--- a/apps/desktop/src/main/logger.ts+++ b/apps/desktop/src/main/logger.ts@@ -15,8 +15,8 @@** 注意: cc 子进程的内部 debug 由 cc 二进制通过 SDK debugFile 选项直接 fopen 写入一个* raw 中转文件 (sessions/<id>/cc-debug.raw.log, 路径由 resolveSessionCcDebugFile 给出;- * 无 session 时回退全局 cc-debug.raw.log), **不经过本 logger 的 emit**。bootstrap 的- * tailer 扫描这些 raw 文件, 逐行调 writeCcDebugLine() 归一化汇入对应 session 的 agent 流。+ * 无 session 时回退全局 cc-debug.raw.log), **不经过本 logger 的 emit**。tailer 跟踪当前+ * CC 进程注册的 raw 文件, 有界读取并调 writeCcDebugLine() 汇入对应 session 的 agent 流。** 旧的 maker.log / cc-proxy.log / cc-debug.log 已并入, 启动期由 purgeLegacyAgentLogs()* 清掉, 不再生成 (旧 main.log 保留作历史归档, 不删)。@@ -47,6 +47,8 @@ import { app } from 'electron';import path from 'node:path';import fs from 'node:fs';import util from 'node:util';+import { BoundedLogWriter } from './bounded-log-writer.js';+import { CcDebugRawTailer } from './cc-debug-raw-tailer.js';import { LOG_RETENTION_DAYS } from '../shared/logRetention';import {@@ -118,6 +120,18 @@ const SESSIONS_DIR = 'sessions';const MAX_OPEN_SESSION_SLOTS = 32;const sessionSlots = new Map<string, DailySlot>();let logRootDir = '';+const agentLogWriter = new BoundedLogWriter();+let droppedAgentRecords = 0;+const ccDebugRawTailer = new CcDebugRawTailer(writeCcDebugLine);++/** Called once per local CC process; release on that process's exit/error. */+export function trackSessionCcDebugFile(file: string, sessionId = ''): () => void {+ return ccDebugRawTailer.register(file, sessionId);+}++export function setCcDebugTailingEnabled(enabled: boolean): void {+ ccDebugRawTailer.setEnabled(enabled);+}// scope 路由: maker-host adapter 用 'maker' / 'maker/xxx' 作为根 scope,// renderer 转发会被加 'r:' 前缀, 所以 'r:maker' / 'r:maker/xxx' 也算。@@ -563,6 +577,10 @@ function ensureDailySlot(slot: DailySlot, now: Date): void {slot.dateKey = key;try {slot.stream = fs.createWriteStream(dailyLogPath(slot, key), { flags: 'a' });+ const stream = slot.stream;+ stream.on('error', () => {+ if (slot.stream === stream) slot.stream = null;+ });} catch (err) {origStderr(`[logger] failed to open ${slot.prefix}${key}${slot.ext}: ${(err as Error).message}\n`);slot.stream = null;@@ -631,20 +649,34 @@ function writeMainLine(line: string): void {// agent NDJSON 写入点: maker/proxy (经 emit) 与 cc-debug (经 writeCcDebugLine) 都汇到这里。// 有 sessionId → 写 sessions/<id>/<date>.ndjson; 无 → 写 logs 根 agent-<date>.ndjson。-function writeAgentRecord(rec: Omit<AgentLogRecord, 'seq'>): void {+function writeAgentRecord(rec: Omit<AgentLogRecord, 'seq'>, retryable = false): boolean {+ // Bound serialization too. Raw debug is already fragmented by the tailer.+ const msg = rec.msg.length > 128 * 1024+ ? `${rec.msg.slice(0, 128 * 1024)} [log record truncated]` : rec.msg;+ const full = { ...rec, msg, seq: agentSeq, ...(droppedAgentRecords ? { droppedRecords: droppedAgentRecords } : {}) };+ const line = `${JSON.stringify(full)}\n`;+ const rejected = (): false => {+ // Raw diagnostics remain on disk and the tailer retries; other synchronous+ // producers cannot wait, so report omitted records on the next accepted one.+ if (!retryable) droppedAgentRecords = Math.min(Number.MAX_SAFE_INTEGER, droppedAgentRecords + 1);+ return false;+ };+ // Check before opening a new session stream: LRU eviction must not turn a+ // saturated writer into an unbounded queue of pending open/close operations.+ if (!agentLogWriter.canAccept(line)) return rejected();const slot = rec.sessionId ? sessionAgentSlot(rec.sessionId) : agentSlot;- if (!slot) return;+ if (!slot) return rejected();ensureDailySlot(slot, new Date(rec.ts));- if (!slot.stream) return;- const full: AgentLogRecord = { ...rec, seq: agentSeq++ };- try { slot.stream.write(`${JSON.stringify(full)}\n`); } catch { /* stream broken — silent */ }+ if (!slot.stream || !agentLogWriter.write(slot.stream, line)) return rejected();+ agentSeq++;+ droppedAgentRecords = 0;+ return true;}// cc 子进程 debug 行 (格式 "<UTC-ISO> [LEVEL] [scope?] msg") 解析归一化后汇入 agent 流。-// 由 bootstrap-electron 的 cc-debug tailer 逐行调用, sessionId 来自 raw 文件所在的-// sessions/<id>/ 目录 (per-session debugFile)。无 sessionId 时归根 agent 流。+// 由进程注册驱动的 cc-debug tailer 调用, sessionId 来自启动参数。无 sessionId 时归根 agent 流。const CC_DEBUG_LINE_RE = /^(\d{4}-\d{2}-\d{2}T[\d:.]+Z)\s+\[(\w+)\]\s*(?:\[([^\]]+)\])?\s*([\s\S]*)$/;-export function writeCcDebugLine(rawLine: string, sessionId = ''): void {+export function writeCcDebugLine(rawLine: string, sessionId = ''): boolean {const m = CC_DEBUG_LINE_RE.exec(rawLine);let ts: number;let level: LogLevel;@@ -662,7 +694,7 @@ export function writeCcDebugLine(rawLine: string, sessionId = ''): void {scope = 'cc';msg = rawLine;}- writeAgentRecord({ ts, tz: -new Date(ts).getTimezoneOffset(), level, source: 'cc-debug', scope, sessionId, msg });+ return writeAgentRecord({ ts, tz: -new Date(ts).getTimezoneOffset(), level, source: 'cc-debug', scope, sessionId, msg }, true);}function emit(level: LogLevel, scope: string, args: unknown[]): void {diff --git a/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.tsnew file mode 100644index 0000000000..146d0c1324--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts@@ -0,0 +1,60 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { PreparationCache } from '../preparation-cache.js';++const state = vi.hoisted(() => ({+ owner: { dataOwnerId: 'a', generation: 1, mode: 'cloud' },+ boundary: false,+ bridge: vi.fn(),+}));+vi.mock('electron', () => ({ app: { getPath: () => '', isPackaged: true }, safeStorage: {} }));+vi.mock('@cindy/maker-core', () => ({}));+vi.mock('../../appSessionState.js', async (original) => ({+ ...await original<typeof import('../../appSessionState.js')>(),+ getActiveAppSession: () => ({ ...state.owner }),+ isAppSessionBoundaryPending: () => state.boundary,+}));+vi.mock('../codex-global-plugins.js', () => ({ prepareCodexGlobalPluginsBridge: state.bridge }));++import { DesktopClaudeAuthAdapter, DesktopCodexAuthAdapter } from '../auth-adapters.js';++beforeEach(() => {+ state.owner = { dataOwnerId: 'a', generation: 1, mode: 'cloud' };+ state.boundary = false;+ state.bridge.mockReset().mockResolvedValue({ warnings: [], routingFailures: [] });+});++describe('asset preparation boundaries', () => {+ it('rechecks plugin capability revocation even while successful Skill preparation is cached', async () => {+ const skills = vi.fn(async () => true);+ // Avoid constructor credential reconciliation; exercise the real preparation entry points.+ const adapter = Object.assign(Object.create(DesktopCodexAuthAdapter.prototype), {+ pendingAssetsPrep: new PreparationCache(0),+ skillAssetsPrep: new PreparationCache(30_000), runEnsureGlobalCodexSkills: skills,+ }) as DesktopCodexAuthAdapter;+ Object.defineProperty(adapter, 'codexHome', { value: 'unused-test-home' });+ await adapter.ensureGlobalCodexAssets();+ state.bridge.mockResolvedValueOnce({ warnings: [], routingFailures: ['revoked'] });+ await expect(adapter.ensureGlobalCodexAssets()).rejects.toThrow('Cannot start Codex safely');+ expect(skills).toHaveBeenCalledTimes(1);+ expect(state.bridge).toHaveBeenCalledTimes(2);+ state.bridge.mockRejectedValueOnce(new Error('unreadable'));+ await expect(adapter.ensureGlobalCodexAssets()).rejects.toThrow('unreadable');+ });++ it('does not reuse a completion across owner generations or an in-progress boundary', async () => {+ const prepare = vi.fn(async () => true);+ const adapter = Object.assign(Object.create(DesktopClaudeAuthAdapter.prototype), {+ sharedSkillsPreparation: new PreparationCache(30_000), runEnsureSharedGlobalSkills: prepare,+ }) as DesktopClaudeAuthAdapter;+ await adapter.ensureSharedGlobalSkills();+ await adapter.ensureSharedGlobalSkills();+ expect(prepare).toHaveBeenCalledTimes(1);+ state.boundary = true;+ await adapter.ensureSharedGlobalSkills();+ await adapter.ensureSharedGlobalSkills();+ expect(prepare).toHaveBeenCalledTimes(3);+ state.boundary = false; state.owner.generation++;+ await adapter.ensureSharedGlobalSkills();+ expect(prepare).toHaveBeenCalledTimes(4);+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.tsindex ec0e3c7f9d..7bbffce095 100644--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts@@ -587,13 +587,16 @@ describe('built-in Skills', () => {const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');const orphanBundle = 'v10-aaaaaaaaaaaaaaaa-00000000-0000-0000-0000-000000000000';const orphanRoot = path.join(root, '.versions', orphanBundle);- // Copy immutable bytes, not the active junction: Windows symlink creation- // requires privileges, and an alias would not model an unpublished bundle.- fs.cpSync(path.dirname(initial.descriptors[0]!.absolutePath), orphanRoot, {+ // Copy the immutable bundle, not its .active junction/symlink. The orphan+ // must be a separate directory, including on Windows without symlink rights.+ const bundleRoot = fs.realpathSync(path.dirname(initial.descriptors[0]!.absolutePath));+ fs.cpSync(bundleRoot, orphanRoot, {recursive: true,dereference: true,});expect(fs.lstatSync(orphanRoot).isSymbolicLink()).toBe(false);+ expect(fs.lstatSync(orphanRoot).isDirectory()).toBe(true);+ expect(fs.realpathSync(orphanRoot)).not.toBe(bundleRoot);const creatorLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');fs.unlinkSync(creatorLink);fs.symlinkSync(diff --git a/apps/desktop/src/main/maker-host/__tests__/preparation-cache.test.ts b/apps/desktop/src/main/maker-host/__tests__/preparation-cache.test.tsnew file mode 100644index 0000000000..1ac939172a--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/preparation-cache.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it, vi } from 'vitest';+import { PreparationCache } from '../preparation-cache.js';++describe('successful preparation cache', () => {+ it('coalesces concurrent calls and expires completed work', async () => {+ let now = 0;+ let release!: (ok: boolean) => void;+ const cache = new PreparationCache(30_000, () => now);+ const prepare = vi.fn(() => new Promise<boolean>((resolve) => { release = resolve; }));+ const a = cache.ensure('owner:1', prepare);+ const b = cache.ensure('owner:1', prepare);+ await Promise.resolve();+ expect(prepare).toHaveBeenCalledTimes(1);+ release(true);+ await Promise.all([a, b]);+ await cache.ensure('owner:1', prepare);+ expect(prepare).toHaveBeenCalledTimes(1);+ now = 30_000;+ const c = cache.ensure('owner:1', prepare);+ await Promise.resolve(); release(true); await c;+ expect(prepare).toHaveBeenCalledTimes(2);+ });++ it('does not cache failures, warnings, or an invalidated owner completion', async () => {+ const cache = new PreparationCache(30_000);+ const prepare = vi.fn().mockResolvedValueOnce(false).mockRejectedValueOnce(new Error('failed')).mockResolvedValue(true);+ await cache.ensure('owner:1', prepare);+ await expect(cache.ensure('owner:1', prepare)).rejects.toThrow('failed');+ await cache.ensure('owner:1', prepare);+ await cache.ensure('owner:2', prepare);+ expect(prepare).toHaveBeenCalledTimes(4);+ });++ it('serializes owners without reusing the old owner result', async () => {+ const cache = new PreparationCache(30_000);+ let release!: (ok: boolean) => void;+ const first = cache.ensure('a', () => new Promise((resolve) => { release = resolve; }));+ const other = vi.fn(async () => true);+ const second = cache.ensure('b', other);+ await Promise.resolve();+ expect(other).not.toHaveBeenCalled();+ release(true);+ await Promise.all([first, second]);+ expect(other).toHaveBeenCalledTimes(1);+ });++ it('never caches sequential capability checks at TTL zero, even when the clock moves backwards', async () => {+ let now = 100;+ const cache = new PreparationCache(0, () => now);+ const prepare = vi.fn(async () => true);+ await cache.ensure('owner', prepare);+ now = 50;+ await cache.ensure('owner', prepare);+ expect(prepare).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 7e6b89b770..659d5d098c 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -39,6 +39,7 @@ import { prepareCodexGlobalRulesCopy } from './codex-global-rules.js';import { prepareCodexGlobalPluginsBridge } from './codex-global-plugins.js';import { DESKTOP_CAPABILITY_ROUTING_POLICY } from './capability-routing.js';import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';+import { PreparationCache } from './preparation-cache.js';import {prepareBuiltInSkills,refreshBuiltInClaudeSkillLinks,@@ -134,6 +135,19 @@ const log = createLogger('auth-adapters');* (见 `log-upload/sourceAllowlist` 的 `DENIED_SUB_SCOPES`)。本机日志照常写全,只是不上报。*/const assetPrepLog = createLogger('auth-adapters:asset-prep');++function preparationScope(): { key: string; ownerId: string | null; current: () => boolean } {+ const owner = getActiveAppSession();+ return {+ key: JSON.stringify([owner.dataOwnerId, owner.generation, isAppSessionBoundaryPending()]),+ ownerId: owner.dataOwnerId,+ current: () => {+ const latest = getActiveAppSession();+ return !isAppSessionBoundaryPending() && latest.generation === owner.generation+ && latest.dataOwnerId === owner.dataOwnerId;+ },+ };+}/*** 凭证文件的落盘 / 权限 / 硬链操作失败诊断。这些消息(icacls/chmod 的 `{ file }`、`fsp.rm` 与* `relinkSharedCodexAuth` 的 `error.message`)会带 `auth.json` / `models_cache.json` 等**凭证文件@@ -545,7 +559,7 @@ export const CLAUDE_OAUTH_CALLBACK_TIMEOUT_MS = 12_000;/** Claude AuthAdapter —— 只回鉴权 env, endpoint / behavior flag 走 runtime-configs.ts。 */export class DesktopClaudeAuthAdapter implements AuthAdapter {- private pendingSharedSkillsPrep: Promise<void> | null = null;+ private readonly sharedSkillsPreparation = new PreparationCache(30_000);/** invalidate() 触发时把 auth state 推给 renderer(maker-host 装配注入,对齐 codex)。 */private onInvalidatedBroadcast?: (reason: string) => void;@@ -594,16 +608,15 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {}async ensureSharedGlobalSkills(): Promise<void> {- if (this.pendingSharedSkillsPrep) return this.pendingSharedSkillsPrep;- this.pendingSharedSkillsPrep = this.runEnsureSharedGlobalSkills().finally(() => {- this.pendingSharedSkillsPrep = null;+ const scope = preparationScope();+ await this.sharedSkillsPreparation.ensure(scope.key, async () => {+ const success = await this.runEnsureSharedGlobalSkills(scope.ownerId);+ return success && scope.current();});- return this.pendingSharedSkillsPrep;}- private async runEnsureSharedGlobalSkills(): Promise<void> {+ private async runEnsureSharedGlobalSkills(ownerId: string | null): Promise<boolean> {try {- const ownerId = getActiveAppSession().dataOwnerId;const result = await withSharedGlobalSkillProjectionMutation(ownerId, async () => {// Bundle publication keeps every managed Agent link on one stable// active pointer. The stable-owner boundary prevents a passive profile@@ -643,10 +656,12 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {for (const warning of result.warnings) {assetPrepLog.warn('shared global skill warning', { warning });}+ return result.warnings.length === 0;} catch (error) {assetPrepLog.warn('prepare shared global skills failed', {error: error instanceof Error ? error.message : String(error),});+ return false;}}@@ -969,12 +984,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {private lastKnownCodexCredentialScope: AuthState['credentialScope'] = undefined;/**- * 进行中的 ensureGlobalCodexAssets 调用 —— 同一时刻并发进入直接复用同一 Promise,- * 避免重复 stat / copy。每次 codex session start 都会过一遍 getAuthEnv → ensure,- * 没有缓存时连续启动会触发并发竞态 (功能正确但浪费 io)。结束后置 null 不做长期缓存,- * 因为源文件 (~/.codex/AGENTS.md) 随时可能被用户改, 仍需要后续调用触发新一轮检查。+ * Plugin capability enforcement is always rechecked after concurrent callers+ * settle. Only successful Skill/rules preparation has a 30-second TTL.*/- private pendingAssetsPrep: Promise<void> | null = null;+ private readonly pendingAssetsPrep = new PreparationCache(0);+ private readonly skillAssetsPrep = new PreparationCache(30_000);/*** 进行中的 reconcileWithSystemCodex 调用 —— 多个调用点 (构造 / getState / getAuthEnv /@@ -1410,17 +1424,20 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {}async ensureGlobalCodexAssets(): Promise<void> {- if (this.pendingAssetsPrep) return this.pendingAssetsPrep;- this.pendingAssetsPrep = this.runEnsureGlobalCodexAssets().finally(() => {- this.pendingAssetsPrep = null;+ const scope = preparationScope();+ await this.pendingAssetsPrep.ensure(scope.key, async () => {+ await this.skillAssetsPrep.ensure(scope.key, async () => {+ const success = await this.runEnsureGlobalCodexSkills(scope.ownerId);+ return success && scope.current();+ });+ await this.runEnsureGlobalCodexPlugins();+ return true;});- return this.pendingAssetsPrep;}- private async runEnsureGlobalCodexAssets(): Promise<void> {+ private async runEnsureGlobalCodexSkills(ownerId: string | null): Promise<boolean> {// Load-bearing order: Codex skill linking scans ~/.agents/skills, so shared// links must populate that directory before prepareCodexGlobalSkillsLinks runs.- const ownerId = getActiveAppSession().dataOwnerId;const sharedOutcome = await withSharedGlobalSkillProjectionMutation(ownerId, () =>prepareSharedGlobalSkillLinks({assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),@@ -1430,7 +1447,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {(err: Error) => ({ ok: false as const, label: 'shared-skills' as const, err }),);- const [skillsOutcome, rulesOutcome, pluginsOutcome] = await Promise.all([+ const [skillsOutcome, rulesOutcome] = await Promise.all([prepareCodexGlobalSkillsLinks(this.codexHome).then((r) => ({ ok: true as const, label: 'skills' as const, warnings: r.warnings }),(err: Error) => ({ ok: false as const, label: 'skills' as const, err }),@@ -1439,20 +1456,10 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {(r) => ({ ok: true as const, label: 'rules' as const, warnings: r.warnings }),(err: Error) => ({ ok: false as const, label: 'rules' as const, err }),),- prepareCodexGlobalPluginsBridge(this.codexHome, {- capabilityRouting: DESKTOP_CAPABILITY_ROUTING_POLICY,- }).then(- (r) => ({- ok: true as const,- label: 'plugins' as const,- warnings: r.warnings,- routingFailures: r.routingFailures,- }),- (err: Error) => ({ ok: false as const, label: 'plugins' as const, err }),- ),]);- for (const outcome of [sharedOutcome, skillsOutcome, rulesOutcome, pluginsOutcome]) {+ const outcomes = [sharedOutcome, skillsOutcome, rulesOutcome];+ for (const outcome of outcomes) {if (!outcome.ok) {assetPrepLog.warn('prepare Codex global asset failed', {asset: outcome.label,@@ -1464,6 +1471,21 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {assetPrepLog.warn('Codex global asset warning', { asset: outcome.label, warning });}}+ return outcomes.every((outcome) => outcome.ok && outcome.warnings.length === 0);+ }++ private async runEnsureGlobalCodexPlugins(): Promise<void> {+ const pluginsOutcome = await prepareCodexGlobalPluginsBridge(this.codexHome, {+ capabilityRouting: DESKTOP_CAPABILITY_ROUTING_POLICY,+ }).then(+ (r) => ({ ok: true as const, warnings: r.warnings, routingFailures: r.routingFailures }),+ (err: Error) => ({ ok: false as const, err }),+ );+ if (pluginsOutcome.ok) {+ for (const warning of pluginsOutcome.warnings) {+ assetPrepLog.warn('Codex global asset warning', { asset: 'plugins', warning });+ }+ }if (!pluginsOutcome.ok) {// Expected cache/config I/O failures are normalized by the bridge and// gated against the isolated plugin enablement. A rejection here is andiff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex c7a8f8fd75..bba84339be 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -134,7 +134,7 @@ import { createToolResultImageDescriptor } from '../vision-bridge/tool-result-imimport * as blobStore from '../cindy-media/blobStore.js';import { buildPiVisionBridgeEnv } from '../vision-bridge/pi-vision-bridge-env.js';import { resolveVisionBackendRoute, setVisionGatewayKeyReader } from './provider-route.js';-import { resolveSessionCcDebugFile } from '../logger.js';+import { resolveSessionCcDebugFile, trackSessionCcDebugFile } from '../logger.js';import { resetProviderModelAutoRefreshCooldowns } from './provider-model-auto-refresh.js';import { getThinkingEnabledFromMemory } from './newMakerDefaultsCache.js';import { getSessionFastMode } from './session-effort-store.js';@@ -1167,6 +1167,7 @@ export function getMaker(): Maker {// 每个 session 的 cc 子进程 debug 写到 sessions/<id>/cc-debug.raw.log (logger 拼路径// + mkdir), tailer 再归一化汇入该 session 的 <date>.ndjson。resolveCcDebugFile: resolveSessionCcDebugFile,+ trackCcDebugFile: trackSessionCcDebugFile,mcpProviders: claudeMcpProviders,capabilityRouting: DESKTOP_CAPABILITY_ROUTING_POLICY,makerMemory: makerMemoryManager,diff --git a/apps/desktop/src/main/maker-host/preparation-cache.ts b/apps/desktop/src/main/maker-host/preparation-cache.tsnew file mode 100644index 0000000000..9f5facb479--- /dev/null+++ b/apps/desktop/src/main/maker-host/preparation-cache.ts@@ -0,0 +1,23 @@+/** One owner/generation at a time; only successful work gets a short completion TTL. */+export class PreparationCache {+ private pending: { key: string; promise: Promise<boolean> } | null = null;+ private completed: { key: string; until: number } | null = null;++ constructor(private readonly ttlMs: number, private readonly now = Date.now) {}++ async ensure(key: string, prepare: () => Promise<boolean>): Promise<void> {+ while (this.pending) {+ const pending = this.pending;+ if (pending.key === key) { await pending.promise; return; }+ await pending.promise.catch(() => undefined);+ }+ if (this.completed?.key === key && this.now() < this.completed.until) return;+ this.completed = null;+ const promise = Promise.resolve().then(prepare).then((success) => {+ this.completed = success && this.ttlMs > 0 ? { key, until: this.now() + this.ttlMs } : null;+ return success;+ }).finally(() => { this.pending = null; });+ this.pending = { key, promise };+ await promise;+ }+}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 41b2a83ba3..f4caa86fa8 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -706,6 +706,8 @@ export interface AgentDeps {* 缺省 / 返回 undefined → 回退到全局 process.env.XDT_CC_DEBUG_FILE。*/resolveCcDebugFile?: (sessionId?: string) => string | undefined;+ /** Register one local debug writer; the returned disposer runs on process exit/error. */+ trackCcDebugFile?: (filePath: string, sessionId?: string) => () => void;/*** MCP server 提供者列表(host 注入)。agent 在 startSession 时按上下文挑选diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex c8765b6f30..f35425403c 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -3863,7 +3863,7 @@ export class ClaudeCodeAgent extends BaseAgent {...(finalResumeAt ? { resumeSessionAt: finalResumeAt } : {}),...(finalFork ? { forkSession: true } : {}),env,- ...(this.deps.registerLocalAgentProcess+ ...(this.deps.registerLocalAgentProcess || this.deps.trackCcDebugFile? {spawnClaudeCodeProcess: (spawnOptions) =>spawnObservedClaudeProcess({@@ -3874,6 +3874,9 @@ export class ClaudeCodeAgent extends BaseAgent {kind: 'claude',role: 'task-host',}),+ trackDebugFile: process.env.XDT_CC_DEBUG_NET === '1' && ccDebugFile+ ? () => this.deps.trackCcDebugFile?.(ccDebugFile, opts.sessionId) ?? (() => {})+ : undefined,onStderr: vo.onStderrLine as ((line: string) => void) | undefined,}),}diff --git a/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts b/packages/maker-core/src/agents/claude-code/local-process-spawn.test.tsindex abdff32582..fc003eaf7b 100644--- a/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts+++ b/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts@@ -29,6 +29,7 @@ function makeChild(pid = 4321) {function spawnProcess(overrides: {registerProcess?: (pid: number) => void | (() => void);+ trackDebugFile?: () => () => void;onStderr?: (chunk: string) => void;} = {}) {return spawnObservedClaudeProcess({@@ -48,6 +49,17 @@ beforeEach(() => {});describe('spawnObservedClaudeProcess', () => {+ it('releases debug tracking once even when the process observer fails', () => {+ const child = makeChild();+ mocks.spawn.mockReturnValue(child);+ const release = vi.fn();+ const trackDebugFile = vi.fn(() => release);+ spawnProcess({ registerProcess: () => { throw new Error('observer'); }, trackDebugFile });+ expect(trackDebugFile).toHaveBeenCalledOnce();+ child.emit('error', new Error('spawn'));+ child.emit('exit', 1, null);+ expect(release).toHaveBeenCalledOnce();+ });it('registers the concrete PID and disposes that generation once', () => {const child = makeChild();mocks.spawn.mockReturnValue(child);diff --git a/packages/maker-core/src/agents/claude-code/local-process-spawn.ts b/packages/maker-core/src/agents/claude-code/local-process-spawn.tsindex f59a21a9cf..e984da30bf 100644--- a/packages/maker-core/src/agents/claude-code/local-process-spawn.ts+++ b/packages/maker-core/src/agents/claude-code/local-process-spawn.ts@@ -5,6 +5,7 @@ import type { SpawnOptions, SpawnedProcess } from '@anthropic-ai/claude-agent-sdexport interface ObservedClaudeProcessOptions {spawnOptions: SpawnOptions;registerProcess?: (pid: number) => void | (() => void);+ trackDebugFile?: () => () => void;onStderr?: (chunk: string) => void;}@@ -24,6 +25,7 @@ export function spawnObservedClaudeProcess(},);let disposeRegistration: (() => void) | undefined;+ let disposeDebugFile: (() => void) | undefined;if (child.pid != null && child.pid > 0) {try {const dispose = opts.registerProcess?.(child.pid);@@ -32,6 +34,7 @@ export function spawnObservedClaudeProcess(// Observation failures must not block Claude startup. Missing registry state// only makes this process fail closed for termination.}+ try { disposeDebugFile = opts.trackDebugFile?.(); } catch { /* diagnostics are best effort */ }}let registrationDisposed = false;@@ -39,6 +42,8 @@ export function spawnObservedClaudeProcess(if (registrationDisposed) return;registrationDisposed = true;try { disposeRegistration?.(); } catch { /* best-effort cleanup */ }+ try { disposeDebugFile?.(); } catch { /* best-effort diagnostics */ }+ disposeDebugFile = undefined;disposeRegistration = undefined;};child.once('exit', disposeOnce);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 8842205edb..41009ea34a 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -24,6 +24,7 @@ import {import { tmpdir } from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as subagentRuns from '../pi-subagent-runs.js';import type { AutoReviewRequest } from '../../shared/auto-review-decision.js';const captured = vi.hoisted(() => ({@@ -743,6 +744,89 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {}});+ it.each([false, true])('backs off an empty root and wakes a launch (scan in flight: %s)', async (inFlight) => {+ const realInterval = globalThis.setInterval;+ let tick: (() => void) | undefined;+ const interval = vi.spyOn(globalThis, 'setInterval').mockImplementation(((callback: () => void, ms: number, ...args: unknown[]) => {+ if (ms === 500) {+ tick = callback;+ return realInterval(() => {}, 2_000_000_000);+ }+ return realInterval(callback, ms, ...args);+ }) as typeof setInterval);+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);+ const realScan = subagentRuns.scanPiSubagentRuns;+ let scansFinished = 0;+ let releaseScan: (() => void) | undefined;+ let holdScan = false;+ const scan = vi.spyOn(subagentRuns, 'scanPiSubagentRuns').mockImplementation(async function* (root, options) {+ try {+ yield* realScan(root, options);+ if (holdScan && root.startsWith(agentHome + path.sep)) {+ await new Promise<void>((resolve) => { releaseScan = resolve; });+ }+ } finally { if (root.startsWith(agentHome + path.sep)) scansFinished++; }+ });+ const pollCount = () => scan.mock.calls.filter(([root]) => root.startsWith(agentHome + path.sep)).length;+ let handle: PiTestSessionHandle | undefined;+ try {+ handle = await start();+ // Wait for the initial filesystem iterator to finish before sampling cadence.+ await vi.waitFor(() => expect(scansFinished).toBe(1));+ await flush();+ const initial = pollCount();+ expect(initial).toBeGreaterThan(0);+ now += 500; tick!();+ await flush();+ expect(pollCount()).toBe(initial);+ now += 2_000; tick!();+ await vi.waitFor(() => expect(pollCount()).toBeGreaterThan(initial));+ await vi.waitFor(() => expect(scansFinished).toBe(2));+ await flush();+ if (inFlight) {+ holdScan = true;+ now += 2_000; tick!();+ await vi.waitFor(() => expect(releaseScan).toBeTypeOf('function'));+ }+ const afterIdle = pollCount();+ const runId = '123e4567-e89b-42d3-a456-4266141740ad';+ const runDir = path.join(captured.env.CINDY_PI_SUBAGENT_RUN_ROOT!, runId);+ mkdirSync(runDir, { recursive: true });+ writeFileSync(path.join(runDir, 'runner.cjs'), '');+ writeFileSync(path.join(runDir, 'config.json'), '{}');+ writeFileSync(path.join(runDir, 'status.json'), JSON.stringify({+ version: 1, runId, taskId: 'poll-wake', parentSessionId: 's1',+ runtimeOwnerId: captured.env.CINDY_PI_SUBAGENT_OWNER_ID,+ runnerInstanceId: `launch-pending-${runId}`, state: 'queued',+ startedAt: now, updatedAt: now, tasks: [],+ }));+ fireSubagentRunnerRequest('poll-launch', 'launch', runId);+ await waitForResponse('poll-launch');+ if (inFlight) {+ expect(pollCount()).toBe(afterIdle);+ holdScan = false; releaseScan!();+ await vi.waitFor(() => expect(scansFinished).toBe(3));+ await flush();+ now += 500; tick!();+ await vi.waitFor(() => expect(scansFinished).toBe(4));+ await flush();+ }+ expect(pollCount()).toBeGreaterThan(afterIdle);+ await vi.waitFor(() => expect(scansFinished).toBe(inFlight ? 4 : 3));+ await flush();+ expect(handle.listBackgroundTasks?.()).toEqual(expect.arrayContaining([expect.objectContaining({ taskId: 'poll-wake' })]));+ const active = pollCount();+ now += 500; tick!();+ await vi.waitFor(() => expect(pollCount()).toBeGreaterThan(active));+ } finally {+ holdScan = false; releaseScan?.();+ clock.mockRestore();+ await handle?.close();+ interval.mockRestore(); scan.mockRestore();+ }+ });+it.each(['success', 'native-failure'] as const)('consumes the %s package tool result and replies before Session retirement', async (outcome) => {const deps = buildDeps();let session!: Session;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex 11ca0d2868..a5defe412f 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -131,6 +131,15 @@ const noopLogger: Logger = {child: () => noopLogger,};+// The same durable store feeds streaming foreground discovery and detached lease inspection.+function mockRunDiscovery() {+ const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns');+ vi.spyOn(piSubagentRuns, 'scanPiSubagentRuns').mockImplementation(async function* (root) {+ yield* await piSubagentRuns.listPiSubagentRuns(root);+ });+ return list;+}+describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {let agentHome = '';let cwd = '';@@ -713,7 +722,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// offered again the instant the file parsed — two decisions racing for one// request.const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ const list = mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'listPiSubagentRunDirectoryIds').mockResolvedValue([run.runId]);vi.spyOn(piSubagentRuns, 'listPiSubagentRunDiagnostics').mockResolvedValue([]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);@@ -764,7 +773,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// own terminal state. The child then waited out its run timeout on a card// nobody was consuming.const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -809,7 +818,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('parks a detached Subagent approval instead of denying it when the listener is torn down', async () => {const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -829,7 +838,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('delivers a parked Subagent approval once an approval surface is attached again', async () => {const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -858,7 +867,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// fail-closed boundary is unchanged: "surface exists and said no" is a deny,// only "nobody was listening" parks.const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -882,7 +891,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// The user had the card on screen and never answered; closing the session// must not convert that into a denial for a child that is still running.const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -931,7 +940,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// proc.close() fires onExit after close() already stopped the runners; that// exit must not start a supervisor that answers the outgoing owner's cards.const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);// A runner that misses its stop deadline is exactly the risky case.vi.spyOn(piSubagentRuns, 'stopPiSubagentRunsForAccountBoundary').mockResolvedValue(false);@@ -957,7 +966,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// its approvals through the outgoing account's resolver while holding that// account's proxy lease.let approvalGeneration = 0;- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockImplementation(async () => {+ mockRunDiscovery().mockImplementation(async () => {// A fresh approval id per poll: the supervisor's dedupe would otherwise// hide a loop that is still very much running.approvalGeneration += 1;@@ -994,7 +1003,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// before the barrier, close() could return — the caller then revoking the// token and handing the runtime over — with that write still in progress.let approvalGeneration = 0;- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockImplementation(async () => {+ mockRunDiscovery().mockImplementation(async () => {approvalGeneration += 1;const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });run.tasks[0]!.pendingApproval!.id = `approval-${approvalGeneration}`;@@ -1043,7 +1052,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const scanStarted = new Promise<void>((resolve) => { openScan = resolve; });const scanGate = new Promise<void>((resolve) => { releaseScan = resolve; });let scans = 0;- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockImplementation(async () => {+ mockRunDiscovery().mockImplementation(async () => {scans += 1;if (scans === 1) {openScan();@@ -1087,7 +1096,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'bash',input: { command: 'printf hi > ./inside.txt' },}, {}, 'input');- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);vi.spyOn(piSubagentRuns, 'stopPiSubagentRunsForAccountBoundary').mockResolvedValue(true);@@ -1116,7 +1125,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {let releaseReview!: (value: { verdict: typeof verdict }) => void;const reviewGate = new Promise<{ verdict: typeof verdict }>((resolve) => { releaseReview = resolve; });const run = pendingSubagentRun({ toolName: 'bash', input: { command: 'printf hi > /outside/report.txt' } }, {}, method);- const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ const list = mockRunDiscovery().mockResolvedValue([run]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn<NonNullable<AgentDeps['reviewAutoPermissionAction']>>(() => reviewGate);@@ -1157,7 +1166,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {});it('keeps Auto approvals that start after detaching under that lifecycle', async () => {- const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([]);+ const list = mockRunDiscovery().mockResolvedValue([]);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'allow' as const }));@@ -1173,7 +1182,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('stays idempotent over a repeated account-boundary close', async () => {let approvalGeneration = 0;- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockImplementation(async () => {+ mockRunDiscovery().mockImplementation(async () => {approvalGeneration += 1;const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });run.tasks[0]!.pendingApproval!.id = `approval-${approvalGeneration}`;@@ -1217,7 +1226,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const runId = '123e4567-e89b-42d3-a456-426614174097';const noteOpaqueWrite = vi.fn();const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([{+ mockRunDiscovery().mockResolvedValue([{version: 1,runId,taskId: 'tool-turn-change',@@ -1298,7 +1307,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// Navigation-close tests may still have a detached supervisor draining.// Only this test's unique home owns the run and the captured write gate.const root = piSubagentRuns.piSubagentRunRoot(agentHome, opts().sessionId);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns')+ mockRunDiscovery().mockImplementation(async candidate => candidate === root ? [run] : []);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockImplementation(async candidate => candidate === root ? 1 : 0);@@ -1501,7 +1510,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);vi.spyOn(piSubagentRuns, 'countPiSubagentRunDirectories').mockResolvedValue(1);vi.spyOn(piSubagentRuns, 'stopPiSubagentRunsForAccountBoundary').mockResolvedValue(true);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([{+ mockRunDiscovery().mockResolvedValue([{version: 1,runId,taskId: 'tool-turn-change',@@ -1559,7 +1568,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'bash',input: { command: 'printf fixture' },});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const resolver = vi.fn(async () => ({ kind: 'permission', behavior }) as const);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -1598,7 +1607,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'bash',input: { command: 'printf fixture' },}, {}, 'input');- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());handle.setInteractionResolver(vi.fn(async () => ({ kind: 'permission', behavior }) as const));@@ -1616,7 +1625,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it.each(['before-review', 'during-review'] as const)('retains durable child authority when root settles %s', async (boundary) => {const run = pendingSubagentRun({ toolName: 'unknown_sender', input: { action: 'send' } });- const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([]);+ const list = mockRunDiscovery().mockResolvedValue([]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);let release!: (decision: { verdict: 'allow' }) => void;const review = vi.fn<NonNullable<AgentDeps['reviewAutoPermissionAction']>>(() => new Promise((resolve) => { release = resolve; }));@@ -1643,7 +1652,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'bash',input: { command: 'printf unsafe > /tmp/outside.txt' },}, {}, 'input');- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'block' as const, reason: 'This task is read-only.' }));const handle = await new PiAgent(buildDeps({ reviewAutoPermissionAction: review })).startSession({@@ -1669,7 +1678,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'write',input: { path: 'a.txt' },}, {}, 'input');- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());handle.setInteractionResolver(vi.fn(async () => { throw new Error('resolver failed'); }));@@ -1690,7 +1699,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// dead owner, so this stays refused.{ runtimeOwnerId: piSubagentRuns.piSubagentRuntimeOwnerId(process.ppid, 'another-runtime') },);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' }) as const);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -1710,7 +1719,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {parentSessionId: 'some-other-session',},);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' }) as const);const handle = await new PiAgent(buildDeps()).startSession(opts());@@ -1733,7 +1742,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {{ toolName: 'write', input: { path: 'a.txt' } },{ runtimeOwnerId: ownerId('earlier-handle-instance'), parentSessionId: 'adopt-1' },);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' }) as const);const handle = await new PiAgent(buildDeps())@@ -1763,7 +1772,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {const run = pendingSubagentRun({ toolName: 'write', input,resolvedWritePath: path.join(cwd, 'a.txt'), resolvedWritableRoots: [cwd],}, { runtimeOwnerId: ownerId('earlier-handle-instance'), parentSessionId: `auto-adopt-${verdict}` });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn<NonNullable<AgentDeps['reviewAutoPermissionAction']>>(async () => ({ verdict }));const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);@@ -1794,7 +1803,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {{ toolName: 'bash', input: { command: 'rm -rf /tmp/x' } },{ runtimeOwnerId: ownerId('earlier-handle-instance'), parentSessionId: 'adopt-2' },);- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'allow' as const }));const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);@@ -1826,7 +1835,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {resolvedWritePath: path.join(cwd, 'tmp', 'auto-safe.txt'),resolvedWritableRoots: [cwd],});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession({...opts(),@@ -1851,7 +1860,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {input: { path: 'tmp/legacy-safe.txt', content: 'legacy' },resolvedWritePath: path.join(cwd, 'tmp', 'legacy-safe.txt'),});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'allow' as const }));const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);@@ -1884,7 +1893,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {resolvedWritePath: path.join(outsideDir, 'result.txt'),resolvedWritableRoots: [cwd, writableDir],});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'block' as const }));const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);@@ -1929,7 +1938,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {resolvedWritePath: path.join(realpathSync(realWritableDir), 'result.txt'),resolvedWritableRoots: [cwd, realpathSync(realWritableDir)],});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);const handle = await new PiAgent(buildDeps()).startSession({@@ -1959,7 +1968,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {toolName: 'bash',input: { command: "printf unsafe > /tmp/outside.txt" },});- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const review = vi.fn(async () => ({ verdict: 'ask' as const }));const handle = await new PiAgent(buildDeps({ reviewAutoPermissionAction: review })).startSession({@@ -1986,7 +1995,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('fails closed when the durable Subagent approval resolver throws', async () => {const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);const handle = await new PiAgent(buildDeps()).startSession(opts());handle.setInteractionResolver(vi.fn(async () => { throw new Error('resolver failed'); }));@@ -2002,7 +2011,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('retries durable Subagent approval delivery without asking the user twice', async () => {const run = pendingSubagentRun({ toolName: 'write', input: { path: 'a.txt' } });- vi.spyOn(piSubagentRuns, 'listPiSubagentRuns').mockResolvedValue([run]);+ mockRunDiscovery().mockResolvedValue([run]);const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockRejectedValueOnce(new Error('mailbox unavailable')).mockResolvedValue(1);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex e76441f0bd..181274b9fb 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -13,6 +13,7 @@ import {verifyPiSubagentRunnerIdentity,listPiSubagentRunDiagnostics,listPiSubagentRuns,+ scanPiSubagentRuns,acquirePiSubagentLaunchFence,clearStalePiSubagentLaunchFence,isPiSubagentLaunchFenceActive,@@ -191,6 +192,38 @@ afterEach(async () => {});describe('PI durable subagent run store', () => {+ it('selects only the newest generation of a logical task before delivering historical payloads', async () => {+ const root = await makeRoot();+ const older = status('123e4567-e89b-42d3-a456-4266141740ab', {+ taskId: 'same-task', state: 'completed', startedAt: 10,+ });+ const newer = status('123e4567-e89b-42d3-a456-4266141740ac', {+ taskId: 'same-task', state: 'completed', startedAt: 20,+ });+ await writeStatus(root, older);+ await writeStatus(root, newer);+ const discovered = [];+ for await (const run of scanPiSubagentRuns(root, { latestPerTask: true })) discovered.push(run);+ expect(discovered.map((run) => run.runId)).toEqual([newer.runId]);+ });++ it('streams historical status files lazily and closes the directory after early cancellation', async () => {+ const root = await makeRoot();+ const ids = ['123e4567-e89b-42d3-a456-4266141740ab', '123e4567-e89b-42d3-a456-4266141740ac'];+ for (const id of ids) await writeStatus(root, status(id, { state: 'completed' }));+ const iterator = scanPiSubagentRuns(root);+ const first = await iterator.next();+ expect(first.done).toBe(false);+ // The other status has not been read or retained while the consumer is suspended.+ const other = ids.find((id) => id !== first.value!.runId)!;+ await writeFile(path.join(root, other, 'status.json'), 'corrupt');+ expect((await iterator.next()).done).toBe(true);+ const early = scanPiSubagentRuns(root);+ await early.next();+ await early.return(undefined);+ await rm(root, { recursive: true, force: true });+ });+it('records a host-observed runner failure without rewriting completed child results', async () => {const root = await makeRoot();const runId = '123e4567-e89b-42d3-a456-4266141740ab';diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 6b9cad422e..555dcae800 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -119,6 +119,9 @@ import {listPiSubagentRunDiagnostics,listPiSubagentRunDirectoryIds,listPiSubagentRuns,+ scanPiSubagentRuns,+ PI_SUBAGENT_ACTIVE_POLL_MS,+ PI_SUBAGENT_IDLE_POLL_MS,piSubagentRunRoot,piSubagentApprovalScope,piSubagentRuntimeOwnerId,@@ -3973,7 +3976,9 @@ export class PiAgent extends BaseAgent {* approvals.*/let piProcessExited = false;- const piSubagentStatuses = new Map<string, PiSubagentRunStatus>();+ type PiSubagentStatusSummary = Pick<PiSubagentRunStatus,+ 'runId' | 'taskId' | 'state' | 'startedAt' | 'updatedAt' | 'title' | 'description'>;+ const piSubagentStatuses = new Map<string, PiSubagentStatusSummary>();const piSubagentFingerprints = new Map<string, string>();const piSubagentApprovalRequests = new Set<string>();const piSubagentApprovalDeliveries = new Set<string>();@@ -4031,6 +4036,8 @@ export class PiAgent extends BaseAgent {}};let piSubagentRefreshInFlight = false;+ let piSubagentNextRefreshAt = 0;+ let piSubagentRefreshGeneration = 0;// Approval delivery belongs to the *detached run* lifecycle, not to the// parent handle. After a navigation close the foreground refresh timer is// gone, but `deferProxyDisposalForDetachedRuns` keeps polling durable status@@ -4074,7 +4081,7 @@ export class PiAgent extends BaseAgent {const taskId = status.taskId;const projectedStatus = status.state === 'queued' ? 'running' : status.state;if (isPiSubagentTerminal(status.state)) clearPiSubagentApprovalState(status.runId);- const fingerprint = JSON.stringify([+ const fingerprint = createHash('sha256').update(JSON.stringify([status.runId,status.state,status.totalTokens,@@ -4088,7 +4095,7 @@ export class PiAgent extends BaseAgent {task.error,task.pendingApproval?.id,]),- ]);+ ])).digest('hex');if (piSubagentFingerprints.get(taskId) === fingerprint) return;piSubagentFingerprints.set(taskId, fingerprint);const taskModels = new Set(status.tasks.map((task) => task.model ?? null));@@ -4164,7 +4171,7 @@ export class PiAgent extends BaseAgent {* that is merely unreadable is held, not buried.*/const emitPiSubagentDiagnostic = (- previous: PiSubagentRunStatus,+ previous: PiSubagentStatusSummary,diagnostic: PiSubagentRunDiagnostic,): void => {queue.push({@@ -4623,16 +4630,28 @@ export class PiAgent extends BaseAgent {};const refreshPiSubagentRuns = async (): Promise<void> => {if (closed || piSubagentRefreshInFlight) return;+ const generation = piSubagentRefreshGeneration;+ const refreshStartedAt = Date.now();piSubagentRefreshInFlight = true;+ let active = false;+ let succeeded = false;try {- const statuses = await listPiSubagentRuns(subagentRunRoot);- if (closed) return;- const newestTaskIds = new Set<string>();- for (const status of statuses) {+ const seenRunIds = new Set<string>();+ for await (const status of scanPiSubagentRuns(subagentRunRoot, { latestPerTask: true })) {if (closed) break;- if (newestTaskIds.has(status.taskId)) continue;- newestTaskIds.add(status.taskId);- piSubagentStatuses.set(status.taskId, status);+ seenRunIds.add(status.runId);+ const previous = piSubagentStatuses.get(status.taskId);+ if (previous && (previous.startedAt > status.startedAt+ || (previous.startedAt === status.startedAt && previous.runId.localeCompare(status.runId) > 0))) continue;+ const terminal = isPiSubagentTerminal(status.state);+ if (!terminal) active = true;+ // Disk/DB remain the history source. Output is delivered below, but+ // never pinned by this live handle's discovery or fingerprint cache.+ piSubagentStatuses.set(status.taskId, {+ runId: status.runId, taskId: status.taskId, state: status.state,+ startedAt: status.startedAt, updatedAt: status.updatedAt,+ ...(!terminal ? { title: status.title, description: status.description } : {}),+ });emitPiSubagentStatus(status);for (const task of status.tasks) dispatchPiSubagentApproval(status, task);}@@ -4642,7 +4661,7 @@ export class PiAgent extends BaseAgent {// deleted the approval dedupe state, so the same pendingApproval was// offered again the instant the file parsed and two decisions raced for// one request. Ask the directory set what actually happened.- const missing = [...piSubagentStatuses].filter(([taskId]) => !newestTaskIds.has(taskId));+ const missing = [...piSubagentStatuses].filter(([, status]) => !seenRunIds.has(status.runId));if (missing.length > 0) {const [runIds, diagnostics] = await Promise.all([listPiSubagentRunDirectoryIds(subagentRunRoot),@@ -4671,18 +4690,31 @@ export class PiAgent extends BaseAgent {if (stale) emitPiSubagentDiagnostic(previous, stale);}}+ // Unreadable statuses are not proof that a previously active run ended.+ active ||= [...piSubagentStatuses.values()].some((status) => !isPiSubagentTerminal(status.state));+ succeeded = true;} catch (error) {deps.logger.warn('pi subagent durable status refresh failed', {message: error instanceof Error ? error.message : String(error),});} finally {piSubagentRefreshInFlight = false;+ if (generation === piSubagentRefreshGeneration) {+ piSubagentNextRefreshAt = refreshStartedAt + (succeeded && !active+ ? PI_SUBAGENT_IDLE_POLL_MS : PI_SUBAGENT_ACTIVE_POLL_MS);+ }}};+ const requestPiSubagentRefresh = async (): Promise<void> => {+ piSubagentRefreshGeneration++;+ piSubagentNextRefreshAt = 0;+ await refreshPiSubagentRuns();+ };const piSubagentRefreshTimer = localSubagentSupported? setInterval(() => {+ if (Date.now() < piSubagentNextRefreshAt) return;void refreshPiSubagentRuns();- }, 500)+ }, PI_SUBAGENT_ACTIVE_POLL_MS): null;let piSubagentRefreshTimerCleared = false;const clearPiSubagentRefreshTimer = (): void => {@@ -4691,7 +4723,7 @@ export class PiAgent extends BaseAgent {if (piSubagentRefreshTimer) clearInterval(piSubagentRefreshTimer);};piSubagentRefreshTimer?.unref?.();- if (localSubagentSupported) void refreshPiSubagentRuns();+ if (localSubagentSupported) void requestPiSubagentRefresh();// Cindy 侧对 pi plan 模式的镜像态;setPlanMode 经 /plan toggle 驱动,与 pi 内部// planModeEnabled 保持一致(RPC 下 Execute/Refine 选择框被 auto-cancel,pi 不会自行// 翻转,故镜像不漂移)。@@ -4968,19 +5000,26 @@ export class PiAgent extends BaseAgent {// cannot rule out a launch already in flight inside it, even if the// process exits before the scan returns.const scanFollowsExit = piProcessExited;- const [directoryCount, statuses] = await Promise.all([+ const [directoryCount, inspected] = await Promise.all([countPiSubagentRunDirectories(subagentRunRoot),- listPiSubagentRuns(subagentRunRoot),+ (async () => {+ let readable = 0;+ const activeStatuses: PiSubagentRunStatus[] = [];+ for await (const status of scanPiSubagentRuns(subagentRunRoot)) {+ readable++;+ if (!isPiSubagentTerminal(status.state)) activeStatuses.push(status);+ }+ return { readable, activeStatuses };+ })(),]);- const active = statuses.some((status) => !isPiSubagentTerminal(status.state));- const allDirectoriesReadable = statuses.length === directoryCount;+ const active = inspected.activeStatuses.length > 0;+ const allDirectoriesReadable = inspected.readable === directoryCount;settleInitialInspection();// Approval delivery keeps running while any detached run is live. The// decision/delivery dedupe sets are the same ones the foreground timer// used, so a request already answered before close is never re-asked.if (localSubagentSupported && !leaseDisposed) {- for (const status of statuses) {- if (isPiSubagentTerminal(status.state)) continue;+ for (const status of inspected.activeStatuses) {for (const task of status.tasks) dispatchPiSubagentApproval(status, task);}}@@ -5279,6 +5318,7 @@ export class PiAgent extends BaseAgent {'PI Subagent runner request is unavailable',);}+ void requestPiSubagentRefresh();return true;},emitExtensionNotification: (message, event) => {@@ -6926,7 +6966,7 @@ export class PiAgent extends BaseAgent {await controlPiSubagentRuns(subagentRunRoot, taskId, 'stop', {runtimeOwnerId: subagentRuntimeOwnerId,});- await refreshPiSubagentRuns();+ await requestPiSubagentRefresh();},async resumeBackgroundTask(taskId: string, message: string, childId?: string): Promise<void> {@@ -6955,7 +6995,7 @@ export class PiAgent extends BaseAgent {runtimeSnapshot: { modelsJson, bridgeSource, runnerSource },}, childId);if (!runId) throw new Error('No terminal PI Subagent run is available to resume.');- await refreshPiSubagentRuns();+ await requestPiSubagentRefresh();})();// close() waits for every resume that entered while this handle was// live before inspecting durable runs and transferring the proxy-tokendiff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex c6c204101c..9096717870 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -765,13 +765,72 @@ async function readSmallJson(file: string): Promise<unknown> {if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_STATUS_BYTES) {throw new Error('oversized, linked, or non-file subagent status');}- return JSON.parse(await fs.readFile(file, 'utf8')) as unknown;+ const handle = await fs.open(file, 'r');+ try {+ // Bound the actual read as well as the preflight stat: a concurrent writer+ // must not turn a small status into an unbounded readFile allocation.+ const buffer = Buffer.allocUnsafe(stat.size + 1);+ let used = 0;+ while (used < buffer.length) {+ const { bytesRead } = await handle.read(buffer, used, buffer.length - used, used);+ if (bytesRead === 0) break;+ used += bytesRead;+ }+ if (used > stat.size) throw new Error('subagent status changed size while reading');+ return JSON.parse(buffer.toString('utf8', 0, used)) as unknown;+ } finally { await handle.close(); }}export function isPiSubagentTerminal(state: PiSubagentRunState): boolean {return state === 'completed' || state === 'failed' || state === 'stopped';}+/** Empty/settled roots do not need the cadence used for active approvals. */+export const PI_SUBAGENT_ACTIVE_POLL_MS = 500;+export const PI_SUBAGENT_IDLE_POLL_MS = 2_000;++/** Background polling consumes one bounded status at a time, not Promise.all(history). */+export async function* scanPiSubagentRuns(+ root: string,+ options: { latestPerTask?: boolean } = {},+): AsyncGenerator<PiSubagentRunStatus> {+ if (options.latestPerTask) {+ // Directory order is not generation order. Select using small identities+ // first so an old run cannot publish a result/approval before its successor.+ // Re-read only the selected payloads instead of retaining every output.+ const newest = new Map<string, { runId: string; startedAt: number }>();+ for await (const status of scanPiSubagentRuns(root)) {+ const previous = newest.get(status.taskId);+ if (!previous || status.startedAt > previous.startedAt+ || (status.startedAt === previous.startedAt && status.runId.localeCompare(previous.runId) > 0)) {+ newest.set(status.taskId, { runId: status.runId, startedAt: status.startedAt });+ }+ }+ for (const [taskId, selected] of newest) {+ let status: PiSubagentRunStatus | null;+ try {+ status = parseStatus(await readSmallJson(path.join(root, selected.runId, 'status.json')), selected.runId);+ } catch { continue; }+ if (status?.taskId === taskId && status.startedAt === selected.startedAt+ && !isPiSubagentRunStale(status, Date.now())) yield status;+ }+ return;+ }+ let directory: Awaited<ReturnType<typeof fs.opendir>>;+ try { directory = await fs.opendir(root); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ for await (const entry of directory) {+ if (!entry.isDirectory() || !RUN_DIR_RE.test(entry.name)) continue;+ let status: PiSubagentRunStatus | null;+ try {+ status = parseStatus(await readSmallJson(path.join(root, entry.name, 'status.json')), entry.name);+ } catch { continue; }+ if (status && !isPiSubagentRunStale(status, Date.now())) yield status;+ }+}+/*** Read the live command line for `pid`, or null when it cannot be established.*@@ -1406,23 +1465,9 @@ export async function listPiSubagentRunDirectoryIds(root: string): Promise<strin}export async function listPiSubagentRuns(root: string): Promise<PiSubagentRunStatus[]> {- const runIds = await listRunDirectoryIds(root);- const now = Date.now();- const statuses = await Promise.all(runIds- .map(async (runId): Promise<PiSubagentRunStatus | null> => {- try {- return parseStatus(- await readSmallJson(path.join(root, runId, 'status.json')),- runId,- );- } catch {- return null;- }- }));- return statuses- .filter((status): status is PiSubagentRunStatus => status !== null)- .filter((status) => !isPiSubagentRunStale(status, now))- .sort((left, right) => right.startedAt - left.startedAt || right.runId.localeCompare(left.runId));+ const statuses: PiSubagentRunStatus[] = [];+ for await (const status of scanPiSubagentRuns(root)) statuses.push(status);+ return statuses.sort((left, right) => right.startedAt - left.startedAt || right.runId.localeCompare(left.runId));}export async function listPiSubagentRunDiagnostics(root: string): Promise<PiSubagentRunDiagnostic[]> {