Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(pane): match a human-typed prompt by provenance, not by shape

Jack Rudenko70dc58a4e7ea
diff --git a/packages/cli/src/pane/transcript-follower-human.test.ts b/packages/cli/src/pane/transcript-follower-human.test.ts
new file mode 100644
index 00000000..850c20b8
--- /dev/null
+++ b/packages/cli/src/pane/transcript-follower-human.test.ts
@@ -0,0 +1,207 @@
+/**
+ * The human witness (hook-system architecture §3.2, §7.5, §19 H2): a prompt a human
+ * typed into the interactive launcher's session, matched by PROVENANCE. Every record is
+ * a real capture (phase-2 transcripts, Claude Code 2.1.290 / 2.1.291).
+ *
+ * The negative cases are the ones that bit: the captured background notifications are
+ * non-meta, main-chain user records with plain-text content, so a shape-only witness
+ * matched them and a re-wake read as a new human turn.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { type Rec, transcriptRecords } from "./test-helpers/transcript-fixtures.js";
+import {
+ TranscriptFollower,
+ type Witness,
+ applyRecord,
+ initialFollowerState,
+ isHumanPrompt,
+ lastHumanPromptOffset,
+ openTurnState,
+ turnView,
+} from "./transcript-follower.js";
+
+const TOOLS = transcriptRecords("tools-session");
+const LOCAL = transcriptRecords("local-commands");
+/** 1-based fixture line numbers, as the architecture cites them. */
+const line = (n: number): Rec => TOOLS[n - 1] as Rec;
+
+const HUMAN: Witness = { kind: "human" };
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+function tmpTranscript(records: Rec[]): string {
+ const dir = mkdtempSync(join(tmpdir(), "human-witness-"));
+ dirs.push(dir);
+ const path = join(dir, "s.jsonl");
+ writeFileSync(path, records.map((r) => `${JSON.stringify(r)}\n`).join(""));
+ return path;
+}
+
+/** One human-witness turn at offset 0, fed `records` in order. */
+function feed(records: Rec[]) {
+ const state = initialFollowerState((p) => p);
+ openTurnState(state, { index: 1, offset: 0, witness: HUMAN });
+ let offset = 1;
+ for (const r of records) {
+ applyRecord(state, r, offset);
+ offset += 100;
+ }
+ return turnView(state.turns[0] as never);
+}
+
+describe("isHumanPrompt — provenance, not shape", () => {
+ test("a typed prompt (origin.kind human) matches", () => {
+ const r = line(5);
+ expect(r.origin?.kind).toBe("human");
+ expect(isHumanPrompt(r)).toBe(true);
+ });
+
+ test("the captured task notifications at tools-session.jsonl:54 and :74 never match", () => {
+ for (const n of [54, 74]) {
+ const r = line(n);
+ // the shape a text-only rule would accept: main chain, not meta, plain content
+ expect(r.type).toBe("user");
+ expect(r.isSidechain).toBe(false);
+ expect(r.isMeta).toBeUndefined();
+ expect(typeof r.message.content).toBe("string");
+ expect(isHumanPrompt(r)).toBe(false);
+ }
+ });
+
+ test("a notification WITHOUT its origin field is still refused by its <task-notification> text", () => {
+ const r = structuredClone(line(54));
+ delete r.origin;
+ expect(isHumanPrompt(r)).toBe(false);
+ });
+
+ test("an interrupt marker never matches, even dressed as human", () => {
+ const interrupts = TOOLS.filter(
+ (r) =>
+ r.type === "user" &&
+ typeof r.message?.content !== "string" &&
+ JSON.stringify(r.message?.content).includes("[Request interrupted by user")
+ );
+ expect(interrupts.length).toBeGreaterThan(0);
+ for (const r of interrupts) {
+ expect(isHumanPrompt(r)).toBe(false);
+ expect(isHumanPrompt({ ...r, origin: { kind: "human" } })).toBe(false);
+ }
+ });
+
+ test("a compact summary, an isMeta record and a tool_result never match", () => {
+ const summary = TOOLS.find((r) => r.isCompactSummary);
+ const meta = LOCAL.find((r) => r.type === "user" && r.isMeta);
+ const toolResult = TOOLS.find(
+ (r) =>
+ r.type === "user" &&
+ Array.isArray(r.message?.content) &&
+ r.message.content.some((b: Rec) => b.type === "tool_result")
+ );
+ for (const r of [summary, meta, toolResult]) {
+ expect(r).toBeDefined();
+ expect(isHumanPrompt(r as Rec)).toBe(false);
+ }
+ });
+
+ test("a local command's records (/model, /compact typed line aside) never match", () => {
+ const commands = LOCAL.filter(
+ (r) =>
+ r.type === "user" &&
+ /^\s*<(local-command-caveat|command-name|local-command-stdout)>/.test(
+ typeof r.message?.content === "string" ? r.message.content : ""
+ )
+ );
+ expect(commands.length).toBeGreaterThan(0);
+ for (const r of commands) expect(isHumanPrompt(r)).toBe(false);
+ });
+
+ test("a sidechain (subagent) user record never matches", () => {
+ expect(isHumanPrompt({ ...line(5), isSidechain: true })).toBe(false);
+ });
+
+ test("a prompt with an origin naming anything but human is refused", () => {
+ expect(isHumanPrompt({ ...line(5), origin: { kind: "hook" } })).toBe(false);
+ });
+});
+
+describe("a human-witness turn", () => {
+ test("is accepted by the typed prompt and folds its answer", () => {
+ const answer = line(29);
+ const v = feed([line(5), answer, line(30)]);
+ expect(v.acceptedAt).toBe(line(5).timestamp);
+ expect(v.lastAssistant).not.toBeNull();
+ expect(v.unwitnessedChatOffset).toBeNull();
+ });
+
+ test("a notification and the model's reply to it do NOT open it: they are recorded as unwitnessed chat", () => {
+ const notification = line(54);
+ const reply = line(29);
+ const v = feed([notification, reply]);
+ expect(v.acceptedAt).toBeNull();
+ expect(v.lastAssistant).toBeNull();
+ // the offset of the notification: the first record of the re-wake
+ expect(v.unwitnessedChatOffset).toBe(1);
+ });
+
+ test("an assistant record alone (a continuation with no prompt) is unwitnessed chat", () => {
+ const v = feed([line(29)]);
+ expect(v.acceptedAt).toBeNull();
+ expect(v.unwitnessedChatOffset).toBe(1);
+ });
+
+ test("state records before the prompt are not chat", () => {
+ const v = feed([line(1), line(2), line(5)]);
+ expect(v.acceptedAt).not.toBeNull();
+ expect(v.unwitnessedChatOffset).toBeNull();
+ });
+});
+
+describe("TranscriptFollower.rewindTo and lastHumanPromptOffset", () => {
+ test("rewindTo re-reads a turn from its own offset", () => {
+ const path = tmpTranscript([line(5), line(29), line(30)]);
+ const f = new TranscriptFollower(path, join(path, "..", "subagents"));
+ f.openTurn({ index: 1, offset: 0, witness: HUMAN });
+ f.poll();
+ expect(f.view().current?.acceptedAt).not.toBeNull();
+ // the next turn opens at the end, and a notification + reply arrive
+ f.openTurn({ index: 2, offset: f.size(), witness: HUMAN });
+ appendFileSync(path, `${JSON.stringify(line(54))}\n${JSON.stringify(line(29))}\n`);
+ f.poll();
+ expect(f.view().current?.acceptedAt).toBeNull();
+ expect(f.view().current?.unwitnessedChatOffset).not.toBeNull();
+ // re-open turn 1: its prompt, its first answer AND the continuation are its records
+ f.rewindTo({ index: 1, offset: 0, witness: HUMAN });
+ const v = f.view().current;
+ expect(v?.index).toBe(1);
+ expect(v?.acceptedAt).toBe(line(5).timestamp);
+ expect(v?.wakingAfterLast).toBe(false);
+ expect(v?.assistantText.length).toBe(2);
+ });
+
+ test("lastHumanPromptOffset finds the line of the last typed prompt, skipping notifications", () => {
+ const records = [line(1), line(5), line(29), line(54), line(29)];
+ const path = tmpTranscript(records);
+ const lengths = records.map((r) => Buffer.byteLength(`${JSON.stringify(r)}\n`));
+ expect(lastHumanPromptOffset(path)).toBe((lengths[0] as number) + 0);
+ const second: Rec = { ...line(5), message: { ...line(5).message, content: "second prompt" } };
+ appendFileSync(path, `${JSON.stringify(second)}\n`);
+ const total = lengths.reduce((a, b) => a + b, 0);
+ expect(lastHumanPromptOffset(path)).toBe(total);
+ // a turn opened there is accepted by that prompt alone
+ const f = new TranscriptFollower(path, join(path, "..", "subagents"));
+ f.rewindTo({ index: 1, offset: total, witness: HUMAN });
+ expect(f.view().current?.acceptedAt).toBe(second.timestamp);
+ });
+
+ test("lastHumanPromptOffset is null for a transcript with no human prompt, and for none at all", () => {
+ expect(lastHumanPromptOffset(tmpTranscript([line(1), line(54)]))).toBeNull();
+ expect(lastHumanPromptOffset(join(tmpdir(), "no-such-transcript.jsonl"))).toBeNull();
+ });
+});
diff --git a/packages/cli/src/pane/transcript-follower.ts b/packages/cli/src/pane/transcript-follower.ts
index cfd77f2d..2e5de3eb 100644
--- a/packages/cli/src/pane/transcript-follower.ts
+++ b/packages/cli/src/pane/transcript-follower.ts
@@ -45,7 +45,12 @@ import { RECENT_STEP_LIMIT, stepOf } from "./slot-steps.js";
export type Witness =
| { kind: "text"; text: string } // typed plain line or the file-reference instruction (exact)
/** slash command: its `<command-name>` record, or the plain user record of the typed `line` */
- | { kind: "command"; name: string; line?: string };
+ | { kind: "command"; name: string; line?: string }
+ /**
+ * A prompt a HUMAN typed (the interactive driver, hook-system §7.5): matched by
+ * provenance, never by text. See `isHumanPrompt`.
+ */
+ | { kind: "human" };
export interface TurnDelivery {
/** absolute path of the turn file the child must Read */
@@ -91,6 +96,13 @@ export interface TurnView {
localCommandOutput: string | null;
/** the last RECENT_STEP_LIMIT steps of this turn, oldest first (SlotRow.recent); [] before the first */
recent: SlotStep[];
+ /**
+ * Before the witness: the offset of the first main-chain record that shows the model
+ * working without any prompt of this turn (an assistant record, or a task notification
+ * waking it). The interactive driver reads it as a re-wake of the turn it settled
+ * (D23); panes never open a turn ahead of their own delivery and ignore it.
+ */
+ unwitnessedChatOffset: number | null;
}
export interface SessionFacts {
@@ -151,6 +163,7 @@ interface TurnState {
localOutput: { text: string; offset: number } | null;
/** at most RECENT_STEP_LIMIT, oldest dropped first */
steps: SlotStep[];
+ unwitnessedChat: number | null;
}
export interface FollowerState {
@@ -254,7 +267,30 @@ function isLocalCommandSystem(r: Rec): boolean {
return r.type === "system" && r.subtype === "local_command" && !r.isSidechain;
}
+const INTERRUPT_PREFIX = "[Request interrupted by user";
+
+/**
+ * A prompt a human typed, by PROVENANCE (hook-system §3.2, §7.5): a main-chain user
+ * record that is not `isMeta`, carries no `tool_result`, and is none of the records
+ * Claude Code writes on its own — a task notification, a local command's records, an
+ * interrupt marker, a compact summary. When the record carries `origin` (2.1.290+ always
+ * does for typed prompts), `origin.kind` must be `"human"`. A background notification
+ * (`origin.kind: "task-notification"`) therefore never reads as a human turn, so a D23
+ * re-wake stays the turn it woke.
+ */
+export function isHumanPrompt(record: Record<string, unknown>): boolean {
+ const r = record as Rec;
+ if (!isMainUser(r) || r.isMeta || hasToolResult(r) || r.isCompactSummary) return false;
+ if (isTaskNotification(r)) return false;
+ const text = userText(r);
+ if (!text.trim() || isLocalCommandText(text) || text.startsWith(INTERRUPT_PREFIX)) return false;
+ const origin = r.origin;
+ if (origin !== undefined && origin !== null) return origin?.kind === "human";
+ return true;
+}
+
function matchesWitness(r: Rec, w: Witness): boolean {
+ if (w.kind === "human") return isHumanPrompt(r);
// Some local commands are written as system records, not user records (captured:
// 2.1.291 `/color yellow` → two `system/local_command` records).
if (w.kind === "command" && isLocalCommandSystem(r))
@@ -497,7 +533,7 @@ function applyUser(t: TurnState, r: Rec, offset: number): void {
applyLocalCommandRecord(t, text, offset);
return;
}
- if (text.startsWith("[Request interrupted by user")) {
+ if (text.startsWith(INTERRUPT_PREFIX)) {
t.interrupt = { forToolUse: text.includes("for tool use") };
t.pending.clear();
t.pendingInput.clear();
@@ -546,6 +582,8 @@ export function applyRecord(
if (t.acceptedAt === null) {
acceptIfWitness(t, r, offset);
+ if (t.acceptedAt === null && t.unwitnessedChat === null && wakesModel(r))
+ t.unwitnessedChat = offset;
return state;
}
@@ -560,6 +598,12 @@ export function applyRecord(
return state;
}
+/** A main-chain record that shows the model working with no prompt: its reply, or a notification. */
+function wakesModel(r: Rec): boolean {
+ if (r.type === "assistant") return true;
+ return isMainUser(r) && !hasToolResult(r) && isTaskNotification(r);
+}
+
function applyTurnDuration(state: FollowerState, t: TurnState, r: Rec): void {
const la = t.lastAssistant;
if (!la || t.waking) return;
@@ -622,6 +666,7 @@ export function openTurnState(
lastChatOffset: null,
localOutput: null,
steps: [],
+ unwitnessedChat: null,
});
return state;
}
@@ -676,6 +721,7 @@ export function turnView(t: TurnState): TurnView {
lastChatOffset: t.lastChatOffset,
localCommandOutput: t.localOutput?.text ?? null,
recent: [...t.steps],
+ unwitnessedChatOffset: t.unwitnessedChat,
};
}
@@ -691,6 +737,12 @@ export class Tail {
private rest: Buffer = Buffer.alloc(0);
constructor(readonly path: string) {}
+ /** Read again from byte `offset` (a line start): the next `read()` returns every line from there. */
+ seek(offset: number): void {
+ this.offset = Math.max(0, offset);
+ this.rest = Buffer.alloc(0);
+ }
+
/** Read appended bytes; return complete lines with the byte offset each starts at. */
read(): Array<{ offset: number; line: string }> {
let fd: number;
@@ -799,6 +851,23 @@ export class TranscriptFollower {
openTurnState(this.state, t);
}
+ /**
+ * Re-open turn `t` from its own offset and fold its records again. The interactive
+ * driver does this on a re-wake (D23): it had opened the NEXT turn after the settle,
+ * so the continuation's records were read into a turn that never accepted them. Usage,
+ * tool ids and assistant ids are keyed, so folding a record twice counts it once.
+ */
+ rewindTo(t: {
+ index: number;
+ offset: number;
+ witness: Witness;
+ delivery?: TurnDelivery | null;
+ }): void {
+ this.main.seek(t.offset);
+ openTurnState(this.state, t);
+ this.poll();
+ }
+
markSettled(): void {
this.settled++;
}
@@ -838,6 +907,24 @@ export class TranscriptFollower {
}
}
+/**
+ * The byte offset of the line holding the LAST human prompt in a transcript, or null
+ * when it holds none. The interactive driver opens a turn there when it learns a session
+ * id from a proxy request rather than minting it (`--resume`, `--continue`,
+ * `--fork-session`, `/clear`): Claude Code writes the prompt before it sends the
+ * request that names the session, so the prompt is already on disk and is the turn's
+ * witness.
+ */
+export function lastHumanPromptOffset(path: string): number | null {
+ const tail = new Tail(path);
+ let found: number | null = null;
+ for (const { offset, line } of tail.read()) {
+ const rec = parse(line);
+ if (rec && isHumanPrompt(rec)) found = offset;
+ }
+ return found;
+}
+
function fileSize(p: string): number {
try {
return statSync(p).size;