open-pstack 0.9.157 → 0.9.158

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-pstack",
3
- "version": "0.9.157",
3
+ "version": "0.9.158",
4
4
  "description": "Install pstack into the agent harnesses on this machine: Claude Code, Codex, Pi, Copilot, Muse, OMP, Kimi, Grok, MiniMax, OpenCode, Antigravity, and the shared skills directory.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.157",
3
+ "version": "0.9.158",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Antigravity. Original pstack by Lauren Tan (poteto).",
5
5
  "author": "Michael Denyer",
6
6
  "logo": "assets/pstack-icon.png",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (Claude Code port)",
4
- "version": "0.9.157",
4
+ "version": "0.9.158",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Claude Code. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.157",
3
+ "version": "0.9.158",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Codex port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/codex-tools.md. Original pstack by Lauren Tan (poteto).",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (GitHub Copilot port)",
4
- "version": "0.9.157",
4
+ "version": "0.9.158",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to GitHub Copilot CLI and app. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.157",
3
+ "version": "0.9.158",
4
4
  "description": "pstack workflows and skills for Grok Build",
5
5
  "skills": [
6
6
  "./skills",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "name": "pstack",
4
4
  "displayName": "pstack (Muse port)",
5
- "version": "0.9.157",
5
+ "version": "0.9.158",
6
6
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. Rigorous agent workflows you can parallelize with confidence. Muse port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/muse-tools.md. Original pstack by Lauren Tan (poteto).",
7
7
  "compat": {
8
8
  "source": "native",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.157",
3
+ "version": "0.9.158",
4
4
  "private": true,
5
5
  "omp": {
6
6
  "extensions": ["./omp/index.mjs"]
@@ -8,8 +8,9 @@ import { Value } from "typebox/value";
8
8
 
9
9
  import { noticeOf, OUTPUT_CAP_BYTES, statusText, truncateUtf8 } from "./agent-text.ts";
10
10
  import type { AgentParams } from "./agent-tools.ts";
11
- import { type Activity, type AgentChild, alive, type ChildExit, PiChild, terminateGroup } from "./child.ts";
11
+ import { type Activity, type AgentChild, alive, type ChildExit, type Fate, PiChild, terminateGroup } from "./child.ts";
12
12
  import { HcChild, pidOfTerminal } from "./hc-child.ts";
13
+ import { t3Brief, T3_ENV_REMOVED, T3Child, t3Host, t3Session, type T3Task } from "./t3-child.ts";
13
14
  import { loadAgentTypes } from "./agent-files.ts";
14
15
  import { checkEffort, DEPTH_FLAG, GENERAL_PURPOSE, InvalidValueError, PSTACK_STATE_DIR, readSheet, resolveModel, type Settings } from "./config.ts";
15
16
  import { ensureWorktree, planWorktree, settleWorktree, type Worktree, worktreeSchema } from "./worktree.ts";
@@ -25,6 +26,9 @@ const PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
25
26
 
26
27
  const endedStatus = Type.Union([Type.Literal("completed"), Type.Literal("failed"), Type.Literal("stopped")]);
27
28
  type EndedStatus = Static<typeof endedStatus>;
29
+ // Absent on a record an earlier version wrote; such an agent runs as an RPC child.
30
+ const hostSchema = Type.Union([Type.Literal("rpc"), Type.Literal("hc"), Type.Literal("t3")]);
31
+ type Host = Static<typeof hostSchema>;
28
32
 
29
33
  // Fixed when the agent starts and reused by every launch of it, so a resume
30
34
  // runs the same session, model, thinking, system prompt, and worktree.
@@ -42,6 +46,8 @@ const identitySchema = Type.Object({
42
46
  systemPromptFile: Type.Optional(Type.String()),
43
47
  cwd: Type.String(),
44
48
  worktree: Type.Optional(worktreeSchema),
49
+ host: Type.Optional(hostSchema),
50
+ t3ThreadId: Type.Optional(Type.String()),
45
51
  startedAt: Type.String(),
46
52
  });
47
53
  const runningSchema = Type.Object({
@@ -54,7 +60,8 @@ const runningSchema = Type.Object({
54
60
  pidStart: Type.Optional(Type.String()),
55
61
  // The pi process that launched it. Only that process may reap it.
56
62
  parentPid: Type.Number(),
57
- host: Type.Optional(Type.Literal("hc")),
63
+ host: Type.Optional(hostSchema),
64
+ t3TaskId: Type.Optional(Type.String()),
58
65
  });
59
66
  const endedSchema = Type.Object({
60
67
  agent: identitySchema,
@@ -86,9 +93,11 @@ interface Run {
86
93
  // A remote agent runs under the live pi process that restore left it to.
87
94
  type LocalAgent = { kind: "local"; record: RunningRecord; run: Run };
88
95
  // Unverified restores retry identity checks; interrupted ones await termination.
96
+ // A reap that finds the run gone leaves the record to the next look, which can
97
+ // persist it: by the time the reap ends, the session may have been replaced.
89
98
  type AgentState = LocalAgent
90
99
  | { kind: "remote"; record: RunningRecord }
91
- | { kind: "unverified"; record: RunningRecord }
100
+ | { kind: "unverified"; record: RunningRecord; gone?: boolean }
92
101
  | { kind: "interrupted"; record: RunningRecord }
93
102
  | { kind: "ended"; record: EndedRecord };
94
103
 
@@ -172,16 +181,9 @@ function inspect(pid: number): { parentPid: number; start: string } | undefined
172
181
  return m ? { parentPid: Number(m[1]), start: m[2] } : undefined;
173
182
  }
174
183
 
175
- // What became of the process a running record names:
176
- // - kept: it is still a child of the live pi process that launched it;
177
- // - orphan: it is the process the record was written for, its launcher gone
178
- // (an hc record written before its pid takes the pid and start that hc names
179
- // for the agent's terminal, in identifyByTerminalName);
180
- // - unknown: a process is there, and nothing says whether it is the agent's;
181
- // - gone: no process is there, or another one is.
182
- type Fate = "kept" | "orphan" | "unknown" | "gone";
183
-
184
- function fateOf(record: RunningRecord): Fate {
184
+ // A process host's run is the process the record names by pid and start time. An
185
+ // hc record written before its pid takes both from hc, in identifyByTerminalName.
186
+ function processFate(record: RunningRecord): Fate {
185
187
  const { pid, pidStart, parentPid } = record;
186
188
  if (pid === undefined || !alive(pid)) return "gone";
187
189
  const info = inspect(pid);
@@ -200,12 +202,23 @@ function identifyByTerminalName(record: RunningRecord): RunningRecord {
200
202
  return pid === undefined ? record : { ...record, pid, pidStart: inspect(pid)?.start };
201
203
  }
202
204
 
203
- // Stops an orphan, by its group so the bash command it has running goes too.
205
+ // Stops an orphan process, by its group so the bash command it has running goes too.
204
206
  // No other fate is signalled: a pid that may have been reused is not ours to hit.
205
- function reapOrphan(record: RunningRecord, killGraceMs: number): Promise<void> {
206
- return record.pid === undefined ? Promise.resolve() : terminateGroup(record.pid, () => fateOf(record) === "orphan", killGraceMs);
207
+ async function reapProcess(record: RunningRecord, killGraceMs: number): Promise<Fate> {
208
+ if (record.pid !== undefined) await terminateGroup(record.pid, () => processFate(record) === "orphan", killGraceMs);
209
+ return processFate(record);
210
+ }
211
+
212
+ interface HostPolicy {
213
+ fate(record: RunningRecord): Fate;
214
+ reap(record: RunningRecord, killGraceMs: number): Promise<Fate>;
215
+ notEnded(record: RunningRecord): string;
207
216
  }
208
217
 
218
+ const processHost: HostPolicy = { fate: processFate, reap: reapProcess, notEnded: ({ pid }) => `previous process (pid ${pid}) has not exited` };
219
+ const hosts: Record<Host, HostPolicy> = { rpc: processHost, hc: processHost, t3: t3Host };
220
+ const hostOf = (record: RunningRecord): HostPolicy => hosts[record.host ?? "rpc"];
221
+
209
222
  const now = () => new Date().toISOString();
210
223
 
211
224
  // A value the call left out came from the agent file, which the caller never
@@ -241,7 +254,8 @@ export class AgentRunner {
241
254
  const def = types.get(type);
242
255
  if (!def) throw new Error(`Unknown subagent_type "${type}". Valid types: ${[...types.keys()].join(", ")}.`);
243
256
  const parentModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
244
- const model = fromAgentFile(def.file, params.model, () => resolveModel(params.model ?? def.model, this.settings, readSheet(this.settings.agentDir, ctx.cwd), parentModel, ctx.modelRegistry));
257
+ const sheet = readSheet(this.settings.agentDir, ctx.cwd);
258
+ const model = fromAgentFile(def.file, params.model, () => resolveModel(params.model ?? def.model, this.settings, sheet, parentModel, ctx.modelRegistry));
245
259
  // Claude Code subagents without an effort run at their definition's effort, else the session's.
246
260
  const effort = params.effort ?? def.effort;
247
261
  const thinking = effort === undefined ? this.pi.getThinkingLevel() : fromAgentFile(def.file, params.effort, () => checkEffort(effort, this.settings));
@@ -252,6 +266,11 @@ export class AgentRunner {
252
266
  mkdirSync(sessionDir, { recursive: true });
253
267
  const systemPromptFile = def.body ? join(state, "prompts", `${id}.md`) : undefined;
254
268
  const worktree = params.isolation === "worktree" ? planWorktree(ctx.cwd, id) : undefined;
269
+ // delegate_task runs a task in the session thread's folder, never in the agent's worktree. T3 Code
270
+ // cannot remove a thread's tools, so a read-only agent and one at the depth limit stay local, where
271
+ // --exclude-tools enforces them.
272
+ const t3 = sheet?.t3Host && t3Session() && !worktree && !params.readonly && this.settings.depth + 1 < MAX_SPAWN_DEPTH;
273
+ const host: Host = t3 ? "t3" : sheet?.hcHost && process.env.HC_TERMINAL_ID ? "hc" : "rpc";
255
274
  const identity: AgentIdentity = {
256
275
  id,
257
276
  description: params.description,
@@ -264,6 +283,7 @@ export class AgentRunner {
264
283
  systemPromptFile,
265
284
  cwd: worktree?.path ?? ctx.cwd,
266
285
  worktree,
286
+ host,
267
287
  startedAt: now(),
268
288
  };
269
289
  this.attachSession(ctx);
@@ -285,9 +305,10 @@ export class AgentRunner {
285
305
  }
286
306
  throw e;
287
307
  }
288
- const child = this.spawnChild(identity, prompt);
308
+ const { child, host } = this.spawnChild(identity, prompt);
289
309
  const pidStart = child.pid === undefined ? undefined : inspect(child.pid)?.start;
290
- const record: RunningRecord = { agent: identity, status: "running", pid: child.pid, pidStart, parentPid: process.pid, host: child instanceof HcChild ? "hc" : undefined };
310
+ // An RPC record leaves host unset, as earlier versions wrote it, so an older pstack can still restore it.
311
+ const record: RunningRecord = { agent: identity, status: "running", pid: child.pid, pidStart, parentPid: process.pid, host: host === "rpc" ? undefined : host };
291
312
  const run: Run = { child, background, done: child.exited.then((exit) => this.finish(identity, run, exit)) };
292
313
  this.agents.set(identity.id, { kind: "local", record, run });
293
314
  this.persist(record);
@@ -295,15 +316,27 @@ export class AgentRunner {
295
316
  return record;
296
317
  }
297
318
 
298
- private spawnChild(identity: AgentIdentity, prompt: string): AgentChild {
319
+ private spawnChild(identity: AgentIdentity, prompt: string): { child: AgentChild; host: Host } {
299
320
  const { command, args } = this.settings.pi;
300
321
  const base = [...args, "--extension", join(this.settings.pluginRoot, "pi", "index.ts"), "--skill", join(this.settings.pluginRoot, "skills")];
301
322
  const flags = childArgs(identity, this.settings.depth);
302
- const env = { [PARENT_SESSION_ENV]: this.ownSessionId };
303
- // The session's sheet, as for the model: a worktree is a checkout of HEAD and lacks an uncommitted sheet.
304
- if (readSheet(this.settings.agentDir, identity.worktree?.repo ?? identity.cwd)?.hcHost && process.env.HC_TERMINAL_ID) {
323
+ // T3 Code runs a task in its thread's folder, so an agent in a worktree must not hand its own agents to T3 Code.
324
+ const env = { [PARENT_SESSION_ENV]: this.ownSessionId, ...(identity.worktree && T3_ENV_REMOVED) };
325
+ const host = identity.host ?? "rpc";
326
+ if (host === "t3") {
327
+ const t3 = t3Session();
328
+ if (!t3) throw new Error(`Agent ${identity.id} runs in T3 Code; message it from a Pi session inside T3 Code.`);
329
+ const onStart = ({ threadId, taskId }: T3Task) => {
330
+ identity.t3ThreadId = threadId;
331
+ this.track(identity.id, { t3TaskId: taskId });
332
+ };
333
+ const launch = { title: identity.description, model: identity.model, thinking: identity.thinking, threadId: identity.t3ThreadId, onStart };
334
+ return { child: new T3Child(t3, launch, identity.t3ThreadId ? prompt : t3Brief(identity, prompt)), host };
335
+ }
336
+ // An hc agent's session is a Pi session file, so outside herdr-core an RPC child resumes it.
337
+ if (host === "hc" && process.env.HC_TERMINAL_ID) {
305
338
  // An interactive pi asks whether to trust the project before it reports any status; the parent already decided.
306
- return new HcChild(identity.id, command, [...base, ...flags, this.projectTrusted ? "--approve" : "--no-approve"], {
339
+ const child = new HcChild(identity.id, command, [...base, ...flags, this.projectTrusted ? "--approve" : "--no-approve"], {
307
340
  cwd: identity.cwd,
308
341
  env: { ...env, PI_CODING_AGENT_DIR: this.settings.agentDir },
309
342
  envFile: join(identity.sessionDir, `${identity.id}.env`),
@@ -311,11 +344,13 @@ export class AgentRunner {
311
344
  transcript: () => sessionFile(identity),
312
345
  onStart: (pid) => this.track(identity.id, { pid, pidStart: inspect(pid)?.start }),
313
346
  }, prompt);
347
+ return { child, host };
314
348
  }
315
- return new PiChild(command, [...base, "--mode", "rpc", ...flags], { cwd: identity.cwd, env, exitGraceMs: this.settings.exitGraceMs, onActivity: () => this.showStatus() }, prompt);
349
+ const child = new PiChild(command, [...base, "--mode", "rpc", ...flags], { cwd: identity.cwd, env, exitGraceMs: this.settings.exitGraceMs, onActivity: () => this.showStatus() }, prompt);
350
+ return { child, host: "rpc" };
316
351
  }
317
352
 
318
- private track(id: string, handle: Pick<RunningRecord, "pid" | "pidStart">): void {
353
+ private track(id: string, handle: Pick<RunningRecord, "pid" | "pidStart"> | Pick<RunningRecord, "t3TaskId">): void {
319
354
  const state = this.agents.get(id);
320
355
  if (state?.kind !== "local") return;
321
356
  Object.assign(state.record, handle);
@@ -408,14 +443,14 @@ export class AgentRunner {
408
443
  }
409
444
 
410
445
  // An agent this process can act on. One running under another pi process is
411
- // not: only that process holds its stdin and can message or stop it.
446
+ // not: only that process holds its run and can message or stop it.
412
447
  private owned(to: string): Exclude<AgentState, { kind: "remote" | "unverified" | "interrupted" }> {
413
448
  const state = this.find(to);
414
449
  if (state.kind === "remote") {
415
450
  throw new Error(`Agent ${state.record.agent.id} is running under another pi process (pid ${state.record.parentPid}); only that process can message or stop it.`);
416
451
  }
417
452
  if (state.kind === "unverified" || state.kind === "interrupted") {
418
- throw new Error(`Agent ${state.record.agent.id}'s previous process (pid ${state.record.pid}) has not exited; it cannot resume or be stopped here until its exit is confirmed.`);
453
+ throw new Error(`Agent ${state.record.agent.id}'s ${hostOf(state.record).notEnded(state.record)}; it cannot resume or be stopped here until its exit is confirmed.`);
419
454
  }
420
455
  return state;
421
456
  }
@@ -473,7 +508,7 @@ export class AgentRunner {
473
508
  private refreshRestored(state: AgentState): AgentState {
474
509
  if (state.kind === "local" || state.kind === "ended") return state;
475
510
  const { record } = state;
476
- const fate = fateOf(record);
511
+ const fate = state.kind === "unverified" && state.gone ? "gone" : hostOf(record).fate(record);
477
512
  if (fate === "kept" && state.kind === "remote") return state;
478
513
  if (fate !== "gone") {
479
514
  if (state.kind === "interrupted") return state;
@@ -483,9 +518,9 @@ export class AgentRunner {
483
518
  };
484
519
  this.agents.set(record.agent.id, restored);
485
520
  if (restored.kind === "interrupted") {
486
- void reapOrphan(record, this.settings.killGraceMs).then(() => {
521
+ void hostOf(record).reap(record, this.settings.killGraceMs).then((next) => {
487
522
  if (this.agents.get(record.agent.id) === restored) {
488
- this.agents.set(record.agent.id, { kind: "unverified", record });
523
+ this.agents.set(record.agent.id, { kind: "unverified", record, gone: next === "gone" });
489
524
  }
490
525
  });
491
526
  }
@@ -505,8 +540,8 @@ export class AgentRunner {
505
540
  return ended;
506
541
  }
507
542
 
508
- // A restored process stays unavailable until its exit is confirmed. Only a
509
- // process whose identity matches the record can be signalled.
543
+ // A restored run stays unavailable until its host reports it gone. Only a run
544
+ // its host identifies as the record's is stopped.
510
545
  restore(entries: readonly SessionEntry[]): void {
511
546
  for (const entry of entries) {
512
547
  if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE || !Value.Check(recordSchema, entry.data)) continue;
@@ -260,6 +260,13 @@ export class PiChild {
260
260
 
261
261
  export type AgentChild = Pick<PiChild, "pid" | "exited" | "activity" | "steer" | "end" | "signal">;
262
262
 
263
+ // What became of a restored running record's run, as its host reports it:
264
+ // - kept: another live pi holds it;
265
+ // - orphan: it is the record's run, and no live pi holds it;
266
+ // - unknown: something runs, and the host cannot tell whether it is the agent's;
267
+ // - gone: nothing of the run is left.
268
+ export type Fate = "kept" | "orphan" | "unknown" | "gone";
269
+
263
270
  // Splits pi's stdout into lines on LF only: a Unicode line separator is valid
264
271
  // inside a JSON string.
265
272
  export function lineSplitter(onLine: (line: string) => void): { write(chunk: Buffer | string): void; end(): void } {
@@ -70,6 +70,7 @@ interface Sheet {
70
70
  // profile that delegates through another extension, such as pi-subagents.
71
71
  agentToolsOff: boolean;
72
72
  hcHost: boolean;
73
+ t3Host: boolean;
73
74
  piModels: Map<string, string>;
74
75
  }
75
76
 
@@ -90,6 +91,7 @@ export function parseSheet(text: string): Sheet {
90
91
  askToolOff: lines.some((l) => l === "pi ask tool: off"),
91
92
  agentToolsOff: lines.some((l) => l === "pi agent tools: off"),
92
93
  hcHost: lines.some((l) => l === "pi agent host: hc"),
94
+ t3Host: lines.some((l) => l === "pi agent host: t3"),
93
95
  piModels,
94
96
  };
95
97
  }
@@ -0,0 +1,254 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { type Static, type TSchema, Type } from "typebox";
3
+ import { Value } from "typebox/value";
4
+
5
+ import { alive, type ChildExit, type Fate } from "./child.ts";
6
+
7
+ const PROTOCOL = "2025-06-18";
8
+ const WAIT_MS = 30_000;
9
+ // T3 Code's terminal task statuses (OrchestratorMcpTerminalDelegatedTaskStatus).
10
+ const ENDED = new Set(["completed", "failed", "cancelled", "interrupted"]);
11
+
12
+ const toolResult = Type.Object({
13
+ content: Type.Optional(Type.Array(Type.Object({ type: Type.String(), text: Type.Optional(Type.String()) }))),
14
+ structuredContent: Type.Optional(Type.Unknown()),
15
+ isError: Type.Optional(Type.Boolean()),
16
+ });
17
+ const delegated = Type.Object({ taskId: Type.String(), childThreadId: Type.String(), childRunId: Type.Union([Type.String(), Type.Null()]) });
18
+ const sent = Type.Object({ taskId: Type.Optional(Type.Union([Type.String(), Type.Null()])), runId: Type.String(), delivery: Type.String() });
19
+ const waited = Type.Object({ timedOut: Type.Boolean() });
20
+ const taskResult = Type.Object({ status: Type.String(), summary: Type.Union([Type.String(), Type.Null()]) });
21
+ const capabilities = Type.Object({
22
+ inheritedProviderInstanceId: Type.String(),
23
+ inheritedModel: Type.Optional(Type.Union([Type.String(), Type.Null()])),
24
+ providers: Type.Array(
25
+ Type.Object({
26
+ providerInstanceId: Type.String(),
27
+ models: Type.Array(Type.Object({ id: Type.String(), options: Type.Optional(Type.Array(Type.Object({ id: Type.String(), values: Type.Optional(Type.Array(Type.Unknown())) }))) })),
28
+ }),
29
+ ),
30
+ });
31
+
32
+ export interface T3Session {
33
+ endpoint: string;
34
+ token: string;
35
+ }
36
+
37
+ export const T3_ENV_REMOVED = { T3_MCP_URL: undefined, T3_MCP_BEARER_TOKEN: undefined };
38
+
39
+ export function t3Session(): T3Session | undefined {
40
+ const endpoint = process.env.T3_MCP_URL;
41
+ const token = process.env.T3_MCP_BEARER_TOKEN;
42
+ return endpoint && token ? { endpoint, token } : undefined;
43
+ }
44
+
45
+ export interface T3Task {
46
+ threadId: string;
47
+ taskId: string;
48
+ }
49
+
50
+ export interface T3Launch {
51
+ title: string;
52
+ model?: string;
53
+ thinking?: string;
54
+ threadId?: string;
55
+ onStart: (task: T3Task) => void;
56
+ }
57
+
58
+ // A T3 Code thread takes no launch flags, so its first message carries the agent file's body.
59
+ export function t3Brief(agent: { subagentType: string; systemPromptFile?: string }, prompt: string): string {
60
+ const body = agent.systemPromptFile ? readFileSync(agent.systemPromptFile, "utf8").trim() : "";
61
+ const parts = [
62
+ body && `<agent name="${agent.subagentType}">\n${body}\n</agent>`,
63
+ prompt,
64
+ ];
65
+ return parts.filter(Boolean).join("\n\n");
66
+ }
67
+
68
+ export class T3Child {
69
+ readonly pid = undefined;
70
+ readonly activity = undefined;
71
+ readonly exited: Promise<ChildExit>;
72
+ private readonly mcp: T3Mcp;
73
+ private threadId?: string;
74
+ private taskId?: string;
75
+ private settled = false;
76
+ private ending = false;
77
+ private cancelled?: Promise<void>;
78
+ private readonly stopWaiting = new AbortController();
79
+
80
+ constructor(session: T3Session, launch: T3Launch, prompt: string) {
81
+ this.mcp = new T3Mcp(session);
82
+ this.exited = this.drive(launch, prompt);
83
+ }
84
+
85
+ async steer(message: string): Promise<{ response: { success: boolean } | undefined; taken: boolean }> {
86
+ if (this.settled || this.threadId === undefined) return { response: undefined, taken: false };
87
+ try {
88
+ const { delivery } = await this.mcp.call(sent, "t3_thread_send", { threadId: this.threadId, message, mode: "steer" });
89
+ return { response: { success: true }, taken: delivery === "steered" && !this.settled };
90
+ } catch {
91
+ return { response: undefined, taken: false };
92
+ }
93
+ }
94
+
95
+ // T3 Code has no kill, so after graceMs the agent stops waiting for the thread to settle.
96
+ end(graceMs: number): void {
97
+ this.ending = true;
98
+ void this.cancel();
99
+ setTimeout(() => this.stopWaiting.abort(new Error(`T3 Code had not settled thread ${this.threadId} ${graceMs} ms after the cancel of task ${this.taskId}.`)), graceMs).unref();
100
+ }
101
+
102
+ // The exit hook runs synchronously, so a task_cancel would never go out; a resumed session inside T3 Code cancels the task as an orphan.
103
+ signal(): void {}
104
+
105
+ private async drive(launch: T3Launch, prompt: string): Promise<ChildExit> {
106
+ try {
107
+ const { threadId, runId } = await this.start(launch, prompt);
108
+ if (this.ending) await this.cancel();
109
+ await settled(this.mcp, threadId, runId, this.stopWaiting.signal);
110
+ const { status, summary } = await this.mcp.call(taskResult, "task_status", { taskId: this.taskId });
111
+ this.settled = status === "completed";
112
+ const text = summary ?? "";
113
+ if (this.settled) return { exitCode: 0, settled: true, finalText: text, errorMessage: "", stderr: "" };
114
+ return { exitCode: null, settled: false, finalText: "", errorMessage: text || `The T3 Code task ended with status ${status}.`, stderr: "" };
115
+ } catch (e) {
116
+ const message = (e as Error).message;
117
+ return { exitCode: null, settled: false, finalText: this.ending ? message : "", errorMessage: message, stderr: "" };
118
+ }
119
+ }
120
+
121
+ private async start(launch: T3Launch, prompt: string): Promise<{ threadId: string; runId?: string }> {
122
+ if (launch.threadId !== undefined) {
123
+ this.threadId = launch.threadId;
124
+ const { taskId, runId } = await this.mcp.call(sent, "t3_thread_send", { threadId: launch.threadId, message: prompt, mode: "auto" });
125
+ if (!taskId) throw new Error(`T3 Code took the message in thread ${launch.threadId} without starting a task.`);
126
+ this.taskId = taskId;
127
+ launch.onStart({ threadId: launch.threadId, taskId });
128
+ return { threadId: launch.threadId, runId };
129
+ }
130
+ const thinking = launch.thinking && (await this.takesThinking(launch.model, launch.thinking)) ? { options: { thinking: launch.thinking } } : {};
131
+ const target = { ...(launch.model && { model: launch.model }), ...thinking };
132
+ const task = await this.mcp.call(delegated, "delegate_task", { task: prompt, title: launch.title, target, mode: "async" });
133
+ this.threadId = task.childThreadId;
134
+ this.taskId = task.taskId;
135
+ launch.onStart({ threadId: task.childThreadId, taskId: task.taskId });
136
+ return { threadId: task.childThreadId, runId: task.childRunId ?? undefined };
137
+ }
138
+
139
+ private async takesThinking(model: string | undefined, thinking: string): Promise<boolean> {
140
+ const caps = await this.mcp.call(capabilities, "orchestrator_capabilities", model ? { search: model } : {});
141
+ const id = model ?? caps.inheritedModel;
142
+ const provider = caps.providers.find((p) => p.providerInstanceId === caps.inheritedProviderInstanceId);
143
+ const levels = provider?.models.find((m) => m.id === id)?.options?.find((o) => o.id === "thinking")?.values ?? [];
144
+ return levels.includes(thinking);
145
+ }
146
+
147
+ private cancel(): Promise<void> | undefined {
148
+ const { taskId, threadId } = this;
149
+ if (taskId === undefined) return;
150
+ this.cancelled ??= this.mcp.call(Type.Unknown(), "task_cancel", { taskId, reason: "stop_agent" }).then(
151
+ () => undefined,
152
+ (e: Error) => this.stopWaiting.abort(new Error(`T3 Code did not cancel task ${taskId}, so thread ${threadId} may still be running: ${e.message}`)),
153
+ );
154
+ return this.cancelled;
155
+ }
156
+ }
157
+
158
+ export async function cancelOrphan(task: T3Task): Promise<boolean> {
159
+ const session = t3Session();
160
+ if (!session) return false;
161
+ const mcp = new T3Mcp(session);
162
+ try {
163
+ await mcp.call(Type.Unknown(), "task_cancel", { taskId: task.taskId, reason: "its Pi session ended" });
164
+ await settled(mcp, task.threadId);
165
+ return true;
166
+ } catch {
167
+ // A task that has already ended needs no cancel, and T3 Code may refuse one for good.
168
+ return mcp.call(taskResult, "task_status", { taskId: task.taskId }).then(({ status }) => ENDED.has(status), () => false);
169
+ }
170
+ }
171
+
172
+ type T3Record = { parentPid: number; t3TaskId?: string; agent: { t3ThreadId?: string } };
173
+
174
+ export const t3Host = {
175
+ fate: ({ t3TaskId, parentPid }: T3Record): Fate => (t3TaskId === undefined ? "gone" : parentPid !== process.pid && alive(parentPid) ? "kept" : "orphan"),
176
+ reap: async ({ t3TaskId, agent }: T3Record): Promise<Fate> =>
177
+ t3TaskId && agent.t3ThreadId && (await cancelOrphan({ taskId: t3TaskId, threadId: agent.t3ThreadId })) ? "gone" : "orphan",
178
+ notEnded: ({ t3TaskId }: T3Record): string => `T3 Code task ${t3TaskId} has not been cancelled`,
179
+ };
180
+
181
+ async function settled(mcp: T3Mcp, threadId: string, runId?: string, signal?: AbortSignal): Promise<void> {
182
+ for (;;) {
183
+ const { timedOut } = await mcp.call(waited, "t3_thread_wait", { threadId, ...(runId && { runId }), timeoutMs: WAIT_MS, untilDelegatedWorkSettled: true }, signal);
184
+ if (!timedOut) return;
185
+ }
186
+ }
187
+
188
+ class T3Mcp {
189
+ private nextId = 1;
190
+ private sessionId?: string;
191
+ private ready?: Promise<unknown>;
192
+
193
+ constructor(private readonly session: T3Session) {}
194
+
195
+ async call<T extends TSchema>(schema: T, name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<Static<T>> {
196
+ this.ready ??= this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pstack", version: "1" } }).then(() =>
197
+ this.post({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }),
198
+ );
199
+ await this.ready;
200
+ const result = await this.request("tools/call", { name, arguments: args }, signal);
201
+ if (!Value.Check(toolResult, result)) throw new Error(`T3 Code ${name} answered: ${JSON.stringify(result).slice(0, 300)}`);
202
+ const text = result.content?.find((part) => part.type === "text")?.text ?? "";
203
+ if (result.isError) throw new Error(`T3 Code ${name} failed: ${text.slice(0, 1000)}`);
204
+ const value = result.structuredContent ?? parseJson(text);
205
+ if (value === undefined || !Value.Check(schema, value)) throw new Error(`T3 Code ${name} answered: ${text.slice(0, 300)}`);
206
+ return value;
207
+ }
208
+
209
+ private async request(method: string, params: unknown, signal?: AbortSignal): Promise<unknown> {
210
+ const response = await this.post({ jsonrpc: "2.0", id: this.nextId++, method, params }, signal);
211
+ const body = await response.text();
212
+ if (!response.ok) throw new Error(`T3 Code MCP ${method} failed (${response.status}): ${body.slice(0, 300)}`);
213
+ const reply = rpcReply(body, response.headers.get("content-type") ?? "");
214
+ if (reply.error) throw new Error(`T3 Code MCP ${method} failed: ${reply.error.message ?? JSON.stringify(reply.error)}`);
215
+ return reply.result;
216
+ }
217
+
218
+ private async post(message: unknown, signal?: AbortSignal): Promise<Response> {
219
+ const headers: Record<string, string> = {
220
+ accept: "application/json, text/event-stream",
221
+ authorization: `Bearer ${this.session.token}`,
222
+ "content-type": "application/json",
223
+ "mcp-protocol-version": PROTOCOL,
224
+ ...(this.sessionId && { "mcp-session-id": this.sessionId }),
225
+ };
226
+ const response = await fetch(this.session.endpoint, { method: "POST", headers, body: JSON.stringify(message), signal });
227
+ this.sessionId = response.headers.get("mcp-session-id") ?? this.sessionId;
228
+ return response;
229
+ }
230
+ }
231
+
232
+ function rpcReply(body: string, contentType: string): { result?: unknown; error?: { message?: string } } {
233
+ if (!contentType.includes("text/event-stream")) return JSON.parse(body);
234
+ let data: string[] = [];
235
+ for (const line of [...body.split(/\r\n|\r|\n/), ""]) {
236
+ if (line.startsWith("data:")) data.push(line.slice(line.startsWith("data: ") ? 6 : 5));
237
+ else if (line === "" && data.length) {
238
+ const text = data.join("\n");
239
+ data = [];
240
+ if (!text) continue;
241
+ const reply = JSON.parse(text);
242
+ if (reply.id !== undefined) return reply;
243
+ }
244
+ }
245
+ throw new Error("T3 Code MCP sent an event stream with no reply.");
246
+ }
247
+
248
+ function parseJson(text: string): unknown {
249
+ try {
250
+ return JSON.parse(text);
251
+ } catch {
252
+ return undefined;
253
+ }
254
+ }
@@ -35,7 +35,8 @@ poteto-mode's Subagents section applies on Pi through the `agent` tool:
35
35
  - `subagent_type` takes the same values. `pstack:poteto-agent`, `pstack:comment-sicko`, `pstack:thermo-nuclear-review-subagent`, and `pstack:thermo-nuclear-code-quality-review-subagent` resolve to the plugin's agent files. A `.md` file in `pstack-agents` in the Pi agent directory adds a type under its file name with no `pstack:` prefix, as a Claude Code user agent has no plugin prefix, and the body after the frontmatter is the child's system prompt. Its `tools:`, `disallowedTools:`, and `isolation:` fields are ignored, so pass `readonly: true` or `isolation: "worktree"` on the `agent` call instead. A hidden file, a file whose name has a colon, and one that cannot be read are skipped. The extension reads the frontmatter as YAML, and a repeated key keeps its last value, as in Claude Code. When the YAML does not parse, it retries as Claude Code 2.1.310 does, reading an unquoted top-level value that holds YAML syntax, such as `description: Use for a: b`, as text and turning leading tabs into spaces. It skips a user file whose frontmatter still does not parse. A user file never replaces a type, so `poteto-agent.md` there adds `poteto-agent` and leaves `pstack:poteto-agent` alone. The extension does not read Pi's `agents` folder, whose files other subagent extensions write with their own frontmatter. `general-purpose`, or no `subagent_type`, runs a child with no agent file. Claude Code's built-in types such as `Explore` and `Plan` do not exist on Pi, so use `general-purpose` and put the constraint in the prompt. An unknown type errors and lists the valid ones. The `agent` tool's `subagent_type` description lists each type the session starts with and what it is for, from each agent file's `description:`, the user's files included.
36
36
  - `readonly: true`, which the `how` subagent sets, runs the child without the `edit` and `write` tools. It keeps `bash`, so a reviewer can still run `git diff`; say in the prompt that it must not change files.
37
37
  - Each child is its own `pi --mode rpc` process in your working directory, and the extension sends it the prompt on its stdin. It loads the packages and settings saved on disk, so it sees the pstack skills when pstack was installed with `pi install`. It does not inherit the parent's command-line flags, such as `-e`, `--api-key`, or a one-off `-a` project trust, so a pstack loaded only through `-e` gives children no extension.
38
- - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt.
38
+ - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child started there is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt. Messaged from a session outside herdr-core, it runs that turn as an RPC child.
39
+ - With a `pi agent host: t3` line in the sheet and the session inside T3 Code (`T3_MCP_URL` and `T3_MCP_BEARER_TOKEN` are set), each child started there without `isolation: "worktree"` is instead a T3 Code child thread of your thread, titled with the agent's description, on the agent's model, in your thread's folder. Its effort goes to T3 Code only when T3 Code lists that level for the model. The user can watch it and type into it in T3 Code. `send_message` to a running one steers its turn, a finished one resumes in the same thread, and `stop_agent` cancels its task; when T3 Code refuses the cancel, the agent reads as stopped with the refusal as its text, and its thread can go on running. When T3 Code accepts the cancel but the thread has not settled after the kill grace, the agent also reads as stopped. A worktree agent and the agents it starts stay local processes in its worktree. A `readonly: true` agent and an agent at the third layer also stay local processes, because T3 Code cannot remove a thread's tools. A question it asks waits until someone answers it in T3 Code. T3 Code marks its first message as sent by an agent, so say in the prompt that the user started the task. The agent file's body arrives at the top of its first message. Only a Pi session inside T3 Code can message it. `list_agents` shows no `activity` and no transcript for it; its transcript is the T3 Code thread.
39
40
  - A child can start its own agents, down to three layers below the main session, as on Claude Code. A child at the third layer runs without the `agent` tool.
40
41
  - `isolation: "worktree"` runs the child in its own git worktree under `.claude/worktrees/`. A worktree the agent left nothing in is removed when the agent finishes; a change, a gitignored file it wrote, or a commit on its branch or on any commit its HEAD visited keeps it.
41
42
  - `run_in_background: true` returns the agent id at once. The completion joins the conversation after your current tool calls finish, as on Claude Code, or starts a turn when you are idle. In print and JSON mode (`pi -p`), where Pi exits once the run settles, the extension holds the settle while a background agent runs, so each completion still arrives as a turn and the process ends after the last one. A child agent holds its settle the same way while its own background agents run, because its parent closes its stdin once it settles, and a message from the parent ends the hold. Interactive and RPC main sessions settle as usual and take the completion when it arrives.
@@ -95,7 +96,7 @@ No skill file carries a Pi line. poteto-mode's Platform Adaptation section point
95
96
  | `interrogate` | Adversaries dispatch through `agent` with the same `subagent_type` and `model` (see Subagent policy). Keep the panel on distinct models (see Model names). |
96
97
  | `recall` | Search the Pi sessions directory for this workspace (see Tool actions). Do not list or read `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/`: it holds Claude Code transcripts, not this session's history. Match on `type: "message"` entries and their `message.role`. |
97
98
  | `show-me-your-work` | Check the log against this run's Pi session file (see Tool actions), not a Claude Code transcript. |
98
- | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
99
+ | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`; inside T3 Code, add `pi agent host: t3`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
99
100
  | `no-comments` | `pstack:comment-sicko` resolves through `agent` as written. Pass it the scope, not a request to run `/no-comments`, and run it without `isolation: "worktree"`, because a worktree starts from `HEAD` and lacks the scope's uncommitted changes. |
100
101
  | `teach` | Running `how` and `why` in parallel maps to two background `agent` calls. Pi has no image generation tool, so draw with Mermaid or plain text. |
101
102
  | `create-verification-skill` | The generated skill lands under `.claude/skills/verify/` on Claude Code. Write it where Pi discovers project skills, `.pi/skills/verify/` or `.agents/skills/verify/`, instead. The app-driving harness is platform-neutral. |
@@ -7,6 +7,77 @@ import type { GitHubReader } from "./types.ts";
7
7
 
8
8
  const silentIo = { stdout: () => {}, stderr: () => {} };
9
9
 
10
+ describe("watching a head without checks after an earlier commit passed", () => {
11
+ it.each([
12
+ [
13
+ "CONFLICTING",
14
+ { mergeable: "CONFLICTING" },
15
+ 2,
16
+ ["BLOCKER"],
17
+ "merge-conflicts",
18
+ ],
19
+ [
20
+ "DIRTY",
21
+ { mergeable: "UNKNOWN", mergeStateStatus: "DIRTY" },
22
+ 2,
23
+ ["BLOCKER"],
24
+ "merge-conflicts",
25
+ ],
26
+ [
27
+ "MERGEABLE",
28
+ { mergeable: "MERGEABLE" },
29
+ 7,
30
+ ["RETRY", "BLOCKER"],
31
+ "status-query",
32
+ ],
33
+ ] as const)(
34
+ "uses the correct verdict for %s",
35
+ async (_label, facts, exitCode, kinds, blocker) => {
36
+ const stdout: string[] = [];
37
+ const runtime = {
38
+ reader: fakeReader({
39
+ facts,
40
+ fastPath: { kind: "none-reported" },
41
+ rollupPages: [{ kind: "no-rollup" }],
42
+ commitRollups: [
43
+ { oid: "earlier", state: "SUCCESS" },
44
+ { oid: "head", state: null },
45
+ ],
46
+ }),
47
+ deadline: new WatchDeadline(0, () => 0),
48
+ clock: {
49
+ now: () => 0,
50
+ observedAt: () => "2026-07-26T00:00:00.000Z",
51
+ async sleep() {},
52
+ },
53
+ stdout: (text: string) => stdout.push(text),
54
+ stderr: () => {},
55
+ } satisfies CliRuntime;
56
+ const code = await main(
57
+ [
58
+ "--owner",
59
+ "owner",
60
+ "--repo",
61
+ "repo",
62
+ "--pr",
63
+ "1",
64
+ "--max-query-errors",
65
+ "2",
66
+ ],
67
+ runtime
68
+ );
69
+ expect(code).toBe(exitCode);
70
+ const verdicts = stdout.map((line) => JSON.parse(line));
71
+ expect(verdicts.map((verdict) => verdict.kind)).toEqual([...kinds]);
72
+ expect(verdicts.at(-1)).toMatchObject({
73
+ terminal: true,
74
+ exitCode,
75
+ blocker: { kind: blocker },
76
+ });
77
+ }
78
+ );
79
+ });
80
+
10
81
  describe("--expect-app", () => {
11
82
  it("collects each named app into the polling options", () => {
12
83
  expect(
@@ -152,17 +152,55 @@ describe("facts that change while the snapshot is read", () => {
152
152
  });
153
153
  });
154
154
 
155
+ it.each([
156
+ [
157
+ { mergeable: "UNKNOWN", mergeStateStatus: "DIRTY" },
158
+ "mergeStateStatus DIRTY -> CLEAN",
159
+ ],
160
+ [
161
+ { mergeable: "CONFLICTING", mergeStateStatus: "UNKNOWN" },
162
+ "mergeable CONFLICTING -> MERGEABLE",
163
+ ],
164
+ ] as const)(
165
+ "retries when one merge field is unknown and the other clears a known conflict (%j)",
166
+ async (facts, detail) => {
167
+ await expect(
168
+ read({
169
+ facts,
170
+ factsOnReread: { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" },
171
+ fastPath: { kind: "none-reported" },
172
+ rollupPages: [{ kind: "no-rollup" }],
173
+ commitRollups: [
174
+ { oid: "earlier", state: "SUCCESS" },
175
+ { oid: "head", state: null },
176
+ ],
177
+ })
178
+ ).rejects.toMatchObject({
179
+ failure: {
180
+ kind: "snapshot-changed",
181
+ retryable: true,
182
+ detail: expect.stringContaining(detail),
183
+ },
184
+ });
185
+ }
186
+ );
187
+
155
188
  it("keeps an unknown first read when GitHub computes mergeability before the re-read", async () => {
156
189
  const unknown = {
157
190
  mergeable: "UNKNOWN",
158
191
  mergeStateStatus: "UNKNOWN",
159
192
  } as const;
160
- expect(
161
- await read({
162
- facts: unknown,
163
- factsOnReread: { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" },
164
- })
165
- ).toMatchObject({ kind: "open", facts: unknown });
193
+ for (const facts of [
194
+ unknown,
195
+ { mergeable: "UNKNOWN", mergeStateStatus: "CLEAN" },
196
+ { mergeable: "MERGEABLE", mergeStateStatus: "UNKNOWN" },
197
+ ] as const)
198
+ expect(
199
+ await read({
200
+ facts,
201
+ factsOnReread: { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" },
202
+ })
203
+ ).toMatchObject({ kind: "open", facts });
166
204
  await expect(
167
205
  read({
168
206
  facts: unknown,
@@ -691,6 +729,24 @@ describe("a PR with no checks configured", () => {
691
729
  });
692
730
  });
693
731
 
732
+ it("keeps earlier passing CI in a conflicting head's unreported status", async () => {
733
+ const snapshot = await read({
734
+ facts: { mergeStateStatus: "DIRTY" },
735
+ commitRollups: [
736
+ { oid: "earlier", state: "SUCCESS" },
737
+ { oid: "head", state: null },
738
+ ],
739
+ });
740
+ expect(snapshot).toMatchObject({
741
+ kind: "open",
742
+ ci: { kind: "ci-unreported", hadPreviousPassingCi: true },
743
+ });
744
+ expect(classifyPr(snapshot)).toMatchObject({
745
+ kind: "blocker",
746
+ blocker: { kind: "merge-conflicts" },
747
+ });
748
+ });
749
+
694
750
  it("fails closed while the head may not have reported yet", async () => {
695
751
  const unsettled = [
696
752
  {
@@ -58,6 +58,13 @@ async function mergeAssessment(
58
58
  };
59
59
  }
60
60
  type OpenFacts = Extract<T.PullRequestFacts, { readonly state: "OPEN" }>;
61
+ function hasMergeConflict(facts: OpenFacts): boolean {
62
+ return (
63
+ facts.mergeable === "CONFLICTING" ||
64
+ facts.mergeStateStatus === "DIRTY" ||
65
+ facts.mergeStateStatus === "CONFLICTING"
66
+ );
67
+ }
61
68
  export type NoChecksConfirmer = (
62
69
  head: Pick<OpenFacts, "context" | "headRefOid">
63
70
  ) => boolean;
@@ -92,15 +99,22 @@ async function noChecksCi(
92
99
  confirmNoChecks = neverConfirms
93
100
  ): Promise<T.CiNone | T.CiUnreported> {
94
101
  const merge = await mergeAssessment(reader, facts);
95
- if (merge.anyCommitReported || merge.github.kind === "refused")
96
- throw new ChecksUnavailable(
97
- `no checks reported on head ${facts.headRefOid}, but a commit on this PR has reported checks`
98
- );
99
102
  const none = {
100
103
  failed: [],
101
104
  pending: [],
102
105
  hadPreviousPassingCi: false,
103
106
  } as const;
107
+ if (merge.anyCommitReported || merge.github.kind === "refused") {
108
+ if (merge.github.headRollupState === null && hasMergeConflict(facts))
109
+ return {
110
+ ...none,
111
+ kind: "ci-unreported",
112
+ hadPreviousPassingCi: merge.hadPreviousPassingCi,
113
+ };
114
+ throw new ChecksUnavailable(
115
+ `no checks reported on head ${facts.headRefOid}, but a commit on this PR has reported checks`
116
+ );
117
+ }
104
118
  return confirmNoChecks(facts)
105
119
  ? { ...none, kind: "ci-none", github: merge.github, queuedWithoutRuns }
106
120
  : { ...none, kind: "ci-unreported" };
@@ -128,8 +142,8 @@ const VERDICT_FACTS: Record<
128
142
  };
129
143
  const mergeabilityUnknown = (facts: T.PullRequestFacts): boolean =>
130
144
  facts.mergeable === "UNKNOWN" || facts.mergeStateStatus === "UNKNOWN";
131
- // GitHub computes these two on the first read that asks, so an unknown first
132
- // read usually has its answer by the re-read. That is not the PR changing.
145
+ // GitHub may compute either field between reads. Ignore only the field
146
+ // whose original value was unknown.
133
147
  const COMPUTED_ON_DEMAND: ReadonlySet<string> = new Set([
134
148
  "mergeable",
135
149
  "mergeStateStatus",
@@ -141,7 +155,7 @@ const changedFacts = (
141
155
  (Object.keys(VERDICT_FACTS) as (keyof typeof VERDICT_FACTS)[])
142
156
  .filter((fact) => before[fact] !== after[fact])
143
157
  .filter(
144
- (fact) => !(mergeabilityUnknown(before) && COMPUTED_ON_DEMAND.has(fact))
158
+ (fact) => !(before[fact] === "UNKNOWN" && COMPUTED_ON_DEMAND.has(fact))
145
159
  )
146
160
  .map((fact) => `${fact} ${before[fact]} -> ${after[fact]}`);
147
161
  export async function readSnapshot(args: {
@@ -251,10 +265,7 @@ export async function readSnapshot(args: {
251
265
  };
252
266
  }
253
267
  const conflictBlocker = (row: T.PrSnapshot): T.MergeBlocker | null =>
254
- row.kind === "open" &&
255
- (row.facts.mergeable === "CONFLICTING" ||
256
- row.facts.mergeStateStatus === "DIRTY" ||
257
- row.facts.mergeStateStatus === "CONFLICTING")
268
+ row.kind === "open" && hasMergeConflict(row.facts)
258
269
  ? { kind: "merge-conflicts", pr: row.context, facts: row.facts }
259
270
  : null;
260
271
  function threadBlocker(row: T.PrSnapshot): T.MergeBlocker | null {
@@ -187,7 +187,7 @@ export interface CiUnreported {
187
187
  readonly kind: "ci-unreported";
188
188
  readonly failed: readonly [];
189
189
  readonly pending: readonly [];
190
- readonly hadPreviousPassingCi: false;
190
+ readonly hadPreviousPassingCi: boolean;
191
191
  }
192
192
  export type CiState =
193
193
  | CiFailing