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(desktop): script 通道意识 out_file 落盘 + jira.add_comment 支持 ADF 正文 (#1696)

yan9a4ac6793793
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
index d49276bc79..aa51395b35 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
@@ -306,7 +306,7 @@ describe('withCardToken(令牌注入纯函数)', () => {
it('inFlightCallInfoOf 只认真正在途:交卷/重开/查无一律 null(workspace 凭证语义)', () => {
const { svc } = makeService();
svc.registerCall('c1', { ghostId: 'g1', toolUseId: null, sessionId: 's1' });
- expect(svc.inFlightCallInfoOf('c1')).toEqual({ ghostId: 'g1', sessionId: 's1' });
+ expect(svc.inFlightCallInfoOf('c1')).toEqual({ ghostId: 'g1', sessionId: 's1', scriptWorkdir: null, scriptWritePath: null, channel: 'session' });
// 交卷后:宽限窗内 callInfoOf 仍可查(卡片供片语义),但在途凭证必须失效。
svc.finalizeCall('c1');
expect(svc.callInfoOf('c1')).not.toBeNull();
@@ -316,6 +316,40 @@ describe('withCardToken(令牌注入纯函数)', () => {
expect(svc.inFlightCallInfoOf('c1')).toBeNull();
expect(svc.inFlightCallInfoOf('nope')).toBeNull();
});
+
+ it('脚本通道条目:callInfoOf 带出 scriptWorkdir;供片拒绝;finalize 即失在途资格', () => {
+ const { svc, broadcast, advance } = makeService();
+ svc.registerCall('c1', { ghostId: 'g1', toolUseId: null, sessionId: null, scriptWorkdir: 'D:\\proj', channel: 'script' });
+ // fs 槽 workdir 档凭 scriptWorkdir 定位脚本通道的写入根。
+ expect(svc.callInfoOf('c1')).toEqual({ ghostId: 'g1', sessionId: null, scriptWorkdir: 'D:\\proj' });
+ // 在途期间严格查询命中(带 scriptWorkdir);交卷后立即失效——不等宽限窗、
+ // 不等懒清扫(目录授权上下文用完即废,review M1)。
+ expect(svc.inFlightCallInfoOf('c1')).toEqual({ ghostId: 'g1', sessionId: null, scriptWorkdir: 'D:\\proj', scriptWritePath: null, channel: 'script' });
+ svc.finalizeCall('c1');
+ expect(svc.callInfoOf('c1')).not.toBeNull(); // 宽限窗:卡片供片语义保留
+ expect(svc.inFlightCallInfoOf('c1')).toBeNull(); // 目录授权:交卷即失效
+ // 脚本通道无 sessionId/toolUseId 锚点:供片拒,broadcast 不发生。
+ const r = svc.handleCardUpdate('g1', update('c1'));
+ expect(r.accepted).toBe(false);
+ expect(r.reason).toBe('script-call-no-card');
+ expect(broadcast).not.toHaveBeenCalled();
+ // 拒卡后账本无卡:report-height / card-action 等邻近入口无卡可锚,
+ // 脚本条目不会经旁路入口被开出卡片面(review)。
+ expect(svc.hasCard('c1')).toBe(false);
+ // 条目最终随「宽限窗过期 + 下一次写操作触发懒清扫」回收(账本卫生)。
+ advance(31_000); // > SWEEP_MIN_INTERVAL_MS(30s) 且 > GRACE_MS(10s)
+ svc.registerCall('c2', { ghostId: 'g1', toolUseId: null, sessionId: null, scriptWorkdir: 'D:\\proj', channel: 'script' });
+ expect(svc.callInfoOf('c1')).toBeNull();
+ });
+
+ it('脚本通道判据是显式 channel:workingDir 空白(scriptWorkdir null)的条目同样拒卡(review m2)', () => {
+ const { svc, broadcast } = makeService();
+ svc.registerCall('c1', { ghostId: 'g1', toolUseId: null, sessionId: null, scriptWorkdir: null, channel: 'script' });
+ const r = svc.handleCardUpdate('g1', update('c1'));
+ expect(r.accepted).toBe(false);
+ expect(r.reason).toBe('script-call-no-card');
+ expect(broadcast).not.toHaveBeenCalled();
+ });
});
describe('parseCardHeightReport(report-height IPC 校验 + clamp 纯函数)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
index db9842ef1a..fc0b967647 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
@@ -36,20 +36,33 @@ interface HarnessOverrides {
saveWrite?: FsSlotDeps['writeSaveDeposit'];
callSessionId?: string | null;
callGhostId?: string;
+ /** 脚本通道条目的落盘根(schedule.workingDir);undefined = 会话调用不带。 */
+ callScriptWorkdir?: string | null;
+ /** 脚本声明的唯一可写相对路径(out_file);非 null 时只放行该路径。 */
+ callScriptWritePath?: string | null;
+ /** 条目通道;缺省按 callSessionId 推导(null ⇒ script,否则 session)。 */
+ callChannel?: 'session' | 'script';
+ /** 严格在途查询结果:false = 模拟已交卷/已清扫(返回 null)。缺省 true。 */
+ inFlight?: boolean;
}
function makeHarness(dataRoot: string, overrides: HarnessOverrides = {}) {
const confirmCalls: string[] = [];
+ const entryFor = (callId: string) =>
+ callId === 'call-1'
+ ? {
+ ghostId: overrides.callGhostId ?? GHOST_ID,
+ sessionId: overrides.callSessionId === undefined ? 'sess-1' : overrides.callSessionId,
+ scriptWorkdir: overrides.callScriptWorkdir ?? null,
+ scriptWritePath: overrides.callScriptWritePath ?? null,
+ channel: overrides.callChannel ?? (overrides.callSessionId === null ? 'script' as const : 'session' as const),
+ }
+ : null;
const deps: FsSlotDeps = {
getGhost: (id) => (id === GHOST_ID ? makeGhost(overrides.slots ?? ['fs']) : null),
dataRootDir: () => dataRoot,
- callInfo: (callId) =>
- callId === 'call-1'
- ? {
- ghostId: overrides.callGhostId ?? GHOST_ID,
- sessionId: overrides.callSessionId === undefined ? 'sess-1' : overrides.callSessionId,
- }
- : null,
+ callInfo: entryFor,
+ inFlightCallInfo: (callId) => (overrides.inFlight === false ? null : entryFor(callId)),
getSessionSnapshot: async () => (overrides.session === undefined ? null : overrides.session),
requestWriteConfirm: async (sessionId) => {
confirmCalls.push(sessionId);
@@ -350,4 +363,113 @@ describe('GhostFsSlot', () => {
expect(r).toMatchObject({ ok: false });
expect(fs.existsSync(path.join(outside, 'escape.txt'))).toBe(false);
});
+
+ it('workdir(脚本通道):无会话但带 scriptWorkdir 的调用直写落盘、不弹确认卡', async () => {
+ const { slot, confirmCalls } = makeHarness(dataRoot, {
+ callSessionId: null,
+ callScriptWorkdir: workdir,
+ });
+ const r = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'reports/result.json', content: '{"n":1}', callId: 'call-1',
+ });
+ expect(r).toMatchObject({ ok: true, op: 'write', path: 'reports/result.json' });
+ // 脚本通道无会话可弹确认卡:直写,确认桥零调用。
+ expect(confirmCalls).toHaveLength(0);
+ expect(await fs.promises.readFile(path.join(workdir, 'reports', 'result.json'), 'utf8')).toBe('{"n":1}');
+ });
+
+ it('workdir(脚本通道):无会话且无 scriptWorkdir 仍拒(无上下文不落盘的回归)', async () => {
+ const { slot } = makeHarness(dataRoot, { callSessionId: null });
+ const r = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'x.md', content: 'x', callId: 'call-1',
+ });
+ expect(r).toMatchObject({ ok: false });
+ expect((r as { message: string }).message).toContain('未配置有效的工作目录');
+ });
+
+ it('workdir:会话通道的无会话调用(sessionId null)报「无会话上下文」,不冒名脚本通道(review nit)', async () => {
+ // resolveSessionContext 查无时会登记 channel:'session' + sessionId:null——
+ // 照拒,但话术必须保住「无会话上下文」,不能误报「脚本通道」。
+ const { slot } = makeHarness(dataRoot, { callSessionId: null, callChannel: 'session' });
+ const r = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'x.md', content: 'x', callId: 'call-1',
+ });
+ expect(r).toMatchObject({ ok: false });
+ expect((r as { message: string }).message).toContain('无会话上下文');
+ });
+
+ it('workdir(脚本通道):已交卷/已清扫的 callId 立即失效(用完即废,review M1)', async () => {
+ // inFlight:false 模拟条目已 settle/回收——即使归属账(宽限窗)里还查得到,
+ // 目录授权也必须在交卷时点失效,不等懒清扫。
+ const { slot } = makeHarness(dataRoot, {
+ callSessionId: null,
+ callScriptWorkdir: workdir,
+ inFlight: false,
+ });
+ const r = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'late/poison.json', content: 'x', callId: 'call-1',
+ });
+ expect(r).toMatchObject({ ok: false });
+ expect((r as { message: string }).message).toContain('授权已失效');
+ expect(fs.existsSync(path.join(workdir, 'late', 'poison.json'))).toBe(false);
+ });
+
+ it('workdir(脚本通道):越界路径/不存在的根/非绝对根都拒', async () => {
+ const { slot } = makeHarness(dataRoot, { callSessionId: null, callScriptWorkdir: workdir });
+ // 越界相对路径:全套路径纪律对脚本通道同样生效。
+ expect(await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: '../escape.txt', content: 'x', callId: 'call-1',
+ })).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmpRoot, 'escape.txt'))).toBe(false);
+ // 根不存在:fail-closed,不为脚本通道自动 mkdir 根目录。
+ const missing = makeHarness(dataRoot, {
+ callSessionId: null,
+ callScriptWorkdir: path.join(tmpRoot, 'no-such-dir'),
+ });
+ const rMissing = await missing.slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'x.md', content: 'x', callId: 'call-1',
+ });
+ expect(rMissing).toMatchObject({ ok: false });
+ expect((rMissing as { message: string }).message).toContain('脚本工作目录不存在');
+ // 失败必须无副作用:根目录没有被顺手建出来。
+ expect(fs.existsSync(path.join(tmpRoot, 'no-such-dir'))).toBe(false);
+ // 非绝对根:登记侧只应放绝对路径,这里防御性拒。
+ const relative = makeHarness(dataRoot, { callSessionId: null, callScriptWorkdir: 'relative/dir' });
+ expect(await relative.slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'x.md', content: 'x', callId: 'call-1',
+ })).toMatchObject({ ok: false });
+ });
+
+ it('workdir(脚本通道):登记后工作目录被删 → realpath fail-closed,不自动重建根目录', async () => {
+ const doomed = path.join(tmpRoot, 'doomed-workdir');
+ await fs.promises.mkdir(doomed, { recursive: true });
+ const { slot } = makeHarness(dataRoot, { callSessionId: null, callScriptWorkdir: doomed });
+ await fs.promises.rm(doomed, { recursive: true, force: true });
+ const r = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'x.md', content: 'x', callId: 'call-1',
+ });
+ expect(r).toMatchObject({ ok: false });
+ expect((r as { message: string }).message).toContain('脚本工作目录不存在');
+ expect(fs.existsSync(doomed)).toBe(false);
+ });
+
+ it('workdir(脚本通道):路径白名单——只放行恰好等于 out_file 的写入(review P1 第五轮)', async () => {
+ const { slot } = makeHarness(dataRoot, {
+ callSessionId: null,
+ callScriptWorkdir: workdir,
+ callScriptWritePath: 'reports/result.json',
+ });
+ // 声明路径:放行。
+ const ok = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'reports/result.json', content: '{}', callId: 'call-1',
+ });
+ expect(ok).toMatchObject({ ok: true });
+ // 根内其它路径(合法相对路径但未声明):拒——在途插件写不了 src/ 等无关文件。
+ const denied = await slot.handleFsRequest(GHOST_ID, {
+ type: 'fs-request', op: 'write', root: 'workdir', path: 'src/evil.ts', content: 'x', callId: 'call-1',
+ });
+ expect(denied).toMatchObject({ ok: false });
+ expect((denied as { message: string }).message).toContain('仅授权写入');
+ expect(fs.existsSync(path.join(workdir, 'src', 'evil.ts'))).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/cardService.ts b/apps/desktop/src/main/cindy-brain/cardService.ts
index ddc1e63479..8fb40b64c3 100644
--- a/apps/desktop/src/main/cindy-brain/cardService.ts
+++ b/apps/desktop/src/main/cindy-brain/cardService.ts
@@ -12,6 +12,15 @@
* 注 xdt_card_id)。finalize 后留 GRACE_MS 宽限窗兜"最后一版在交卷竞态里
* 晚到"的毛刺,窗外拒绝——无限接受会给已完结消息留远程改写面。
*
+ * 无会话调用方(2026-08-04,scheduler「仅运行脚本」通道):脚本经 broker 直调
+ * 意识,没有 agent session,但意识泄洪落盘(root:'workdir')仍凭 callId 定位
+ * 写入根。broker 同样在派发前 registerCall、交卷后 finalizeCall,登记时把
+ * schedule.workingDir 记为条目的 scriptWorkdir(sessionId 恒 null)——fs 槽
+ * 凭它把写盘钳在该目录内,条目随同一套 finalize/宽限/清扫节奏失效,旧
+ * callId 不能跨调用复用(与 inFlightCallInfoOf 注释的目录授权不变量同源)。
+ * 脚本通道条目拒绝卡片供片(sessionId/toolUseId 均无锚,broadcast 出去是
+ * 孤儿卡)。
+ *
* 依赖全注入(规则 14),纯逻辑可用内存 harness 直测,不碰 Electron。
*/
@@ -144,6 +153,25 @@ interface CallEntry {
ghostId: string;
toolUseId: string | null;
sessionId: string | null;
+ /**
+ * 调用通道:'session' = 会话内 ghost_call(默认);'script' = scheduler
+ * 「仅运行脚本」broker 直调。显式字段而非由 sessionId/scriptWorkdir 推导
+ * ——workingDir 空白的脚本条目(scriptWorkdir null)也必须被识别为脚本
+ * 通道(拒卡判据),不能与会话通道的无会话调用混淆(review m2)。
+ */
+ channel: 'session' | 'script';
+ /**
+ * 脚本通道(「仅运行脚本」broker 直调)的落盘根:登记时取 schedule.workingDir,
+ * 普通会话调用恒 null。fs 槽 root:'workdir' 在 sessionId 为空时凭它定位
+ * 写入根(授权来源 = schedule 自身的工作目录配置,意识自报路径被钳在根内)。
+ */
+ scriptWorkdir: string | null;
+ /**
+ * 脚本声明的唯一可写相对路径(broker 登记的 out_file 原值):非 null 时
+ * fs 槽只放行恰好等于它的写入——调用在途期间插件也写不了根内其它文件
+ * (review P1 第五轮:写窗收窄到脚本声明的单个文件)。
+ */
+ scriptWritePath: string | null;
hasCard: boolean;
lastAcceptedAt: number | null;
settledAt: number | null;
@@ -201,13 +229,26 @@ export class GhostCardService {
/** 派发 tool-call 前登记(callId 由调用方铸造,与管子下行同值)。 */
registerCall(
callId: string,
- info: { ghostId: string; toolUseId: string | null; sessionId: string | null },
+ info: {
+ ghostId: string;
+ toolUseId: string | null;
+ sessionId: string | null;
+ /** 脚本通道调用方传入 schedule.workingDir;普通会话调用省略。 */
+ scriptWorkdir?: string | null;
+ /** 脚本通道调用方传入脚本声明的 out_file(唯一可写相对路径);无写窗时省略。 */
+ scriptWritePath?: string | null;
+ /** 脚本通道调用方传 'script';缺省 'session'(会话内 ghost_call)。 */
+ channel?: 'script';
+ },
): void {
this.sweep();
this.calls.set(callId, {
ghostId: info.ghostId,
toolUseId: info.toolUseId,
sessionId: info.sessionId,
+ channel: info.channel ?? 'session',
+ scriptWorkdir: info.scriptWorkdir ?? null,
+ scriptWritePath: info.scriptWritePath ?? null,
hasCard: false,
lastAcceptedAt: null,
settledAt: null,
@@ -243,23 +284,25 @@ export class GhostCardService {
/**
* 内存条目全息查询(card-action 派发用):除归属外带出 sessionId——
* 铸衍生卡位(spawnCallId)登记时要续上会话归属,历史回放才能按会话
- * 捞回衍生卡。查无 null(由持久卡库兜底)。
+ * 捞回衍生卡。查无 null(由持久卡库兜底)。fs 槽 workdir 档也经它反查
+ * (含 scriptWorkdir——脚本通道的落盘根)。
*/
- callInfoOf(callId: string): { ghostId: string; sessionId: string | null } | null {
+ callInfoOf(callId: string): { ghostId: string; sessionId: string | null; scriptWorkdir: string | null } | null {
const e = this.calls.get(callId);
- return e ? { ghostId: e.ghostId, sessionId: e.sessionId } : null;
+ return e ? { ghostId: e.ghostId, sessionId: e.sessionId, scriptWorkdir: e.scriptWorkdir } : null;
}
/**
- * 严格在途查询(workspace 槽的上下文凭证用):仅当该单已登记、未交卷
- * (settledAt 为 null)且非重开态时返回归属。宽限窗/重开窗/working 窗都是
- * 卡片供片语义,不能让 callId 在工具调用结束后继续充当"目录授权上下文"
- * ——否则插件记住一个旧 callId 就能跨调用复用当时会话的 workdir 自动放行。
+ * 严格在途查询(workspace 槽的上下文凭证、fs 槽脚本通道的写盘授权用):
+ * 仅当该单已登记、未交卷(settledAt 为 null)且非重开态时返回归属。
+ * 宽限窗/重开窗/working 窗都是卡片供片语义,不能让 callId 在工具调用
+ * 结束后继续充当"目录授权上下文"——否则插件记住一个旧 callId 就能跨
+ * 调用复用当时会话的 workdir 自动放行。
*/
- inFlightCallInfoOf(callId: string): { ghostId: string; sessionId: string | null } | null {
+ inFlightCallInfoOf(callId: string): { ghostId: string; sessionId: string | null; scriptWorkdir: string | null; scriptWritePath: string | null; channel: 'session' | 'script' } | null {
const e = this.calls.get(callId);
if (!e || e.settledAt !== null || e.reopenedAt !== null) return null;
- return { ghostId: e.ghostId, sessionId: e.sessionId };
+ return { ghostId: e.ghostId, sessionId: e.sessionId, scriptWorkdir: e.scriptWorkdir, scriptWritePath: e.scriptWritePath, channel: e.channel };
}
/**
@@ -283,6 +326,10 @@ export class GhostCardService {
ghostId: info.ghostId,
toolUseId: null,
sessionId: info.sessionId,
+ // 交互卡重开只发生在会话通道(脚本通道条目拒供片,无卡可点)。
+ channel: 'session',
+ scriptWorkdir: null,
+ scriptWritePath: null,
hasCard: true,
lastAcceptedAt: null,
settledAt: null,
@@ -331,6 +378,10 @@ export class GhostCardService {
// 拿着别人的单号供片:归属验身失败(与 pipeDispatcher"不是你的卷子"同款)。
return reject('not-owner', { callId: p.callId, owner: entry.ghostId });
}
+ // 脚本通道(broker 直调,无会话)条目:sessionId/toolUseId 均无锚,broadcast
+ // 出去是孤儿卡——供片语义不成立,直接拒(fs 落盘反查不受影响)。判据用显式
+ // channel 字段:workingDir 空白(scriptWorkdir null)的脚本条目同样拒。
+ if (entry.channel === 'script') return reject('script-call-no-card', { callId: p.callId });
if (!this.deps.hasCardSlot(senderGhostId)) return reject('no-card-slot');
const now = this.now();
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 82388a4445..97f3040dcc 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2615,7 +2615,11 @@ await cindy.fs({ op: 'write', root: 'data', path: 'a.txt', content: 'hi' });
(主机凭它定位会话,不认自报)。**是否放行跟随该会话的权限模式**——agent
编辑文件免批的模式直接写;逐条确认的模式会弹确认卡请用户点头(同目录本
会话批一次);计划/只读模式一律拒。SSH 远程工作区会话不支持(目录在远端
- 机器),会明确报错,请改用 root:'data';
+ 机器),会明确报错,请改用 root:'data'。例外:scheduler「仅运行脚本」通道
+ (无会话的定时脚本直调)下发的调用,以该 schedule 配置的工作目录为写入根
+ 直接放行——没有会话就没有权限模式可跟随,授权来自 schedule 配置本身;
+ 该通道的写入必须在当次 tool-call 处理期间完成,交卷后 callId 立即失效
+ (比会话通道更严:无宽限,先写盘再交卷);
- \`root:'save'\` **过户目录**:仅 write,凭主 agent 在 ghost_call 顶层传 \`save_dir\`
过户后注入的 \`args.save_deposit.token\` 写入(与 §4.7 fetch \`as:'file'\` 下载
落盘同一张票:限时、限次数、限字节、文件名主机消毒、永不覆盖已有文件)。
diff --git a/apps/desktop/src/main/cindy-brain/fsSlot.ts b/apps/desktop/src/main/cindy-brain/fsSlot.ts
index ba5595839b..b0a1e3bd38 100644
--- a/apps/desktop/src/main/cindy-brain/fsSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/fsSlot.ts
@@ -14,6 +14,16 @@
* 直写、逐条模式弹 fs_write 确认卡、plan 拒);远程工作区
* (remoteHostId 非空)明确拒——路径在远端机器,本地代写
* 写不到(规则 26,首期不支持不静默坏)。
+ * 例外分支(2026-08-04):callId 属于「仅运行脚本」通道的
+ * 调用时(无会话,cardService 条目带 scriptWorkdir =
+ * schedule.workingDir),以该目录为写入根直写——无会话就
+ * 没有 permission 模式可跟随、也无人在场可弹确认卡;
+ * 授权来源是 schedule 自身的工作目录配置(script-runner
+ * 本就以此目录 spawn 用户配置的命令,脚本进程对该目录
+ * 有完整写权,意识代写不扩大写面)。脚本通道的 callId
+ * 反查走**严格在途**查询(inFlightCallInfo,与 workspace
+ * 槽同一判据):交卷即失效,不享卡片供片的宽限窗——目录
+ * 授权上下文必须用完即废。
* 'save' 主 agent 过户的 save 票据目录——仅 write;复用
* saveDeposit 票据库的 TTL/次数/字节预算与文件名消毒去重
* (与 fetch as:'file' 下载落盘同一本账)。
@@ -68,8 +78,24 @@ export interface FsSlotDeps {
getGhost(id: string): InstalledGhost | null;
/** 私有数据目录根(生产 = userData/ghost-fs;意识各占 <root>/<ghostId>)。 */
dataRootDir(): string;
- /** callId → 归属反查(生产 = cardService.callInfoOf;不信意识自报)。 */
- callInfo(callId: string): { ghostId: string; sessionId: string | null } | null;
+ /** callId → 归属反查(生产 = cardService.callInfoOf;不信意识自报)。
+ * scriptWorkdir 仅脚本通道条目带(schedule.workingDir),会话调用为 null。 */
+ callInfo(callId: string): { ghostId: string; sessionId: string | null; scriptWorkdir: string | null } | null;
+ /**
+ * callId → 严格在途反查(生产 = cardService.inFlightCallInfoOf):已交卷/
+ * 已清扫的条目返回 null。脚本通道(root:'workdir' 无会话分支)必须走它——
+ * 目录授权上下文在工具调用结束后不得继续有效(用完即废);会话通道沿用
+ * callInfo 宽限窗口径(有 permission 裁决第二道闸,既有行为不变)。
+ * channel 用于拒绝话术分流(会话通道的无会话调用 ≠ 脚本通道);
+ * scriptWritePath(脚本声明的 out_file)非空时只放行该路径。
+ */
+ inFlightCallInfo(callId: string): {
+ ghostId: string;
+ sessionId: string | null;
+ scriptWorkdir: string | null;
+ scriptWritePath: string | null;
+ channel: 'session' | 'script';
+ } | null;
/** sessionId → 会话快照(生产查 localDb sessions 行;查无返回 null)。 */
getSessionSnapshot(sessionId: string): Promise<FsSessionSnapshot | null>;
/**
@@ -458,7 +484,7 @@ export class GhostFsSlot {
return { ok: true, op: 'write', path: written.fileName, bytes: decoded.bytes.byteLength };
}
- /* ── root:'workdir' 会话工作目录(跟随会话 permission)──────────────── */
+ /* ── root:'workdir' 会话工作目录(跟随会话 permission;脚本通道例外直写)── */
private async handleWorkdirWrite(
ghostId: string,
@@ -471,26 +497,63 @@ export class GhostFsSlot {
}
const info = this.deps.callInfo(callId);
if (!info || info.ghostId !== ghostId) return fail('callId 无效或不属于本意识');
- if (!info.sessionId) return fail('本次调用无会话上下文,无法定位工作目录');
- const session = await this.deps.getSessionSnapshot(info.sessionId);
- if (!session) return fail('会话不存在,无法定位工作目录');
- if (session.remoteHostId) {
- return fail('当前会话是 SSH 远程工作区,工作目录在远端机器,意识写文件暂不支持(请改用 root:"data" 私有目录)');
- }
- if (!session.workingDir || !path.isAbsolute(session.workingDir)) {
- return fail('当前会话没有本地工作目录');
+
+ // 写入根两个来源(同一 callId 账本反查,都不信意识自报):
+ // - 会话通道:session 快照的 workingDir,放行与否跟随会话 permission 模式;
+ // - 脚本通道:登记时的 scriptWorkdir(schedule.workingDir),无会话可裁、
+ // 无人可弹确认卡——直写(schedule 配置即授权,见文件头例外分支注释)。
+ // 脚本通道必须走严格在途查询:callInfo 的宽限窗是卡片供片语义,不能
+ // 充当目录授权——交卷后旧 callId 继续可写就是"记住单号跨调用复用
+ // workdir 写权"(review M1:懒清扫间隔内窗口实际无上界)。
+ let workdirSource: 'session' | 'script';
+ let session: FsSessionSnapshot | null = null;
+ let workingDir: string;
+ let scriptWritePath: string | null = null;
+ if (info.sessionId) {
+ workdirSource = 'session';
+ session = await this.deps.getSessionSnapshot(info.sessionId);
+ if (!session) return fail('会话不存在,无法定位工作目录');
+ if (session.remoteHostId) {
+ return fail('当前会话是 SSH 远程工作区,工作目录在远端机器,意识写文件暂不支持(请改用 root:"data" 私有目录)');
+ }
+ if (!session.workingDir || !path.isAbsolute(session.workingDir)) {
+ return fail('当前会话没有本地工作目录');
+ }
+ workingDir = session.workingDir;
+ } else {
+ const inFlight = this.deps.inFlightCallInfo(callId);
+ if (!inFlight || inFlight.ghostId !== ghostId) {
+ return fail('调用已交卷或已过期,工作目录写盘授权已失效');
+ }
+ if (inFlight.scriptWorkdir && path.isAbsolute(inFlight.scriptWorkdir)) {
+ workdirSource = 'script';
+ workingDir = inFlight.scriptWorkdir;
+ scriptWritePath = inFlight.scriptWritePath;
+ } else {
+ // 话术按通道分流:会话通道的无会话调用(resolveSessionContext 查无)
+ // 不是脚本通道,别报「脚本通道」误导(review nit)。
+ return fail(inFlight.channel === 'script'
+ ? '脚本通道未配置有效的工作目录,无法定位写入根'
+ : '本次调用无会话上下文,无法定位工作目录');
+ }
}
+
const reason = validateFsRelPath(req.path);
if (reason) return fail(reason);
const relPath = req.path as string;
+ // 脚本通道的路径白名单(review P1 第五轮):只能写脚本显式声明的
+ // out_file——调用在途期间插件也写不了根内其它文件(src/ 等)。
+ if (workdirSource === 'script' && scriptWritePath !== null && relPath !== scriptWritePath) {
+ return fail(`本次调用仅授权写入脚本声明的 out_file(${scriptWritePath})`);
+ }
const decoded = decodeContent(req.content, req.encoding);
if ('error' in decoded) return fail(decoded.error);
let realWorkdir: string;
try {
- realWorkdir = await fs.promises.realpath(session.workingDir);
+ realWorkdir = await fs.promises.realpath(workingDir);
} catch {
- return fail('工作目录不存在');
+ return fail(workdirSource === 'script' ? '脚本工作目录不存在' : '工作目录不存在');
}
const target = path.join(realWorkdir, ...relPath.split('/'));
if (!isInsideDir(realWorkdir, target)) return fail('path 越界');
@@ -503,6 +566,23 @@ export class GhostFsSlot {
/* 不存在 = 新建 */
}
+ // 脚本通道直写:无会话可裁、无人可弹确认卡——schedule 配置即授权
+ // (script-runner 本就以此目录 spawn 用户配置的命令,脚本进程对该目录有
+ // 完整写权,意识代写不扩大写面);日志标明 channel 供事后分辨。
+ if (workdirSource === 'script') {
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
+ await fs.promises.writeFile(target, decoded.bytes);
+ this.deps.log?.info('ghost fs write (workdir)', {
+ ghostId,
+ channel: 'script',
+ relPath,
+ bytes: decoded.bytes.byteLength,
+ });
+ return { ok: true, op: 'write', path: relPath, bytes: decoded.bytes.byteLength };
+ }
+ // 会话通道继续往下(session 与 sessionId 在上方分支均已判空;此守卫只做类型收窄与防御)。
+ if (!session || !info.sessionId) return fail('本次调用无会话上下文,无法定位工作目录');
+
const verdict = workdirWriteVerdict(session.permissionMode, session.planModeEnabled);
if (verdict === 'deny') {
return fail('当前会话处于计划/只读模式,不允许写工作目录');
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 9dd82e745c..9d6ed82bfb 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -3358,6 +3358,9 @@ export function getGhostFsSlot(): GhostFsSlot {
// callId → 归属/会话反查:与卡片供片同一本账(ghost_call 派单时
// cardService.registerCall 登记),不信意识自报。
callInfo: (callId) => getGhostCardService().callInfoOf(callId),
+ // 严格在途反查:脚本通道(无会话)的 workdir 写盘授权走它——交卷即失效,
+ // 不享宽限窗(目录授权上下文用完即废,与 workspace 槽同一判据)。
+ inFlightCallInfo: (callId) => getGhostCardService().inFlightCallInfoOf(callId),
getSessionSnapshot: (sessionId) => getSessionFsSnapshot(sessionId),
requestWriteConfirm: async (sessionId, payload) => {
const bridge = getGhostGrantConfirmBridge();
diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
index 331e9faae6..f57f851826 100644
--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
@@ -60,7 +60,7 @@ export interface WorkspaceSlotDeps {
* 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。
*/
showDirectoryDialog(params: { ghostName: string; purpose: string | null }): Promise<string | null>;
- /** 在途 ghost_call 反查(cardService.callInfoOf):查无/过期返回 null。 */
+ /** 在途 ghost_call 反查(cardService.inFlightCallInfoOf):查无/过期返回 null。 */
resolveCallContext(callId: string): { ghostId: string; sessionId: string | null } | null;
/** 会话目录快照(localDb);查无会话返回 null。 */
getSessionDirInfo(
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
index 7eed4512f2..ffa0abd54a 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
@@ -1,6 +1,14 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
import type { Schedule } from '@cindy/maker-scheduler';
+import { GhostCardService } from '../../cindy-brain/cardService.js';
+import { GhostFsSlot } from '../../cindy-brain/fsSlot.js';
+import { GhostPipeDispatcher } from '../../cindy-brain/pipeDispatcher.js';
+import type { GhostPipeToolCall, InstalledGhost } from '../../../shared/ghost.js';
import { SchedulerScriptCapabilityBroker } from '../script-capability-broker';
const sendToSessionMock = vi.hoisted(() => vi.fn());
@@ -16,9 +24,13 @@ const callGhostToolMock = vi.hoisted(() =>
}),
),
);
+// cardService 账本:缺省 void spy(生命周期断言用);端到端用例转发到真实实例。
+const registerCallMock = vi.hoisted(() => vi.fn());
+const finalizeCallMock = vi.hoisted(() => vi.fn());
vi.mock('../../cindy-brain/index.js', () => ({
getGhostPipeDispatcher: () => ({ callGhostTool: callGhostToolMock }),
+ getGhostCardService: () => ({ registerCall: registerCallMock, finalizeCall: finalizeCallMock }),
}));
vi.mock('../../maker-ipc/register.js', () => ({
@@ -63,6 +75,8 @@ describe('SchedulerScriptCapabilityBroker', () => {
sendToSessionMock.mockReset();
callGhostToolMock.mockReset();
callGhostToolMock.mockImplementation(async (request: unknown) => ({ ok: true, result: request }));
+ registerCallMock.mockReset();
+ finalizeCallMock.mockReset();
});
it('maps Jira reads to the current xd-atlassian argument contract', async () => {
@@ -102,6 +116,162 @@ describe('SchedulerScriptCapabilityBroker', () => {
).rejects.toMatchObject({ code: 'INVALID_ARGS' });
});
+ it('adds Jira comments with plain text exactly as before', async () => {
+ const result = await new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.add_comment', params: { issue_key: 'DING-1', body_text: 'done' } },
+ new Set(['jira.comment']),
+ { schedule: schedule() },
+ );
+ expect(result).toMatchObject({
+ ghostId: 'xd-atlassian',
+ tool: 'jira_issues',
+ args: { action: 'add_comment', issue_key: 'DING-1', body_text: 'done' },
+ });
+ // 生命周期同样锁住:add_comment 也走 callGhostForScript——登记形状、同一
+ // callId 下行、交卷 finalize,与 jira.get 同一本账(review:只断回显形状
+ // 会让「漏走登记包装」的回归照样绿)。纯写方法不挂写盘授权(review P1
+ // 第三轮):scriptWorkdir 恒 null。
+ expect(registerCallMock).toHaveBeenCalledTimes(1);
+ const [callId, info] = registerCallMock.mock.calls[0] as [string, Record<string, unknown>];
+ expect(info).toMatchObject({ ghostId: 'xd-atlassian', sessionId: null, channel: 'script', scriptWorkdir: null });
+ expect(callGhostToolMock).toHaveBeenCalledWith(expect.objectContaining({ callId }));
+ expect(finalizeCallMock).toHaveBeenCalledWith(callId);
+ });
+
+ it('write-method grantless: add_comment 在途也不持 workdir 写窗(review P1 第三轮)', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-grantless-'));
+ const { fsSlot } = wireRealChannel(tmp);
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ callGhostToolMock.mockImplementationOnce(async () => { await gate; return { ok: true, result: {} }; });
+ const p = new SchedulerScriptCapabilityBroker()
+ .call(
+ { method: 'jira.add_comment', params: { issue_key: 'DING-1', body_text: 'done' } },
+ new Set(['jira.comment']),
+ { schedule: schedule({ workingDir: tmp }), runId: 'run-w' },
+ )
+ .catch((err: unknown) => err);
+ try {
+ // 调用在途:插件此时调 fs 槽 root:'workdir' 必须被拒——add_comment 是
+ // 纯写方法,结果体小不可能泄洪,给写窗只是白白扩大在途暴露面。
+ const callId = registerCallMock.mock.calls[0][0] as string;
+ const w = await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId, path: 'poison.json', content: 'x',
+ });
+ expect(w).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmp, 'poison.json'))).toBe(false);
+ } finally {
+ release();
+ await p;
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('read-method without out_file: jira.search_jql 在途同样不持写窗(review P1 第四轮)', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-read-grantless-'));
+ const { fsSlot } = wireRealChannel(tmp);
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ callGhostToolMock.mockImplementationOnce(async () => { await gate; return { ok: true, result: {} }; });
+ const p = new SchedulerScriptCapabilityBroker()
+ .call(
+ { method: 'jira.search_jql', params: { jql: 'project = DING' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: tmp }), runId: 'run-r' },
+ )
+ .catch((err: unknown) => err);
+ try {
+ // 读方法不带 out_file:写窗不挂——只授 jira.read 的 schedule 不能让插件
+ // 在调用在途期间写项目目录;插件若自动泄洪只是回落 truncated(与收窄前
+ // 一致,无回归)。
+ const callId = registerCallMock.mock.calls[0][0] as string;
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId, path: 'poison.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmp, 'poison.json'))).toBe(false);
+ } finally {
+ release();
+ await p;
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('forwards ADF comment bodies untouched for real @mentions', async () => {
+ // 2026-08-04 DING-179498:决策评论带 mention 的 ADF 曾被白名单拒收导致丢单。
+ // fixture 用真实 mention 形态(text/accessLevel 等 attrs 全带),防「只透传
+ // 了简化形态、真 payload 被剥字段」的回归(review)。
+ const adf = {
+ type: 'doc',
+ version: 1,
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '请 ' },
+ { type: 'mention', attrs: { id: 'acc-1', text: '@张三', accessLevel: '' } },
+ { type: 'text', text: ' 确认方案' },
+ ],
+ },
+ ],
+ };
+ await new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.add_comment', params: { issue_key: 'DING-2', body_adf: adf } },
+ new Set(['jira.comment']),
+ { schedule: schedule() },
+ );
+ expect(callGhostToolMock).toHaveBeenCalledWith({
+ ghostId: 'xd-atlassian',
+ tool: 'jira_issues',
+ args: { action: 'add_comment', issue_key: 'DING-2', body_adf: adf },
+ callId: expect.any(String),
+ });
+ // 互斥的负向断言:body_adf 分支不得夹带 body_text(review)。
+ const dispatched = callGhostToolMock.mock.calls[0][0] as { args: Record<string, unknown> };
+ expect(dispatched.args).not.toHaveProperty('body_text');
+ });
+
+ it('passes through an empty ADF object (shallow validation defers structure to Jira)', async () => {
+ // body_adf {} 是浅校验放行的合法形态:结构深校验留给 Jira 侧,broker 不自作主张拒。
+ await new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.add_comment', params: { issue_key: 'DING-4', body_adf: {} } },
+ new Set(['jira.comment']),
+ { schedule: schedule() },
+ );
+ expect(callGhostToolMock).toHaveBeenCalledWith(expect.objectContaining({
+ args: { action: 'add_comment', issue_key: 'DING-4', body_adf: {} },
+ }));
+ });
+
+ it('requires exactly one of body_text and body_adf, and body_adf must be an object', async () => {
+ const broker = new SchedulerScriptCapabilityBroker();
+ const call = (params: Record<string, unknown>) =>
+ broker.call(
+ { method: 'jira.add_comment', params: { issue_key: 'DING-3', ...params } },
+ new Set(['jira.comment']),
+ { schedule: schedule() },
+ );
+ // 逐个坏输入断言(不合并批处理,哪个回归一眼可见;review):
+ const badInputs: Array<[string, Record<string, unknown>]> = [
+ ['两传', { body_text: 'x', body_adf: { type: 'doc' } }],
+ ['都不传', {}],
+ ['body_adf 为字符串', { body_adf: '{"type":"doc"}' }],
+ ['body_adf 为数组', { body_adf: [{ type: 'doc' }] }],
+ ['body_adf 为 null', { body_adf: null }],
+ // 非 plain object 的 body_adf 全部拒收(结构深校验留给 Jira 侧);
+ // body_text 空串/空白串走 requireString 同样拒。
+ ['body_text 为空串', { body_text: '' }],
+ ['body_text 为空白串', { body_text: ' ' }],
+ ];
+ for (const [label, params] of badInputs) {
+ await expect(call(params), label).rejects.toMatchObject({ code: 'INVALID_ARGS' });
+ }
+ // 账本无污染:全部坏输入必须在 registerCall 之前被拒——触达 ghost 或在
+ // 账本留孤儿条目(未 finalize 永驻)都算事故(review)。
+ expect(callGhostToolMock).not.toHaveBeenCalled();
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(finalizeCallMock).not.toHaveBeenCalled();
+ });
+
it('lists recently-active feishu chats and forwards incremental start_time', async () => {
const broker = new SchedulerScriptCapabilityBroker();
await broker.call(
@@ -113,6 +283,7 @@ describe('SchedulerScriptCapabilityBroker', () => {
ghostId: 'xd-feishu',
tool: 'call_tool',
args: { name: 'im_list_chats', args: { sort_type: 'ByActiveTimeDesc', page_size: 15 } },
+ callId: expect.any(String),
});
callGhostToolMock.mockClear();
@@ -125,6 +296,7 @@ describe('SchedulerScriptCapabilityBroker', () => {
ghostId: 'xd-feishu',
tool: 'call_tool',
args: { name: 'im_read_messages', args: { container_id: 'oc_1', start_time: '1710000000' } },
+ callId: expect.any(String),
});
await expect(
@@ -153,6 +325,7 @@ describe('SchedulerScriptCapabilityBroker', () => {
ghostId: 'xd-feishu',
tool: 'call_tool',
args: { name: 'im_read_messages', args: { container_id: 'oc_123', page_size: 10 } },
+ callId: expect.any(String),
});
expect(result).toMatchObject({ ok: true, messages: [{ message_id: 'om_1' }] });
@@ -315,8 +488,357 @@ describe('SchedulerScriptCapabilityBroker', () => {
).rejects.toMatchObject({ code: 'INVALID_ARGS' });
expect(sendToSessionMock).not.toHaveBeenCalled();
});
+
+ it('forwards out_file to xd-atlassian and rejects unsafe paths', async () => {
+ const broker = new SchedulerScriptCapabilityBroker();
+ const searched = await broker.call(
+ { method: 'jira.search_jql', params: { jql: 'project = DING', out_file: 'reports/r.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule() },
+ );
+ expect(searched).toMatchObject({ args: { action: 'search_jql', out_file: 'reports/r.json' } });
+ const got = await broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'issue.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule() },
+ );
+ expect(got).toMatchObject({ args: { action: 'get', out_file: 'issue.json' } });
+ // 与 fs 槽同一口径(validateFsRelPath):穿越/绝对/反斜杠/空白一律 INVALID_ARGS。
+ for (const bad of ['../escape.json', '/abs/x.json', 'a\\b.json', '', ' ']) {
+ await expect(
+ broker.call(
+ { method: 'jira.search_jql', params: { jql: 'x', out_file: bad } },
+ new Set(['jira.read']),
+ { schedule: schedule() },
+ ),
+ ).rejects.toMatchObject({ code: 'INVALID_ARGS' });
+ }
+ });
+
+ it('registers script-channel callId before dispatch and finalizes it on success and failure', async () => {
+ const broker = new SchedulerScriptCapabilityBroker();
+ // 跨平台绝对路径(isAbsolute 校验在 broker 登记侧,Windows 盘符路径在
+ // POSIX 上不算绝对,会拿到不同的登记形状)。
+ const absWorkdir = path.resolve(path.sep);
+ await broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'r.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: absWorkdir }) },
+ );
+ // 登记形状:无会话、脚本通道标记、带 schedule.workingDir 作为落盘根
+ // (仅显式带 out_file 的调用才挂写窗,review P1 第四轮)。
+ expect(registerCallMock).toHaveBeenCalledTimes(1);
+ const [callId, info] = registerCallMock.mock.calls[0] as [string, Record<string, unknown>];
+ expect(info).toEqual({
+ ghostId: 'xd-atlassian', toolUseId: null, sessionId: null, scriptWorkdir: absWorkdir, scriptWritePath: 'r.json', channel: 'script',
+ });
+ // 同一 callId 下行给意识;顺序:register → dispatch → finalize。
+ expect(callGhostToolMock).toHaveBeenCalledWith(expect.objectContaining({ callId }));
+ expect(finalizeCallMock).toHaveBeenCalledWith(callId);
+ expect(registerCallMock.mock.invocationCallOrder[0]).toBeLessThan(
+ callGhostToolMock.mock.invocationCallOrder[0],
+ );
+ expect(finalizeCallMock.mock.invocationCallOrder[0]).toBeGreaterThan(
+ callGhostToolMock.mock.invocationCallOrder[0],
+ );
+
+ // 不带 out_file 的读调用不挂写窗(review P1 第四轮):scriptWorkdir null,
+ // 登记/下发/finalize 生命周期不变。
+ registerCallMock.mockClear();
+ await broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: absWorkdir }) },
+ );
+ expect(registerCallMock.mock.calls[0][1]).toMatchObject({ scriptWorkdir: null, channel: 'script' });
+
+ // 失败路径同样 finalize——不 finalize 条目永驻,callId 永久有效(破"用完即废")。
+ registerCallMock.mockClear();
+ finalizeCallMock.mockClear();
+ callGhostToolMock.mockResolvedValueOnce({ ok: false, errorCode: 'GHOST_ASLEEP', message: 'x' });
+ await expect(
+ broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']),
+ { schedule: schedule() },
+ ),
+ ).rejects.toMatchObject({ code: 'GHOST_ASLEEP' });
+ expect(finalizeCallMock).toHaveBeenCalledTimes(1);
+
+ // 畸形 workingDir(相对路径/首尾空白)按 null 登记:fs 槽拒写但查询
+ // 不受影响;条目的 channel:'script' 标记不受影响(review m2/m3/n2)。
+ // 带 out_file 调用才挂写窗,否则畸形校验根本不执行(第四轮收窄)。
+ registerCallMock.mockClear();
+ await broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'x.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: 'relative/dir' }) },
+ );
+ expect(registerCallMock.mock.calls[0][1]).toMatchObject({ scriptWorkdir: null, channel: 'script' });
+
+ // 首尾空白的绝对路径按原值登记(trim 只判空不改写)——与 script-runner
+ // 的 spawn cwd 严格同源,POSIX 上带尾空格的目录名不会让授权根分叉(review)。
+ registerCallMock.mockClear();
+ const padded = `${absWorkdir}${path.sep}padded `;
+ await broker.call(
+ { method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'x.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: padded }) },
+ );
+ expect(registerCallMock.mock.calls[0][1]).toMatchObject({ scriptWorkdir: padded, channel: 'script' });
+ });
+
+ it('端到端:脚本通道 out_file 经真实 cardService + fs 槽落进 schedule 工作目录', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-e2e-'));
+ try {
+ const { fsSlot } = wireRealChannel(tmp);
+ // 模拟意识行为(xd-atlassian 的 deliver 路径):收到 tool-call 后按 out_file
+ // 经 fs 槽 root:'workdir' 泄洪写盘,回 saved_to 相对路径。在途期间顺带
+ // 试探写根内其它路径——白名单必须拒(断言在下方)。
+ let offPathResult: { ok: boolean } | null = null;
+ callGhostToolMock.mockImplementation(async (request: unknown) => {
+ const { callId, args } = request as { callId: string; args: Record<string, unknown> };
+ const outFile = args.out_file as string;
+ const w = await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId, path: outFile, content: '{"issues":[1,2,3]}',
+ });
+ if (!w.ok) return { ok: false, errorCode: 'INTERNAL', message: w.message ?? 'write failed' };
+ offPathResult = await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId, path: 'src/evil.ts', content: 'x',
+ });
+ return { ok: true, result: { saved_to: outFile } };
+ });
+
+ const result = await new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.search_jql', params: { jql: 'project = DING', out_file: 'reports/jira.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: tmp }) },
+ );
+ expect(result).toMatchObject({ saved_to: 'reports/jira.json' });
+ // 字节真身落在 schedule 工作目录内,脚本可按相对路径从自己 cwd 读回。
+ expect(await fs.promises.readFile(path.join(tmp, 'reports', 'jira.json'), 'utf8')).toBe('{"issues":[1,2,3]}');
+ // 路径白名单(review P1 第五轮):在途期间写 out_file 之外的根内路径被拒。
+ expect(offPathResult).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmp, 'src', 'evil.ts'))).toBe(false);
+ // 用完即废(review M1 真断言):broker 已 finalize,同一 callId 再经 fs 槽
+ // 写盘必须被拒——插件在交卷后(含 TIMEOUT 后仍在后台跑的场景)持有的
+ // 旧 callId 不再授权任何写入。
+ const usedCallId = registerCallMock.mock.calls[0][0] as string;
+ const late = await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: usedCallId, path: 'reports/late.json', content: 'x',
+ });
+ expect(late).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmp, 'reports', 'late.json'))).toBe(false);
+ } finally {
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('端到端(穿真实 pipeDispatcher):callId 下行配对、错误折叠、交卷后写拒', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-e2e-pipe-'));
+ try {
+ const { fsSlot } = wireRealChannel(tmp);
+ // 真实 dispatcher:资格审 + callId 配对 + 错误折叠全真,只有「意识进程」
+ // 本身由 sendToGhost 内联模拟(先经 fs 槽写盘,再 handleToolResult 交卷)。
+ let dispatcher!: GhostPipeDispatcher;
+ dispatcher = new GhostPipeDispatcher({
+ getGhost: (id) => (id === 'xd-atlassian' ? makeInstalledGhost(id) : null),
+ runtimeStateOf: () => 'running',
+ spawn: async () => ({ ok: true }),
+ sendToGhost: (ghostId: string, payload: GhostPipeToolCall) => {
+ void (async () => {
+ const outFile = (payload.args as Record<string, unknown>).out_file as string;
+ const w = await fsSlot.handleFsRequest(ghostId, {
+ op: 'write', root: 'workdir', callId: payload.callId, path: outFile, content: '{"via":"pipe"}',
+ });
+ dispatcher.handleToolResult(ghostId, w.ok
+ ? { callId: payload.callId, ok: true, result: { saved_to: outFile } }
+ : { callId: payload.callId, ok: false, errorCode: 'INTERNAL', message: w.message });
+ })();
+ return true;
+ },
+ timeoutMs: 5_000,
+ });
+ callGhostToolMock.mockImplementation((request: unknown) =>
+ dispatcher.callGhostTool(request as { ghostId: string; tool: string; args: Record<string, unknown> }),
+ );
+
+ const broker = new SchedulerScriptCapabilityBroker();
+ const ok = await broker.call(
+ { method: 'jira.search_jql', params: { jql: 'x', out_file: 'r/pipe.json' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: tmp }) },
+ );
+ expect(ok).toMatchObject({ saved_to: 'r/pipe.json' });
+ expect(await fs.promises.readFile(path.join(tmp, 'r', 'pipe.json'), 'utf8')).toBe('{"via":"pipe"}');
+ // 已交卷:真实 dispatcher 配对的 callId 同样立即失去写盘授权。
+ const usedCallId = registerCallMock.mock.calls[0][0] as string;
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: usedCallId, path: 'r/late.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ } finally {
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('传输层异常(callGhostTool reject)同样 finalize,旧 callId 立即失在途资格', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-reject-'));
+ try {
+ const { cardService } = wireRealChannel(tmp);
+ // 生产契约上 callGhostTool 永不 reject(pipeDispatcher 折叠),但 finally
+ // 必须对传输层炸裂同样成立——锁死防御语义。
+ callGhostToolMock.mockRejectedValueOnce(new Error('transport blew up'));
+ await expect(
+ new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']),
+ { schedule: schedule({ workingDir: tmp }) },
+ ),
+ ).rejects.toThrow('transport blew up');
+ const callId = registerCallMock.mock.calls[0][0] as string;
+ expect(finalizeCallMock).toHaveBeenCalledWith(callId);
+ expect(cardService.inFlightCallInfoOf(callId)).toBeNull();
+ } finally {
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('finalizeActiveCalls(runId):终结本 run 的在途写权,并发 run 不误伤(两个 review P1)', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-finalize-'));
+ const { cardService, fsSlot } = wireRealChannel(tmp);
+ // 两个不同 run 的调用都挂闸门保持在途。
+ const gates: Array<() => void> = [];
+ callGhostToolMock.mockImplementation(async () => {
+ await new Promise<void>((resolve) => gates.push(resolve));
+ return { ok: true, result: {} };
+ });
+ const broker = new SchedulerScriptCapabilityBroker();
+ const granted = new Set(['jira.read'] as const);
+ // 带 out_file 才挂写窗(第四轮收窄),本用例测的是 run 粒度收口。
+ const pA = broker
+ .call({ method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'a.json' } }, granted, { schedule: schedule({ workingDir: tmp }), runId: 'run-A' })
+ .catch((err: unknown) => err);
+ const pB = broker
+ .call({ method: 'jira.get', params: { issue_key: 'DING-2', out_file: 'b.json' } }, granted, { schedule: schedule({ workingDir: tmp }), runId: 'run-B' })
+ .catch((err: unknown) => err);
+ try {
+ const callIdA = registerCallMock.mock.calls[0][0] as string;
+ const callIdB = registerCallMock.mock.calls[1][0] as string;
+ // 两个 run 都在途:写盘都放行。
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: callIdA, path: 'a.json', content: 'x',
+ })).toMatchObject({ ok: true });
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: callIdB, path: 'b.json', content: 'x',
+ })).toMatchObject({ ok: true });
+ // run-A 终结(drain 30s 截止/abort):它的在途授权立即失效,不等
+ // pipeDispatcher 超时(上限 30min);并发的 run-B 不受影响(broker 单例、
+ // scheduler 并发上限 8,误清别家桶会把合法写盘拒成「已过期」)。
+ broker.finalizeActiveCalls('run-A');
+ expect(cardService.inFlightCallInfoOf(callIdA)).toBeNull();
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: callIdA, path: 'a-late.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: callIdB, path: 'b.json', content: 'x',
+ })).toMatchObject({ ok: true });
+ // run-B 终结后同样失效。
+ broker.finalizeActiveCalls('run-B');
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: callIdB, path: 'b-late.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ } finally {
+ // 调用之后正常交卷:finalize 幂等(dispatcher 配对账本独立),不炸。
+ for (const release of gates) release();
+ await Promise.all([pA, pB]);
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
+ it('并发调用:两个 callId 各自独立,一个 finalize 不误伤另一个的在途写权', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-conc-'));
+ try {
+ const { fsSlot } = wireRealChannel(tmp);
+ // 第一个调用挂闸门(保持在途),第二个立即完成并 finalize。
+ let releaseFirst!: () => void;
+ const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
+ callGhostToolMock
+ .mockImplementationOnce(async () => { await firstGate; return { ok: true, result: {} }; })
+ .mockImplementationOnce(async () => ({ ok: true, result: {} }));
+ const broker = new SchedulerScriptCapabilityBroker();
+ const granted = new Set(['jira.read'] as const);
+ // 带 out_file 才挂写窗(第四轮收窄),本用例测的是并发 callId 隔离。
+ const p1 = broker.call({ method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'a.json' } }, granted, { schedule: schedule({ workingDir: tmp }) });
+ const p2 = broker.call({ method: 'jira.get', params: { issue_key: 'DING-2', out_file: 'b.json' } }, granted, { schedule: schedule({ workingDir: tmp }) });
+ await p2;
+ const firstCallId = registerCallMock.mock.calls[0][0] as string;
+ const secondCallId = registerCallMock.mock.calls[1][0] as string;
+ // 第二个已交卷:写拒;第一个仍在途:写通——两本授权互不串。
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: secondCallId, path: 'second.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: firstCallId, path: 'a.json', content: 'x',
+ })).toMatchObject({ ok: true });
+ releaseFirst();
+ await p1;
+ // 第一个交卷后同样失效。
+ expect(await fsSlot.handleFsRequest('xd-atlassian', {
+ op: 'write', root: 'workdir', callId: firstCallId, path: 'first-late.json', content: 'x',
+ })).toMatchObject({ ok: false });
+ } finally {
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
});
// Compile-time fixture: legacy schedules may omit executionMode.
const _legacySchedule: Partial<Schedule> = { prompt: 'legacy' };
void _legacySchedule;
+
+/** 端到端用例的已装意识(fixture):声明 fs 槽(fs 槽资格审)+ jira_issues 工具
+ * (pipeDispatcher 资格审)。 */
+function makeInstalledGhost(id: string): InstalledGhost {
+ return {
+ manifest: {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['fs'],
+ tools: [{ name: 'jira_issues', description: 'jira' }],
+ } as InstalledGhost['manifest'],
+ dir: '/tmp/fake-install-dir',
+ enabled: true,
+ };
+}
+
+/**
+ * 端到端 harness:真实 GhostCardService + 真实 GhostFsSlot,把 broker 的
+ * mock 边界(register/finalize)接到真实账本——用例只需替换意识行为
+ * (callGhostToolMock 的实现),其余链路全真。
+ */
+function wireRealChannel(tmp: string): { cardService: GhostCardService; fsSlot: GhostFsSlot } {
+ const cardService = new GhostCardService({
+ hasCardSlot: () => false,
+ sanitize: (html: string) => ({ ok: true, html }),
+ persist: async () => {},
+ broadcast: () => {},
+ });
+ const fsSlot = new GhostFsSlot({
+ getGhost: (id) => (id === 'xd-atlassian' ? makeInstalledGhost(id) : null),
+ dataRootDir: () => path.join(tmp, 'ghost-fs'),
+ callInfo: (callId) => cardService.callInfoOf(callId),
+ inFlightCallInfo: (callId) => cardService.inFlightCallInfoOf(callId),
+ getSessionSnapshot: async () => null,
+ requestWriteConfirm: async () => ({ confirmed: false, reason: 'cancelled' as const }),
+ writeSaveDeposit: async () => null,
+ });
+ registerCallMock.mockImplementation((callId: string, info: never) =>
+ cardService.registerCall(callId, info),
+ );
+ finalizeCallMock.mockImplementation((callId: string) => cardService.finalizeCall(callId));
+ return { cardService, fsSlot };
+}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
index cd6bb50801..03fff69169 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
@@ -160,7 +160,7 @@ describe('ScriptScheduleRunner', () => {
expect(broker.call).toHaveBeenCalledWith(
{ method: 'jira.get', params: { issue_key: 'DING-1' } },
new Set(['jira.read']),
- { schedule: expect.objectContaining({ id: 'script-schedule' }) },
+ { schedule: expect.objectContaining({ id: 'script-schedule' }), runId: 'run-1' },
);
child.stdout.write(`${JSON.stringify({
protocol: 'xdt-maker-script/1',
@@ -428,6 +428,43 @@ describe('ScriptScheduleRunner', () => {
await expect(resultPromise).rejects.toThrow('session archived');
});
+ it('fire 终结的统一收口调用 broker.finalizeActiveCalls(残留写盘授权不跨 run 存活,review P1)', async () => {
+ const child = childProcess();
+ spawnMock.mockReturnValue(child);
+ const finalizeActiveCalls = vi.fn();
+ const broker = {
+ call: vi.fn(async () => ({ ok: true })),
+ finalizeActiveCalls,
+ };
+ const runner = new ScriptScheduleRunner({ broker, logger: {} });
+ const resultPromise = runner.fire(schedule(), {
+ runId: 'run-1',
+ firedAt: 1,
+ signal: new AbortController().signal,
+ });
+
+ child.stdout.write(`${JSON.stringify({
+ protocol: 'xdt-maker-script/1',
+ type: 'call',
+ id: 'py-1',
+ method: 'sessions.dispatch',
+ params: { message: 'hi' },
+ })}\n`);
+ await vi.waitFor(() => expect(broker.call).toHaveBeenCalledTimes(1));
+ child.stdout.write(`${JSON.stringify({
+ protocol: 'xdt-maker-script/1',
+ type: 'complete',
+ resultText: 'done',
+ })}\n`);
+ await vi.waitFor(() => expect(child.stdin.writable).toBe(false));
+ child.emit('close', 0);
+
+ await expect(resultPromise).resolves.toEqual({ sessionId: '', resultText: 'done' });
+ // 收口按 runId 调用:scheduler 并发跑多个 schedule 时只 finalize 本 run(review P1 第二轮)。
+ expect(finalizeActiveCalls).toHaveBeenCalledTimes(1);
+ expect(finalizeActiveCalls).toHaveBeenCalledWith('run-1');
+ });
+
it('does not hang past pause/delete when a call is still in flight after the child has already exited (codex review 第七轮)', async () => {
// 子进程已经 close(退出码 0),但 broker.call() 仍未 resolve——这之后若
// abort,不能让 fire() 永久挂起等一个已经失去意义的等待(此前 timer/abort
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunnerPythonProtocol.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunnerPythonProtocol.test.ts
index 03f703cb7d..593bb2c354 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunnerPythonProtocol.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunnerPythonProtocol.test.ts
@@ -189,4 +189,58 @@ describe.skipIf(!PYTHON)('script automation Python client', () => {
expect(stderrCapture).toContain('child noise');
expect(stderrCapture).toContain('stray after rpc');
}, 30_000);
+
+ it('jira wrappers forward body_adf / out_file unchanged, omit absent optional params', async () => {
+ // 跨语言验收:Python 封装构造的 params 原样进 broker 协议帧——body_adf 拼错
+ // 键名/漏传、可选参数缺省时误传,这里先红(broker 单测看不到 Python 侧)。
+ for (const file of ['protocol.py', 'maker_client.py']) {
+ cpSync(path.join(PYTHON_CLIENT_DIR, file), path.join(tmp, file));
+ }
+ writeFileSync(
+ path.join(tmp, 'adf_comment.py'),
+ [
+ 'import maker_client',
+ 'adf = {"type":"doc","version":1,"content":[{"type":"paragraph","content":[{"type":"mention","attrs":{"id":"acc-1"}}]}]}',
+ 'maker_client.jira_issue_add_comment("DING-2", body_adf=adf)',
+ 'maker_client.jira_issues_search_jql("project = DING", out_file="reports/jira.json")',
+ 'maker_client.jira_issue_get("DING-3", out_file="issue.json")',
+ 'maker_client.emit_complete("ok")',
+ '',
+ ].join('\n'),
+ 'utf8',
+ );
+ const seen: Array<{ method: string; params: Record<string, unknown> }> = [];
+ const broker: ScriptCapabilityBroker = {
+ async call(request) {
+ seen.push({ method: request.method, params: request.params });
+ return { ok: true };
+ },
+ };
+ const runner = new ScriptScheduleRunner({ broker, logger: {} });
+ const sched = schedule(`${PYTHON} adf_comment.py`);
+ sched.scriptConfig = {
+ command: `${PYTHON} adf_comment.py`,
+ capabilities: ['jira.read', 'jira.comment'],
+ timeoutMs: 30_000,
+ };
+ const ctx: FireContext = { runId: 'run-3', firedAt: Date.now(), signal: new AbortController().signal };
+ await runner.fire(sched, ctx);
+
+ // toEqual 精确锁键集合:body_adf 原样在、body_text 缺席;可选参数缺省时不出现在 params。
+ expect(seen).toEqual([
+ {
+ method: 'jira.add_comment',
+ params: {
+ issue_key: 'DING-2',
+ body_adf: {
+ type: 'doc',
+ version: 1,
+ content: [{ type: 'paragraph', content: [{ type: 'mention', attrs: { id: 'acc-1' } }] }],
+ },
+ },
+ },
+ { method: 'jira.search_jql', params: { jql: 'project = DING', out_file: 'reports/jira.json' } },
+ { method: 'jira.get', params: { issue_key: 'DING-3', out_file: 'issue.json' } },
+ ]);
+ }, 30_000);
});
diff --git a/apps/desktop/src/main/scheduler-host/python-client/README.md b/apps/desktop/src/main/scheduler-host/python-client/README.md
index e843e61ae9..7166c062e9 100644
--- a/apps/desktop/src/main/scheduler-host/python-client/README.md
+++ b/apps/desktop/src/main/scheduler-host/python-client/README.md
@@ -30,8 +30,8 @@ spawn 你的脚本;脚本通过 stdin/stdout 的 JSONL 协议(`cindy-script/1`)
| 能力 | 方法 | 说明 |
|---|---|---|
| (免授权) | `host_capabilities()` | 自省:返回本任务已授予的能力与完整方法目录,脚本先 list 再决定怎么 call |
-| `jira.read` | `jira_issue_get(key, fields?)` / `jira_issues_search_jql(jql, fields, max_results, next_page_token?)` | 读 Jira(走已连接的 Atlassian 账号;**需要 XD Atlassian 意识装入且唤醒**) |
-| `jira.comment` | `jira_issue_add_comment(key, body_text)` | 写 Jira 评论(同上) |
+| `jira.read` | `jira_issue_get(key, fields?, out_file?)` / `jira_issues_search_jql(jql, fields?, max_results?, next_page_token?, out_file?)` | 读 Jira(走已连接的 Atlassian 账号;**需要 XD Atlassian 意识装入且唤醒**);`out_file` = 大结果整包落盘到任务工作目录的相对路径,返回 `saved_to` 后从自己 cwd 读回 |
+| `jira.comment` | `jira_issue_add_comment(key, body_text=…, body_adf=…)` | 写 Jira 评论(同上);`body_text` 纯文本与 `body_adf`(ADF 文档对象,支持真实 @mention)恰好二选一 |
| `feishu.read` | `feishu_recent_chats(count≤50)` / `feishu_recent_messages(chat_id, count≤50, start_time?)` | 按活跃倒序列最近会话;拉指定会话最近消息(新→旧,含 sender_name,`start_time` 做增量游标)。走应用内飞书登录态,token 不下发脚本 |
| `sessions.dispatch` | `sessions_dispatch(message, title?, target_session_id?)` | 创建或唤醒 Cindy 会话并投递消息;新会话配置继承任务本身(agent/model/目录),脚本无法伪造 |
@@ -45,9 +45,12 @@ spawn 你的脚本;脚本通过 stdin/stdout 的 JSONL 协议(`cindy-script/1`)
- **错误码是结构化的**:`MakerClientError.code` 可能是 `CAPABILITY_DENIED`(没勾
能力)/ `METHOD_NOT_FOUND` / `INVALID_ARGS` / `HOST_NOT_READY` / `GHOST_ASLEEP`
(意识沉睡)/ `AUTH_EXPIRED`(登录态过期)等,按需分支处理。
-- **大结果集要分页**:宿主对单次响应有体积上限,`jira_issues_search_jql` 用
- `next_page_token` 翻页(参考 auto-jira-dispatch 的 `_search_all_issues`:
- 截断时减半页重试)。
+- **大结果集两条路**:宿主对单次响应有体积上限——`jira_issues_search_jql` 可以
+ 用 `next_page_token` 翻页(参考 auto-jira-dispatch 的 `_search_all_issues`:
+ 截断时减半页重试),也可以传 `out_file` 让意识把整包落盘到任务工作目录
+ (如 `out_file="reports/jira.json"`,返回 `saved_to` 相对路径,脚本从自己
+ cwd 读回);`jira_issue_get` 同样支持。落盘路径由宿主校验,必须是工作目录内
+ 的相对路径。
- 环境变量经过白名单过滤(PATH/HOME 等基础项保留,凭证类一律不透传);任务可配
整轮超时,超时杀整棵进程树。
diff --git a/apps/desktop/src/main/scheduler-host/python-client/maker_client.py b/apps/desktop/src/main/scheduler-host/python-client/maker_client.py
index 6ff2aec8eb..c457442154 100644
--- a/apps/desktop/src/main/scheduler-host/python-client/maker_client.py
+++ b/apps/desktop/src/main/scheduler-host/python-client/maker_client.py
@@ -44,24 +44,55 @@ def host_capabilities() -> dict:
return call_rpc("host.capabilities", {})
-def jira_issue_get(issue_key: str, fields: list[str] | None = None) -> dict:
+def jira_issue_get(
+ issue_key: str, fields: list[str] | None = None, out_file: str | None = None
+) -> dict:
+ """按 key 读单条 Jira issue。
+
+ out_file = 把整包结果落盘到任务工作目录下的相对路径(大结果防截断;
+ 路径安全校验由宿主把关),返回值带 saved_to 相对路径,脚本从自己 cwd 读回。"""
params: dict[str, Any] = {"issue_key": issue_key}
if fields:
params["fields"] = fields
+ if out_file is not None:
+ params["out_file"] = out_file
return call_rpc("jira.get", params)
def jira_issues_search_jql(
- jql: str, fields: list[str], max_results: int, next_page_token: str | None = None
+ jql: str,
+ fields: list[str] | None = None,
+ max_results: int | None = None,
+ next_page_token: str | None = None,
+ out_file: str | None = None,
) -> dict:
- params: dict[str, Any] = {"jql": jql, "fields": fields, "max_results": max_results}
+ """JQL 搜索。大结果集两条路:next_page_token 翻页,或 out_file 落盘
+ (任务工作目录内相对路径)后自己读回——宿主对单次响应有体积上限。"""
+ params: dict[str, Any] = {"jql": jql}
+ if fields:
+ params["fields"] = fields
+ if max_results is not None:
+ params["max_results"] = max_results
if next_page_token:
params["next_page_token"] = next_page_token
+ if out_file is not None:
+ params["out_file"] = out_file
return call_rpc("jira.search_jql", params)
-def jira_issue_add_comment(issue_key: str, body_text: str) -> dict:
- return call_rpc("jira.add_comment", {"issue_key": issue_key, "body_text": body_text})
+def jira_issue_add_comment(
+ issue_key: str,
+ body_text: str | None = None,
+ body_adf: dict | None = None,
+) -> dict:
+ """向 Jira issue 添加评论。body_text(纯文本)与 body_adf(ADF 文档对象,
+ 支持真实 @mention)恰好二选一;两个都传或都不传宿主会拒收(INVALID_ARGS)。"""
+ params: dict[str, Any] = {"issue_key": issue_key}
+ if body_text is not None:
+ params["body_text"] = body_text
+ if body_adf is not None:
+ params["body_adf"] = body_adf
+ return call_rpc("jira.add_comment", params)
def feishu_recent_chats(count: int = 20) -> dict:
diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
index 83495f85db..dfb8b39384 100644
--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
@@ -1,6 +1,11 @@
+import { randomUUID } from 'node:crypto';
+import { isAbsolute } from 'node:path';
+
import type { Schedule, ScriptCapability } from '@cindy/maker-scheduler';
-import { getGhostPipeDispatcher } from '../cindy-brain/index.js';
+import type { GhostToolCallResult } from '../../shared/ghost.js';
+import { getGhostCardService, getGhostPipeDispatcher } from '../cindy-brain/index.js';
+import { validateFsRelPath } from '../cindy-brain/fsSlot.js';
import { tryGetOrcaCollabService } from '../maker-ipc/register.js';
import type { ScriptCapabilityBroker, ScriptCapabilityCall } from './script-runner';
// model 兜底与 runner 同源(2026-06 曾因多份拷贝不同步导致 UI 显示与实跑模型不一致)
@@ -48,6 +53,75 @@ function rejectHostOwnedParams(params: Record<string, unknown>, keys: string[]):
}
}
+/**
+ * 脚本通道的意识调用包装(2026-08-04):自铸 callId 并向 cardService 登记
+ * scriptWorkdir(= schedule.workingDir)——意识在调用内经 fs 槽 root:'workdir'
+ * 泄洪落盘(如大结果 out_file)时,主机凭这个 callId 把写入钳在该目录内;
+ * 交卷后 finalize 记账,条目随宽限窗+懒清扫失效(在途有效、用完即废,与
+ * 会话通道同一本账)。不 finalize 的话条目永驻,callId 永久有效——绝不允许。
+ *
+ * active 登记簿(runId → 在途 callId):供 runner 在本轮 fire 终结(放弃等待
+ * 在途调用)时按 run finalize——否则 runner 的 30s drain 截止后,调用要等
+ * pipeDispatcher 超时(上限 GHOST_PIPE_CALL_MAX_TOTAL_MS = 30min)才交卷,
+ * 这段 gap 里旧 callId 仍有写权而下一轮 fire 可能已开始(review P1)。
+ * runId 缺省(非 runner 调用方)归入共享桶,保持原行为。
+ */
+async function callGhostForScript(
+ request: { ghostId: string; tool: string; args: Record<string, unknown> },
+ schedule: Pick<Schedule, 'workingDir'>,
+ runId: string,
+ active: Map<string, Set<string>>,
+ writePath: string | null,
+): Promise<GhostToolCallResult> {
+ const callId = randomUUID();
+ // 登记值与 script-runner 的 spawn cwd 严格同源(同一字符串,不 trim 改写):
+ // POSIX 允许首尾空白的目录名,trim 后登记会让授权根与脚本实际 cwd 分叉
+ // (review)。trim 只用于「全空白 = 未配置」判空;相对/畸形按 null 登记
+ // (fs 槽会以「脚本通道未配置有效的工作目录」拒写,查询本身不受影响)。
+ // writePath(= 脚本显式声明的 out_file)是唯一可写目标:只有显式带 out_file
+ // 的调用才挂写窗,且 fs 槽只放行恰好等于它的路径——调用在途期间插件也
+ // 写不了根内其它文件(经四轮 review 收敛的最小授权口径)。纯写方法
+ // (add_comment)与无 out_file 契约的 feishu 方法传 null:不挂写窗;读调用
+ // 不带 out_file 时若触发插件自动泄洪,只是回落 truncated,无回归。
+ const rawWorkdir = typeof schedule.workingDir === 'string' ? schedule.workingDir : '';
+ const scriptWorkdir = writePath !== null && rawWorkdir.trim() && isAbsolute(rawWorkdir) ? rawWorkdir : null;
+ const cardService = getGhostCardService();
+ cardService.registerCall(callId, {
+ ghostId: request.ghostId,
+ toolUseId: null,
+ sessionId: null,
+ scriptWorkdir,
+ scriptWritePath: scriptWorkdir === null ? null : writePath,
+ channel: 'script',
+ });
+ let bucket = active.get(runId);
+ if (!bucket) {
+ bucket = new Set();
+ active.set(runId, bucket);
+ }
+ bucket.add(callId);
+ try {
+ return await getGhostPipeDispatcher().callGhostTool({ ...request, callId });
+ } finally {
+ bucket.delete(callId);
+ if (bucket.size === 0) active.delete(runId);
+ cardService.finalizeCall(callId);
+ }
+}
+
+/**
+ * out_file 可选参数校验:脚本指定的大结果落盘相对路径(相对 schedule 工作
+ * 目录)。与 fs 槽同一口径(validateFsRelPath),拒绝原因原样回给脚本。
+ */
+function optionalOutFile(params: Record<string, unknown>): string | undefined {
+ const value = params.out_file;
+ if (value === undefined) return undefined;
+ if (typeof value !== 'string' || !value.trim()) fail('INVALID_ARGS', 'out_file must be a non-empty string');
+ const reason = validateFsRelPath(value);
+ if (reason) fail('INVALID_ARGS', `out_file ${reason}`);
+ return value;
+}
+
/**
* 飞书能力走 xd-feishu 意识 ghost pipe(2026-07-17 起,与 callJira 同套路):
* 主机飞书 token 链已随 refresh-feishu 退役,工具真身与凭证(OAuth broker)
@@ -55,23 +129,41 @@ function rejectHostOwnedParams(params: Record<string, unknown>, keys: string[]):
* saved_to / truncated 形态)——这里解开 data,保持脚本可见形状与老
* registry 直调一致;非 data 形态原样透传(自带 hint,脚本能看懂)。
*/
-async function callFeishu(name: string, args: Record<string, unknown>): Promise<unknown> {
- const result = await getGhostPipeDispatcher().callGhostTool({
- ghostId: 'xd-feishu',
- tool: 'call_tool',
- args: { name, args },
- });
+async function callFeishu(
+ name: string,
+ args: Record<string, unknown>,
+ schedule: Pick<Schedule, 'workingDir'>,
+ runId: string,
+ active: Map<string, Set<string>>,
+): Promise<unknown> {
+ const result = await callGhostForScript(
+ { ghostId: 'xd-feishu', tool: 'call_tool', args: { name, args } },
+ schedule,
+ runId,
+ active,
+ // feishu 方法没有 out_file 契约,不挂写窗(收窄口径见 callGhostForScript
+ // 头注释;插件若自动泄洪会回落 truncated,与未挂写窗前的行为一致)。
+ null,
+ );
if (!result.ok) fail(result.errorCode, result.message);
const payload = result.result as { data?: unknown } | null | undefined;
return payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
}
-async function callJira(args: Record<string, unknown>): Promise<unknown> {
- const result = await getGhostPipeDispatcher().callGhostTool({
- ghostId: 'xd-atlassian',
- tool: 'jira_issues',
- args,
- });
+async function callJira(
+ args: Record<string, unknown>,
+ schedule: Pick<Schedule, 'workingDir'>,
+ runId: string,
+ active: Map<string, Set<string>>,
+ writePath: string | null,
+): Promise<unknown> {
+ const result = await callGhostForScript(
+ { ghostId: 'xd-atlassian', tool: 'jira_issues', args },
+ schedule,
+ runId,
+ active,
+ writePath,
+ );
if (!result.ok) fail(result.errorCode, result.message);
return result.result;
}
@@ -87,9 +179,9 @@ const SCRIPT_METHOD_CATALOG: ReadonlyArray<{
description: string;
}> = [
{ method: 'host.capabilities', capability: null, params: '{}', description: '自省:返回协议版本、本任务已授予的能力、可用方法目录' },
- { method: 'jira.get', capability: 'jira.read', params: '{issue_key, fields?}', description: '按 key 读单条 Jira issue' },
- { method: 'jira.search_jql', capability: 'jira.read', params: '{jql, fields?, max_results?≤100, next_page_token?}', description: 'JQL 搜索(大结果集用 next_page_token 分页)' },
- { method: 'jira.add_comment', capability: 'jira.comment', params: '{issue_key, body_text}', description: '向 Jira issue 添加评论' },
+ { method: 'jira.get', capability: 'jira.read', params: '{issue_key, fields?, out_file?}', description: '按 key 读单条 Jira issue(out_file = 结果落盘到工作目录的相对路径)' },
+ { method: 'jira.search_jql', capability: 'jira.read', params: '{jql, fields?, max_results?≤100, next_page_token?, out_file?}', description: 'JQL 搜索(大结果集用 next_page_token 分页,或 out_file 落盘后自行读回)' },
+ { method: 'jira.add_comment', capability: 'jira.comment', params: '{issue_key, body_text | body_adf}', description: '向 Jira issue 添加评论;body_text 纯文本与 body_adf(ADF 文档对象,支持 @mention)恰好二选一' },
{ method: 'feishu.recent_chats', capability: 'feishu.read', params: '{count?≤50}', description: '按活跃时间倒序列最近飞书会话' },
{ method: 'feishu.recent_messages', capability: 'feishu.read', params: '{chat_id, count?≤50, start_time?}', description: '拉指定飞书会话最近消息(新→旧,start_time 增量)' },
{ method: 'sessions.dispatch', capability: 'sessions.dispatch', params: '{message, title?, target_session_id?}', description: '创建或唤醒 Cindy 会话并投递消息' },
@@ -100,6 +192,9 @@ const SCRIPT_METHOD_CATALOG: ReadonlyArray<{
* methods to current host APIs and rejects every method/action not listed here.
*/
export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
+ /** 在途脚本通道调用登记簿:runId → callId 集(runner 按 run 收口用)。 */
+ private readonly activeScriptCallIds = new Map<string, Set<string>>();
+
constructor(private readonly deps: {
resolveDefaultModelRoute?: (
agent: Schedule['agentKind'],
@@ -107,12 +202,32 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
) => Promise<{ model: string; providerId: string } | null>;
} = {}) {}
+ /**
+ * runner 判定本轮 fire 终结(drain 截止/abort/超时放弃等待在途调用)时调用:
+ * 让**本 run** 的残留脚本通道 callId 立即失去写盘授权,不等 pipeDispatcher
+ * 超时(上限 30min)——runId 维度隔离:broker 是单例而 scheduler 可并发跑
+ * 多个 schedule(DEFAULT_MAX_CONCURRENT_RUNS=8),误清并发 run 的在途 callId
+ * 会把别家插件的合法写盘拒成「已过期」(review P1 第二轮)。
+ * cardService.finalizeCall 幂等:被提前 finalize 的调用之后正常交卷不受影响
+ * (dispatcher 配对账本独立)。
+ */
+ finalizeActiveCalls(runId: string): void {
+ const bucket = this.activeScriptCallIds.get(runId);
+ if (!bucket || bucket.size === 0) return;
+ const cardService = getGhostCardService();
+ for (const callId of bucket) cardService.finalizeCall(callId);
+ this.activeScriptCallIds.delete(runId);
+ }
+
async call(
request: ScriptCapabilityCall,
granted: ReadonlySet<ScriptCapability>,
- context: { schedule: Schedule },
+ context: { schedule: Schedule; runId?: string },
): Promise<unknown> {
const params = request.params;
+ // runId 维度隔离:scheduler 并发跑多个 schedule 时,broker 单例的在途
+ // 登记簿按 run 分桶,finalizeActiveCalls 只收本 run(缺省进共享桶)。
+ const runId = context.runId ?? '';
switch (request.method) {
case 'host.capabilities':
// 元方法,免授权(纯自省、无副作用、不触达外部系统):脚本先 list 再决定怎么 call。
@@ -127,11 +242,13 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
case 'jira.get': {
requireCapability(granted, 'jira.read');
const fields = optionalStringArray(params, 'fields');
+ const outFile = optionalOutFile(params);
return callJira({
action: 'get',
issue_key: requireString(params, 'issue_key'),
...(fields ? { fields } : {}),
- });
+ ...(outFile ? { out_file: outFile } : {}),
+ }, context.schedule, runId, this.activeScriptCallIds, outFile ?? null);
}
case 'jira.search_jql': {
requireCapability(granted, 'jira.read');
@@ -147,22 +264,43 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
fail('INVALID_ARGS', 'next_page_token must be a non-empty string');
}
const fields = optionalStringArray(params, 'fields');
+ const outFile = optionalOutFile(params);
return callJira({
action: 'search_jql',
jql: requireString(params, 'jql'),
...(fields ? { fields } : {}),
...(maxResults === undefined ? {} : { max_results: maxResults }),
- // 大结果集意识侧会整包截断(deliver 50K chars),脚本靠分页拿全量。
+ // 大结果集意识侧会整包截断(deliver 50K chars),脚本靠分页拿全量;
+ // 或传 out_file 让意识把整包落盘到 schedule 工作目录,脚本自己读回。
...(nextPageToken === undefined ? {} : { next_page_token: nextPageToken }),
- });
+ ...(outFile ? { out_file: outFile } : {}),
+ }, context.schedule, runId, this.activeScriptCallIds, outFile ?? null);
}
- case 'jira.add_comment':
+ case 'jira.add_comment': {
requireCapability(granted, 'jira.comment');
+ const issueKey = requireString(params, 'issue_key');
+ // body_text / body_adf 恰好二选一。body_adf 校验「非 null、非数组的
+ // object」:经 JSONL 协议到达的 object 必为 plain object(JSON.parse
+ // 产物,Date/Map/class 实例穿不过协议边界),无需更严;文档结构由
+ // Jira 侧把关(下游 xd-atlassian add_comment 本就支持 body_adf)。
+ const hasBodyText = params.body_text !== undefined;
+ const hasBodyAdf = params.body_adf !== undefined;
+ if (hasBodyText === hasBodyAdf) {
+ fail('INVALID_ARGS', 'provide exactly one of body_text or body_adf (both or neither given)');
+ }
+ if (hasBodyAdf) {
+ const bodyAdf = params.body_adf;
+ if (typeof bodyAdf !== 'object' || bodyAdf === null || Array.isArray(bodyAdf)) {
+ fail('INVALID_ARGS', 'body_adf must be an ADF document object');
+ }
+ return callJira({ action: 'add_comment', issue_key: issueKey, body_adf: bodyAdf }, context.schedule, runId, this.activeScriptCallIds, null);
+ }
return callJira({
action: 'add_comment',
- issue_key: requireString(params, 'issue_key'),
+ issue_key: issueKey,
body_text: requireString(params, 'body_text'),
- });
+ }, context.schedule, runId, this.activeScriptCallIds, null);
+ }
case 'feishu.recent_chats': {
// 按活跃时间倒序列最近会话(群/单聊)。配合 feishu.recent_messages 的
// start_time 可拼出"扫最近发给我的任意新消息"的 bot 入口轮询:
@@ -178,7 +316,7 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
return callFeishu('im_list_chats', {
sort_type: 'ByActiveTimeDesc',
page_size: chatCount ?? 20,
- });
+ }, context.schedule, runId, this.activeScriptCallIds);
}
case 'feishu.recent_messages': {
// 拉某个飞书会话(群/单聊)最近 N 条消息,新→旧;实现走 xd-feishu 意识
@@ -200,7 +338,7 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
...(count === undefined ? {} : { page_size: count }),
// 增量扫描游标:只取该时刻之后的消息(配本地已处理游标去重)
...(startTime === undefined ? {} : { start_time: String(startTime) }),
- });
+ }, context.schedule, runId, this.activeScriptCallIds);
}
case 'sessions.dispatch': {
requireCapability(granted, 'sessions.dispatch');
diff --git a/apps/desktop/src/main/scheduler-host/script-runner.ts b/apps/desktop/src/main/scheduler-host/script-runner.ts
index e6f884bf38..a975d4e1d0 100644
--- a/apps/desktop/src/main/scheduler-host/script-runner.ts
+++ b/apps/desktop/src/main/scheduler-host/script-runner.ts
@@ -86,8 +86,15 @@ export interface ScriptCapabilityBroker {
call(
request: ScriptCapabilityCall,
granted: ReadonlySet<ScriptCapability>,
- context: { schedule: Schedule },
+ context: { schedule: Schedule; runId?: string },
): Promise<unknown>;
+ /**
+ * 本轮 fire 终结(成功/失败/放弃等待在途调用)的统一收口:让残留的脚本
+ * 通道意识调用 callId 立即失效(写盘授权不跨 run 存活;review P1)。可选——
+ * 不带意识调用的 broker 实现无需提供。runId 维度隔离:scheduler 并发上限
+ * 8、broker 单例,只能 finalize 本 run 的在途调用,不得误伤并发 run。
+ */
+ finalizeActiveCalls?(runId: string): void;
}
export interface ScriptScheduleRunnerDeps {
@@ -342,7 +349,7 @@ export class ScriptScheduleRunner {
const result = await this.deps.broker.call(
{ method: frame.method, params: frame.params ?? {} },
granted,
- { schedule },
+ { schedule, runId: ctx.runId },
);
// capabilities 的 protocol 字段也应反映本轮协商结果。否则旧客户端虽然
// 能收发旧帧,却会在自省 payload 里突然看到新协议名,严格校验的脚本仍
@@ -609,6 +616,11 @@ export class ScriptScheduleRunner {
if (timer) clearTimeout(timer);
ctx.signal.removeEventListener('abort', onAbort);
cutoffReject = null;
+ // 本轮 fire 终结(无论成败):放弃等待的在途调用不能再留着写盘授权——
+ // 否则旧 callId 要等 pipeDispatcher 超时(上限 30min)才失效,而下一轮
+ // fire 可能已开始(review P1)。按 runId 收口:scheduler 可并发跑多个
+ // schedule,只 finalize 本 run 的在途调用,不误伤并发 run(第二个 P1)。
+ this.deps.broker.finalizeActiveCalls?.(ctx.runId);
}
// deferredCallFailure 只在闭包(handleCall)内被赋值,TS 的控制流分析看不到
// 那次赋值、一直把这里narrow 回声明时的 null——显式断言绕开,不是真的绕过