pi-ate-workflow 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/subagent.ts CHANGED
@@ -1,132 +1,140 @@
1
- /**
2
- * workflow: 子代理执行器公开 API
3
- *
4
- * spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
5
- * 超时在 timeout-config.ts 单点解析(fallback < timeoutMs < agentTimeouts < 显式传参)。
6
- * 桥接在 intercom-bridge.ts 默认注入(PI_SUBAGENT_* 5 变量)。
7
- */
8
-
9
- import * as fs from "node:fs";
10
- import * as path from "node:path";
11
- import type { SubagentResult, SubagentEvent } from "./types";
12
- import {
13
- createVisibleTaskDir,
14
- findAndInjectParentSession,
15
- writeTempPrompt,
16
- } from "./subagent-utils";
17
- import { loadAgentDef } from "@pi-atelier/shared-utils";
18
- import { spawnOnce } from "./subagent-spawn-once";
19
- import { spawnVisible } from "./subagent-spawn-visible";
20
- import { resolveSubagentTimeout } from "./timeout-config";
21
- import {
22
- buildIntercomBridge,
23
- resolveOrchestratorName,
24
- } from "./intercom-bridge";
25
-
26
- /** 模块级 session 文件解析器,由各扩展在 session_start 时注册 */
27
- let _sessionFileResolver: (() => string | undefined) | undefined;
28
-
29
- /** 各扩展在 session_start hook 中调用,注册当前会话文件路径的获取方式 */
30
- export function setSessionFileResolver(resolver: (() => string | undefined) | undefined) {
31
- _sessionFileResolver = resolver;
32
- }
33
-
34
- /** 格式约束,拼入 task 让子代理自检,执行后验证 */
35
- export interface OutputConstraint {
36
- /** 约束描述(自然语言,拼入 task) */
37
- rule: string;
38
- /** 验证函数:返回 null 表示通过,否则返回错误描述 */
39
- validate: (output: string) => string | null;
40
- }
41
-
42
- /** 构建格式约束追加提示词 */
43
- function buildConstraintAppendix(constraints: OutputConstraint[]): string {
44
- const rules = constraints.map((c, i) => `${i + 1}. ${c.rule}`).join("\n");
45
- return `\n\n---\n\n## 输出格式约束(严格遵守)\n\n你的输出会被自动化系统解析,必须严格遵守以下格式规则:\n\n${rules}\n\n**在输出审查结果之前,先检查你的输出是否符合上述所有规则。如果不符合,修正后再输出。**`;
46
- }
47
-
48
- /** 验证输出是否满足所有约束,返回不通过的列表 */
49
- export function validateOutputConstraints(output: string, constraints: OutputConstraint[]): string[] {
50
- const violations: string[] = [];
51
- for (const c of constraints) {
52
- const err = c.validate(output);
53
- if (err) violations.push(err);
54
- }
55
- return violations;
56
- }
57
-
58
- /**
59
- * 运行子代理(唯一 spawn 路径)。
60
- *
61
- * 超时:timeoutMs 参数为显式传参(最高优先级);未传时由配置链解析
62
- * (代码 fallback 30min < subagent.timeoutMs < subagent.agentTimeouts[agentName])。
63
- * 桥接:默认注入 PI_SUBAGENT_* 桥接环境变量(extraEnv 传入的变量优先保留)。
64
- *
65
- * @param agentName 对应 ~/.pi/agent/agents/{name}.md
66
- * @param visible true=在 tmux/WezTerm 窗格中可见运行(默认),false=后台运行
67
- */
68
- export async function runSubagent(
69
- agentName: string,
70
- task: string,
71
- cwd: string,
72
- signal?: AbortSignal,
73
- modelOverride?: string,
74
- timeoutMs?: number,
75
- onEvent?: (event: SubagentEvent) => void,
76
- outputConstraints?: OutputConstraint[],
77
- visible: boolean = true,
78
- extraEnv?: Record<string, string>,
79
- ): Promise<SubagentResult> {
80
- const agentDef = loadAgentDef(agentName, cwd);
81
- if (!agentDef) {
82
- throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ${agentName}.md 在 ~/.pi/agent/agents/、~/.agents/agents/ 或项目级 .pi/agents/ 中存在。`);
83
- }
84
-
85
- // 超时单点解析:显式传参 > agentTimeouts > timeoutMs > fallback
86
- const effectiveTimeout = resolveSubagentTimeout(agentName, cwd, timeoutMs);
87
-
88
- // 自动解析当前会话文件路径,用于建立 parentSession 关联
89
- const parentSessionPath = _sessionFileResolver?.();
90
-
91
- // 桥接环境变量:默认注入,调用方 extraEnv 优先
92
- const orchestratorName = await resolveOrchestratorName();
93
- const bridgeEnv = buildIntercomBridge(orchestratorName, agentName);
94
- const env = { ...bridgeEnv, ...extraEnv };
95
-
96
- const useVisible = visible && !!(process.env.TMUX || process.env.WEZTERM_PANE);
97
-
98
- const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
99
-
100
- try {
101
- const constraintAppendix = outputConstraints?.length ? buildConstraintAppendix(outputConstraints) : "";
102
- const fullTask = task + constraintAppendix;
103
-
104
- const MAX_RETRIES = 2;
105
- let lastResult: SubagentResult | undefined;
106
-
107
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
108
- const taskForAttempt = attempt === 0 ? fullTask
109
- : `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
110
-
111
- const result = useVisible
112
- ? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env)
113
- : await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env);
114
- lastResult = result;
115
-
116
- // 后台模式:子进程退出后通过 sessionId 查找 session 文件并注入 parentSession
117
- if (!useVisible && parentSessionPath && result.subSessionId) {
118
- findAndInjectParentSession(result.subSessionId, parentSessionPath, cwd);
119
- }
120
-
121
- if (!outputConstraints?.length) break;
122
- if (result.exitCode !== 0 && result.output.length <= 100) break;
123
-
124
- const violations = validateOutputConstraints(result.output, outputConstraints);
125
- if (violations.length === 0) break;
126
- }
127
-
128
- return lastResult!;
129
- } finally {
130
- try { const dir = path.dirname(tmpPromptPath); fs.unlinkSync(tmpPromptPath); fs.rmdirSync(dir); } catch { /* ignore */ }
131
- }
132
- }
1
+ /**
2
+ * workflow: 子代理执行器公开 API
3
+ *
4
+ * spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
5
+ * 超时在 timeout-config.ts 单点解析(fallback < timeoutMs < agentTimeouts < 显式传参)。
6
+ * 桥接在 intercom-bridge.ts 默认注入(PI_SUBAGENT_* 5 变量)。
7
+ */
8
+
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import type { SubagentResult, SubagentEvent } from "./types";
12
+ import {
13
+ createVisibleTaskDir,
14
+ findAndInjectParentSession,
15
+ writeTempPrompt,
16
+ } from "./subagent-utils";
17
+ import { loadAgentDef } from "@pi-atelier/shared-utils";
18
+ import { spawnOnce } from "./subagent-spawn-once";
19
+ import { spawnVisible } from "./subagent-spawn-visible";
20
+ import { resolveSubagentTimeout } from "./timeout-config";
21
+ import {
22
+ buildIntercomBridge,
23
+ resolveOrchestratorName,
24
+ } from "./intercom-bridge";
25
+ import { isSystemicSubagentFailure, buildSystemicFailureResult } from "./utils";
26
+
27
+ /** 模块级 session 文件解析器,由各扩展在 session_start 时注册 */
28
+ let _sessionFileResolver: (() => string | undefined) | undefined;
29
+
30
+ /** 各扩展在 session_start hook 中调用,注册当前会话文件路径的获取方式 */
31
+ export function setSessionFileResolver(resolver: (() => string | undefined) | undefined) {
32
+ _sessionFileResolver = resolver;
33
+ }
34
+
35
+ /** 格式约束,拼入 task 让子代理自检,执行后验证 */
36
+ export interface OutputConstraint {
37
+ /** 约束描述(自然语言,拼入 task) */
38
+ rule: string;
39
+ /** 验证函数:返回 null 表示通过,否则返回错误描述 */
40
+ validate: (output: string) => string | null;
41
+ }
42
+
43
+ /** 构建格式约束追加提示词 */
44
+ function buildConstraintAppendix(constraints: OutputConstraint[]): string {
45
+ const rules = constraints.map((c, i) => `${i + 1}. ${c.rule}`).join("\n");
46
+ return `\n\n---\n\n## 输出格式约束(严格遵守)\n\n你的输出会被自动化系统解析,必须严格遵守以下格式规则:\n\n${rules}\n\n**在输出审查结果之前,先检查你的输出是否符合上述所有规则。如果不符合,修正后再输出。**`;
47
+ }
48
+
49
+ /** 验证输出是否满足所有约束,返回不通过的列表 */
50
+ export function validateOutputConstraints(output: string, constraints: OutputConstraint[]): string[] {
51
+ const violations: string[] = [];
52
+ for (const c of constraints) {
53
+ const err = c.validate(output);
54
+ if (err) violations.push(err);
55
+ }
56
+ return violations;
57
+ }
58
+
59
+ /**
60
+ * 运行子代理(唯一 spawn 路径)。
61
+ *
62
+ * 超时:timeoutMs 参数为显式传参(最高优先级);未传时由配置链解析
63
+ * (代码 fallback 30min < subagent.timeoutMs < subagent.agentTimeouts[agentName])。
64
+ * 桥接:默认注入 PI_SUBAGENT_* 桥接环境变量(extraEnv 传入的变量优先保留)。
65
+ *
66
+ * @param agentName 对应 ~/.pi/agent/agents/{name}.md
67
+ * @param visible true=在 tmux/WezTerm 窗格中可见运行(默认),false=后台运行
68
+ */
69
+ export async function runSubagent(
70
+ agentName: string,
71
+ task: string,
72
+ cwd: string,
73
+ signal?: AbortSignal,
74
+ modelOverride?: string,
75
+ timeoutMs?: number,
76
+ onEvent?: (event: SubagentEvent) => void,
77
+ outputConstraints?: OutputConstraint[],
78
+ visible: boolean = true,
79
+ extraEnv?: Record<string, string>,
80
+ ): Promise<SubagentResult> {
81
+ const agentDef = loadAgentDef(agentName, cwd);
82
+ if (!agentDef) {
83
+ throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ${agentName}.md 在 ~/.pi/agent/agents/、~/.agents/agents/ 或项目级 .pi/agents/ 中存在。`);
84
+ }
85
+
86
+ // 超时单点解析:显式传参 > agentTimeouts > timeoutMs > fallback
87
+ const effectiveTimeout = resolveSubagentTimeout(agentName, cwd, timeoutMs);
88
+
89
+ // 自动解析当前会话文件路径,用于建立 parentSession 关联
90
+ const parentSessionPath = _sessionFileResolver?.();
91
+
92
+ // 桥接环境变量:默认注入,调用方 extraEnv 优先
93
+ const orchestratorName = await resolveOrchestratorName();
94
+ const bridgeEnv = buildIntercomBridge(orchestratorName, agentName);
95
+ const env = { ...bridgeEnv, ...extraEnv };
96
+
97
+ const useVisible = visible && !!(process.env.TMUX || process.env.WEZTERM_PANE);
98
+
99
+ const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
100
+
101
+ try {
102
+ const constraintAppendix = outputConstraints?.length ? buildConstraintAppendix(outputConstraints) : "";
103
+ const fullTask = task + constraintAppendix;
104
+
105
+ const MAX_RETRIES = 2;
106
+ let lastResult: SubagentResult | undefined;
107
+
108
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
109
+ const taskForAttempt = attempt === 0 ? fullTask
110
+ : `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
111
+
112
+ const result = useVisible
113
+ ? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env)
114
+ : await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env);
115
+ lastResult = result;
116
+
117
+ // 后台模式:子进程退出后通过 sessionId 查找 session 文件并注入 parentSession
118
+ if (!useVisible && parentSessionPath && result.subSessionId) {
119
+ findAndInjectParentSession(result.subSessionId, parentSessionPath, cwd);
120
+ }
121
+
122
+ // 系统性失败(error 字段 / timedOut / 空占位输出兼 stderr 非空,含 visible jsonl 终结形态信号):
123
+ // spawn 层阵亡,重试无效——组装失败档(error 必填 + stderr 尾部透出)直接返回,不消耗重试次数
124
+ if (isSystemicSubagentFailure(result)) {
125
+ lastResult = buildSystemicFailureResult(result);
126
+ break;
127
+ }
128
+
129
+ if (!outputConstraints?.length) break;
130
+ if (result.exitCode !== 0 && result.output.length <= 100) break;
131
+
132
+ const violations = validateOutputConstraints(result.output, outputConstraints);
133
+ if (violations.length === 0) break;
134
+ }
135
+
136
+ return lastResult!;
137
+ } finally {
138
+ try { const dir = path.dirname(tmpPromptPath); fs.unlinkSync(tmpPromptPath); fs.rmdirSync(dir); } catch { /* ignore */ }
139
+ }
140
+ }
@@ -93,6 +93,11 @@ describe("isPidAlive(win32 分支)", () => {
93
93
  const ex = makeExecutor("INFO: No tasks are running which match the specified criteria.");
94
94
  expect(isPidAlive(1234, ex)).toBe(false);
95
95
  });
96
+ // W4 修复防护:列解析防内存列数字子串误判(旧 includes 会匹配 "22,222" 里的 "222")
97
+ it("pid 仅出现在内存列(非第二列)不误判存活", () => {
98
+ const ex = makeExecutor("bar.exe 990 Console 1 22,222 K");
99
+ expect(isPidAlive(222, ex)).toBe(false);
100
+ });
96
101
  it("探测命令失败(null)fail-safe 判活", () => {
97
102
  const ex = makeExecutor(null);
98
103
  expect(isPidAlive(1234, ex)).toBe(true);
@@ -66,8 +66,13 @@ describe("spawnOnce — extraEnv 透传", () => {
66
66
  await resultPromise;
67
67
 
68
68
  const spawnOpts = spawnCalls[0][2];
69
+ // 语义修正(2026-11-24):spawn env = process.env ∪ extraEnv,同名键以 extraEnv 为准。
70
+ // 旧断言 objectContaining(process.env) 在键重叠时自相矛盾(子代理环境跑测试必红)。
71
+ const nonOverlapEnv = Object.fromEntries(
72
+ Object.entries(process.env).filter(([k]) => !(k in extraEnv)),
73
+ );
69
74
  expect(spawnOpts.env).toEqual(expect.objectContaining(extraEnv));
70
- expect(spawnOpts.env).toEqual(expect.objectContaining(process.env));
75
+ expect(spawnOpts.env).toEqual(expect.objectContaining(nonOverlapEnv));
71
76
  });
72
77
 
73
78
  it("extraEnv 的值覆盖 process.env 中同名 key", async () => {
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 测试 F1 失败档修复(opsx-subarch-meta-baseline,spec: subagent-spawn-runtime)
3
+ *
4
+ * 本文件覆盖纯函数层:
5
+ * 1. 占位文本字面量锁死(防文本漂移静默破坏分类)
6
+ * 2. isSystemicSubagentFailure 三级信号优先级
7
+ * 3. isSubagentSuccess 端到端锁死(系统性失败结果 === false)
8
+ * 4. buildSystemicFailureResult 组装契约(error 必填/exitCode 原值/stderr 尾部透出)
9
+ * 5. barrel 断言(新导出同步 index.ts)
10
+ *
11
+ * runSubagent spec 五 scenario 在 subagent-failure-retry.test.ts;
12
+ * visible 模式 jsonl 三形态用例在 subagent-spawn-visible.test.ts。
13
+ */
14
+ import { describe, it, expect } from "vitest";
15
+
16
+ import {
17
+ EMPTY_OUTPUT_PLACEHOLDERS,
18
+ STDERR_TAIL_LIMIT,
19
+ isEmptyPlaceholderOutput,
20
+ isSystemicSubagentFailure,
21
+ buildSystemicFailureResult,
22
+ isSubagentSuccess,
23
+ } from "../utils";
24
+
25
+ describe("F1 字面量锁死", () => {
26
+ it("EMPTY_OUTPUT_PLACEHOLDERS 逐字锁定(含 spawn 分支兜底文本)", () => {
27
+ expect(EMPTY_OUTPUT_PLACEHOLDERS).toEqual([
28
+ "(no output)",
29
+ "(stalled, no output for 5 min)",
30
+ "(timed out)",
31
+ ]);
32
+ });
33
+
34
+ it("isEmptyPlaceholderOutput:空串/空白/占位前缀或包含均命中,实质输出不命中", () => {
35
+ expect(isEmptyPlaceholderOutput("")).toBe(true);
36
+ expect(isEmptyPlaceholderOutput(" \n ")).toBe(true);
37
+ expect(isEmptyPlaceholderOutput("(no output)")).toBe(true);
38
+ // formatOutput 包装后的前缀形态(如折行后仍在场)
39
+ expect(isEmptyPlaceholderOutput("(no output)\n")).toBe(true);
40
+ expect(isEmptyPlaceholderOutput("prefix junk (timed out) suffix")).toBe(true);
41
+ expect(isEmptyPlaceholderOutput("(stalled, no output for 5 min)")).toBe(true);
42
+ expect(isEmptyPlaceholderOutput("这是实质输出,虽然很短")).toBe(false);
43
+ });
44
+ });
45
+
46
+ describe("isSystemicSubagentFailure:三级信号优先级", () => {
47
+ it("① error 字段存在 → 系统性失败(含 visible jsonl 信号源形态)", () => {
48
+ expect(isSystemicSubagentFailure({ output: "anything", error: "spawn ENOENT" })).toBe(true);
49
+ expect(
50
+ isSystemicSubagentFailure({
51
+ output: "(no output)",
52
+ error: "visible 模式信号源=jsonl 终结形态:session.jsonl 缺失(子进程未建立会话)",
53
+ }),
54
+ ).toBe(true);
55
+ });
56
+
57
+ it("① 空串 error 视为无 error(不命中)", () => {
58
+ expect(isSystemicSubagentFailure({ output: "ok", error: "" })).toBe(false);
59
+ });
60
+
61
+ it("② timedOut 布尔 → 系统性失败", () => {
62
+ expect(isSystemicSubagentFailure({ output: "ok", timedOut: true })).toBe(true);
63
+ expect(isSystemicSubagentFailure({ output: "ok", timedOut: false })).toBe(false);
64
+ });
65
+
66
+ it("③ 空占位输出兼 stderr 非空 → 系统性失败(R4 实证形态:exit 0 静默退出)", () => {
67
+ expect(
68
+ isSystemicSubagentFailure({ output: "(no output)", stderr: "Error: Cannot find module './judge'" }),
69
+ ).toBe(true);
70
+ });
71
+
72
+ it("③ 空占位但 stderr 空 → 不命中(正常完成零输出档,回落现状)", () => {
73
+ expect(isSystemicSubagentFailure({ output: "(no output)", stderr: "" })).toBe(false);
74
+ expect(isSystemicSubagentFailure({ output: "(no output)" })).toBe(false);
75
+ });
76
+
77
+ it("③ 有实质输出时 stderr 噪声不参与判定(不误伤)", () => {
78
+ expect(isSystemicSubagentFailure({ output: "x".repeat(200), stderr: "some non-fatal warning" })).toBe(false);
79
+ });
80
+ });
81
+
82
+ describe("isSubagentSuccess 端到端锁死", () => {
83
+ it("系统性失败结果(buildSystemicFailureResult 组装后)=== false", () => {
84
+ const result = buildSystemicFailureResult({
85
+ exitCode: 0,
86
+ output: "(no output)",
87
+ stderr: "Error: Cannot find module './judge'",
88
+ });
89
+ expect(isSubagentSuccess(result)).toBe(false);
90
+ });
91
+
92
+ it("原始系统性失败形态(exit 0 + 空占位 + stderr 非空)=== false —— 修复前此处为 true", () => {
93
+ expect(
94
+ isSubagentSuccess({ exitCode: 0, output: "(no output)", stderr: "Error: Cannot find module './judge'" }),
95
+ ).toBe(false);
96
+ });
97
+
98
+ it("有实质输出 + stderr 噪声 → 成功(现状不变)", () => {
99
+ expect(isSubagentSuccess({ exitCode: 0, output: "x".repeat(200), stderr: "warn noise" })).toBe(true);
100
+ });
101
+
102
+ it("正常完成零输出 + stderr 空 → 维持既有判定(现状语义:exit 0 即成功)", () => {
103
+ expect(isSubagentSuccess({ exitCode: 0, output: "(no output)", stderr: "" })).toBe(true);
104
+ });
105
+ });
106
+
107
+ describe("buildSystemicFailureResult 组装契约", () => {
108
+ it("error 必填 + output 含报错与 stderr 尾部 + exitCode 保持原值 0", () => {
109
+ const result = buildSystemicFailureResult({
110
+ exitCode: 0,
111
+ output: "(no output)",
112
+ stderr: "line1: extension load failed\nline2: Cannot find module './judge'",
113
+ });
114
+ expect(result.exitCode).toBe(0);
115
+ expect(result.error).toBeTruthy();
116
+ expect(result.output).toContain("[子代理系统性失败]");
117
+ expect(result.output).toContain("stderr 尾部");
118
+ expect(result.output).toContain("Cannot find module './judge'");
119
+ });
120
+
121
+ it("stderr 超长截尾(保留尾部)", () => {
122
+ const stderr = `${"a".repeat(STDERR_TAIL_LIMIT + 500)}TAIL_MARKER`;
123
+ const result = buildSystemicFailureResult({ exitCode: 1, output: "(no output)", stderr });
124
+ expect(result.output).toContain("TAIL_MARKER");
125
+ expect(result.stderr.length).toBe(stderr.length); // stderr 原文不动(不剥离)
126
+ expect(result.output.length).toBeLessThan(stderr.length); // output 中只透出尾部
127
+ });
128
+
129
+ it("visible jsonl 信号源的 error 注入后透传进报错行", () => {
130
+ const result = buildSystemicFailureResult({
131
+ exitCode: 0,
132
+ output: "(no output)",
133
+ stderr: "",
134
+ error: "visible 模式信号源=jsonl 终结形态:session.jsonl 无 message 事件(未进入对话阶段)",
135
+ });
136
+ expect(result.output).toContain("visible 模式信号源=jsonl 终结形态");
137
+ expect(result.error).toContain("visible 模式信号源=jsonl 终结形态");
138
+ });
139
+
140
+ it("timedOut 形态:error 标注 timed out", () => {
141
+ const result = buildSystemicFailureResult({ exitCode: 1, output: "(timed out)", stderr: "", timedOut: true });
142
+ expect(result.output).toContain("[子代理系统性失败] timed out");
143
+ expect(result.error).toBeTruthy();
144
+ });
145
+ });
146
+
147
+ // ─── barrel 断言(新导出同步 index.ts)───────────────────────────────────
148
+
149
+ describe("barrel 导出断言", () => {
150
+ it("index.ts 显式导出 F1 失败分类 API", async () => {
151
+ const api = await import("../index");
152
+ expect(typeof api.isSystemicSubagentFailure).toBe("function");
153
+ expect(typeof api.buildSystemicFailureResult).toBe("function");
154
+ expect(typeof api.isEmptyPlaceholderOutput).toBe("function");
155
+ expect(Array.isArray(api.EMPTY_OUTPUT_PLACEHOLDERS)).toBe(true);
156
+ expect(typeof api.checkSessionJsonlTermination).toBe("function");
157
+ });
158
+ });
@@ -0,0 +1,148 @@
1
+ /**
2
+ * 测试 F1 失败档修复的 runSubagent 层(opsx-subarch-meta-baseline,spec: subagent-spawn-runtime)
3
+ *
4
+ * spec 五 scenario(mock spawnOnce/spawnVisible):
5
+ * 1. 系统性失败不重试且透出 stderr(exit 0 + 占位 + stderr 非空)
6
+ * 2. 个体违约保留重试(违约 + stderr 空)
7
+ * 3. 正常完成零输出不误伤(3a 无 constraints 原样返回 / 3b 有 constraints 走违约重试档)
8
+ * 4. 有实质输出时 stderr 不影响成功判定
9
+ * 5.(库侧)visible jsonl 信号源 error 注入后走系统性失败档
10
+ *
11
+ * 纯函数层在 subagent-failure-classification.test.ts;
12
+ * visible 模式 jsonl 三形态用例在 subagent-spawn-visible.test.ts。
13
+ */
14
+ import { describe, it, expect, vi, beforeEach } from "vitest";
15
+
16
+ vi.mock("@pi-atelier/shared-utils", () => ({
17
+ loadAgentDef: vi.fn(),
18
+ getEffectiveConfig: vi.fn(() => ({ config: {}, sources: {} })),
19
+ }));
20
+ vi.mock("../timeout-config", () => ({
21
+ resolveSubagentTimeout: vi.fn(() => 30 * 60 * 1000),
22
+ DEFAULT_SUBAGENT_TIMEOUT_MS: 30 * 60 * 1000,
23
+ SUBAGENT_TIMEOUT_DEFAULTS: { timeoutMs: 1800000, agentTimeouts: {} },
24
+ }));
25
+ vi.mock("../intercom-bridge", () => ({
26
+ buildIntercomBridge: vi.fn(() => ({ PI_SUBAGENT_RUN_ID: "run-test" })),
27
+ resolveOrchestratorName: vi.fn(async () => undefined),
28
+ setOrchestratorNameResolver: vi.fn(),
29
+ }));
30
+ vi.mock("../subagent-utils", () => ({
31
+ writeTempPrompt: vi.fn().mockResolvedValue("/tmp/pi-pv-xxx/system-prompt.md"),
32
+ getPiCommand: vi.fn(),
33
+ }));
34
+ vi.mock("../subagent-spawn-once", () => ({ spawnOnce: vi.fn() }));
35
+ vi.mock("../subagent-spawn-visible", () => ({ spawnVisible: vi.fn() }));
36
+
37
+ import { loadAgentDef } from "@pi-atelier/shared-utils";
38
+ import { spawnOnce } from "../subagent-spawn-once";
39
+ import { spawnVisible } from "../subagent-spawn-visible";
40
+ import { runSubagent } from "../subagent";
41
+
42
+ const GOOD_CONSTRAINT = [{
43
+ rule: "必须包含 GOOD",
44
+ validate: (s: string) => (s.includes("GOOD") ? null : "缺少 GOOD"),
45
+ }];
46
+
47
+ describe("runSubagent 失败档(spec: subagent-spawn-runtime)", () => {
48
+ beforeEach(() => {
49
+ vi.clearAllMocks();
50
+ (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue({
51
+ name: "test-agent",
52
+ tools: ["read"],
53
+ systemPrompt: "You are a test agent",
54
+ });
55
+ delete process.env.TMUX;
56
+ delete process.env.WEZTERM_PANE;
57
+ });
58
+
59
+ it("Scenario 1:系统性失败不重试且透出 stderr(exit 0 + 占位 + stderr 非空)", async () => {
60
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
61
+ exitCode: 0,
62
+ output: "(no output)",
63
+ stderr: "Error: Cannot find module './judge'\n at require (node:internal)",
64
+ });
65
+ const result = await runSubagent(
66
+ "test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, GOOD_CONSTRAINT, false,
67
+ );
68
+ // 重试计数为零:spawn 只被调用 1 次
69
+ expect(spawnOnce).toHaveBeenCalledTimes(1);
70
+ // 失败档闭合标记
71
+ expect(result.error).toBeTruthy();
72
+ // 报错信息含 stderr 尾部原文
73
+ expect(result.output).toContain("Cannot find module './judge'");
74
+ // exitCode 保持子进程原值(本场景即 0)
75
+ expect(result.exitCode).toBe(0);
76
+ // stderr 不被剥离
77
+ expect(result.stderr).toContain("Cannot find module './judge'");
78
+ });
79
+
80
+ it("Scenario 2:个体违约保留重试(违约 + stderr 空 → 下一轮修正)", async () => {
81
+ (spawnOnce as ReturnType<typeof vi.fn>)
82
+ .mockResolvedValueOnce({ exitCode: 0, output: "bad format", stderr: "" })
83
+ .mockResolvedValueOnce({ exitCode: 0, output: "GOOD format", stderr: "" });
84
+ const result = await runSubagent(
85
+ "test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, GOOD_CONSTRAINT, false,
86
+ );
87
+ expect(spawnOnce).toHaveBeenCalledTimes(2);
88
+ expect(result.output).toBe("GOOD format");
89
+ });
90
+
91
+ it("Scenario 3a:正常完成零输出不误伤(无 constraints 原样返回)", async () => {
92
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
93
+ exitCode: 0,
94
+ output: "(no output)",
95
+ stderr: "",
96
+ });
97
+ const result = await runSubagent("test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, undefined, false);
98
+ expect(result.output).toBe("(no output)");
99
+ expect(result.error).toBeUndefined();
100
+ expect(spawnOnce).toHaveBeenCalledTimes(1);
101
+ });
102
+
103
+ it("Scenario 3b:正常完成零输出 + constraints → 按违约走个体失败重试档(现状)", async () => {
104
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
105
+ exitCode: 0,
106
+ output: "(no output)",
107
+ stderr: "",
108
+ });
109
+ const result = await runSubagent(
110
+ "test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, GOOD_CONSTRAINT, false,
111
+ );
112
+ // 现状行为:占位输出不满足约束 → 重派满 MAX_RETRIES=2
113
+ expect(spawnOnce).toHaveBeenCalledTimes(3);
114
+ expect(result.output).toBe("(no output)");
115
+ });
116
+
117
+ it("Scenario 4:有实质输出时 stderr 不影响成功判定", async () => {
118
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
119
+ exitCode: 0,
120
+ output: "GOOD substantial output",
121
+ stderr: "non-fatal deprecation warning",
122
+ });
123
+ const result = await runSubagent(
124
+ "test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, GOOD_CONSTRAINT, false,
125
+ );
126
+ expect(spawnOnce).toHaveBeenCalledTimes(1);
127
+ expect(result.error).toBeUndefined();
128
+ expect(result.output).toBe("GOOD substantial output");
129
+ });
130
+
131
+ it("Scenario 5(库侧):visible jsonl 信号源 error 注入后走系统性失败档", async () => {
132
+ // spawnVisible 被 mock:直接产出 finish() 注入信号后的形态(error 含信号源注明)
133
+ (spawnVisible as ReturnType<typeof vi.fn>).mockResolvedValue({
134
+ exitCode: 0,
135
+ output: "(no output)",
136
+ stderr: "",
137
+ error: "visible 模式信号源=jsonl 终结形态:session.jsonl 无 message 事件(未进入对话阶段)",
138
+ });
139
+ process.env.TMUX = "1";
140
+ const result = await runSubagent(
141
+ "test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, GOOD_CONSTRAINT,
142
+ );
143
+ delete process.env.TMUX;
144
+ expect(spawnVisible).toHaveBeenCalledTimes(1); // 不重试
145
+ expect(result.error).toContain("visible 模式信号源=jsonl 终结形态");
146
+ expect(result.output).toContain("visible 模式信号源=jsonl 终结形态");
147
+ });
148
+ });
@@ -5,6 +5,7 @@
5
5
  * 终端不可用 fallback / pane 消失后读取结果 / 超时 / abort。
6
6
  */
7
7
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
8
+ import { SubagentSession } from "../subagent-session";
8
9
 
9
10
  vi.mock("../subagent-utils", () => ({
10
11
  getPiCommand: vi.fn(() => ({ command: "node", args: ["/usr/local/bin/pi"] })),
@@ -121,6 +122,29 @@ describe("spawnVisible", () => {
121
122
  expect(safeCleanupMock).toHaveBeenCalledWith(false);
122
123
  });
123
124
 
125
+ // C1 修复防护:半行推进丢行反例——写侧未写完的行不解析、不丢失
126
+ it("半行不推进:未写完的行留到下一轮补读", async () => {
127
+ backendMock.isPaneAlive.mockReturnValue(true);
128
+ fsMock.existsSync.mockReturnValue(true);
129
+ // 第一轮:尾行是半行(无换行符)
130
+ fsMock.readFileSync.mockReturnValueOnce('{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"first"}]}}\n{"type":"par');
131
+ const parseSpy = vi.spyOn(SubagentSession.prototype, "parseSessionLine");
132
+ const resultPromise = spawnVisible("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
133
+ await vi.advanceTimersByTimeAsync(2000);
134
+ expect(parseSpy).toHaveBeenCalledTimes(1); // 只有完整行被解析
135
+ // 第二轮:写侧补全了第二行
136
+ fsMock.readFileSync.mockReturnValueOnce('{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"first"}]}}\n{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"second"}]}}\n');
137
+ await vi.advanceTimersByTimeAsync(2000);
138
+ expect(parseSpy).toHaveBeenCalledTimes(2);
139
+ // 收尾:pane 消失走 finish
140
+ backendMock.isPaneAlive.mockReturnValue(false);
141
+ fsMock.readFileSync.mockReturnValue('{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"second"}]}}\n');
142
+ await vi.advanceTimersByTimeAsync(5000);
143
+ const result = await resultPromise;
144
+ expect(result.output).toContain("second");
145
+ parseSpy.mockRestore();
146
+ });
147
+
124
148
  it("超时时返回 timedOut 并清理 pane", async () => {
125
149
  // pane 一直存活,但无 session 文件
126
150
  backendMock.isPaneAlive.mockReturnValue(true);