From 5cb30c8e7ab1edb327d12485bdc609ef5878a16f Mon Sep 17 00:00:00 2001 From: pelikhan Date: Sun, 11 Oct 2026 09:10:15 -0700 Subject: [PATCH 1/2] fix: unify nested caller scopes and progress evidence Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/patch-unified-caller-scopes.md | 5 ++ actions/setup/js/agent_session.cjs | 22 ++++--- actions/setup/js/agent_session.test.cjs | 64 +++++++++++++++++++ actions/setup/js/log_parser_format.cjs | 6 +- actions/setup/js/subagent_session_render.cjs | 4 +- actions/setup/js/types/unified_session.d.ts | 3 + actions/setup/js/unified_session_payload.cjs | 3 + .../setup/js/unified_session_payload.test.cjs | 15 +++++ actions/setup/js/unified_session_render.cjs | 9 ++- .../schemas/unified-session.schema.json | 3 + .../unified-agent-session-specification.md | 9 ++- 11 files changed, 126 insertions(+), 17 deletions(-) create mode 100644 .changeset/patch-unified-caller-scopes.md diff --git a/.changeset/patch-unified-caller-scopes.md b/.changeset/patch-unified-caller-scopes.md new file mode 100644 index 00000000000..b21badfa72a --- /dev/null +++ b/.changeset/patch-unified-caller-scopes.md @@ -0,0 +1,5 @@ +--- +"gh-aw": patch +--- + +Separate agentId-only child conversations, model selection, and accounting from parent sessions, retain background task correlation and errors in unified tool updates, and preserve observed assistant reasoning alongside provider refusals. diff --git a/actions/setup/js/agent_session.cjs b/actions/setup/js/agent_session.cjs index 30ef044f0e6..6ab4bdea868 100644 --- a/actions/setup/js/agent_session.cjs +++ b/actions/setup/js/agent_session.cjs @@ -53,7 +53,13 @@ function sessionContext(event) { /** @param {Array} events @returns {boolean} */ function isSingleNestedSession(events) { - return events.length > 0 && events.every(event => !!sessionContext(event).parentToolUseId) && new Set(events.map(sessionScopeKey)).size === 1; + return events.length > 0 && events.every(isNestedSessionEvent) && new Set(events.map(sessionScopeKey)).size === 1; +} + +/** @param {any} event @returns {boolean} */ +function isNestedSessionEvent(event) { + const { parentToolUseId, agentId } = sessionContext(event); + return !!parentToolUseId || agentId !== undefined; } /** @param {any} event @returns {string} */ @@ -189,12 +195,12 @@ function normalizeAgentSession(entries, { sourceEngine } = {}) { const message = choice.message ?? choice.delta; const streamKey = JSON.stringify([entry.id ?? entry.request_id ?? entry.requestId ?? "chat", choice.index ?? choiceIndex]); if (streaming && typeof message?.content === "string") chatStreamText.set(streamKey, (chatStreamText.get(streamKey) ?? "") + message.content); + if (!streaming && message && (message.role === undefined || message.role === "assistant") && typeof message.reasoning_text === "string") emit("assistant.reasoning", { content: message.reasoning_text }); const refusal = getMessageRefusal(message ?? {}, choice.finish_reason); if (refusal) { if (streaming && refusal.reason === "content_filter" && chatStreamText.has(streamKey)) refusal.content = chatStreamText.get(streamKey); emit("assistant.refusal", refusal, { choiceIndex: choice.index ?? choiceIndex }); } else if (!streaming && message && (message.role === undefined || message.role === "assistant")) { - if (typeof message.reasoning_text === "string") emit("assistant.reasoning", { content: message.reasoning_text }); if (typeof message.content === "string") emit("assistant.message", { content: message.content }, { choiceIndex: choice.index ?? choiceIndex }); } for (const tool of Array.isArray(message?.tool_calls) ? message.tool_calls : []) { @@ -369,7 +375,7 @@ function selectSessionResult(events, { includeNested = false } = {}) { const claudeSessions = new Map(); for (const event of normalized) { const context = sessionContext(event); - if (event.type !== "session.result" || event.data.sourceEngine !== "claude" || (!includeNested && context.parentToolUseId) || typeof context.sessionId !== "string") continue; + if (event.type !== "session.result" || event.data.sourceEngine !== "claude" || (!includeNested && isNestedSessionEvent(event)) || typeof context.sessionId !== "string") continue; const key = sessionScopeKey(event); claudeSessions.set(key, [...(claudeSessions.get(key) ?? []), event]); } @@ -388,7 +394,7 @@ function selectSessionResult(events, { includeNested = false } = {}) { } for (const event of normalized) { const context = sessionContext(event); - if (event.type !== "session.result" || event.data.sourceEngine !== "claude" || (!includeNested && context.parentToolUseId) || typeof context.sessionId === "string") continue; + if (event.type !== "session.result" || event.data.sourceEngine !== "claude" || (!includeNested && isNestedSessionEvent(event)) || typeof context.sessionId === "string") continue; // Unassigned diagnostics are valid evidence, but their usage may overlap a named session. for (const key of ["errors", "permissionDenials"]) { if (Array.isArray(event.data[key])) aggregate[key] = [...(aggregate[key] ?? []), ...structuredClone(event.data[key])]; @@ -401,8 +407,7 @@ function selectSessionResult(events, { includeNested = false } = {}) { let result; for (const event of normalized) { if (event.type !== "session.result") continue; - const context = sessionContext(event); - if (!includeNested && (context.parentToolUseId || context.agentId !== undefined)) continue; + if (!includeNested && isNestedSessionEvent(event)) continue; result ??= {}; const data = event.data; for (const [key, value] of Object.entries(data)) { @@ -439,7 +444,7 @@ function projectSessionInitialization(events, { includeNested = false } = {}) { let data; for (const event of normalizeAgentSession(events)) { if (event.type !== "session.init" && event.type !== "session.start") continue; - if (!includeNested && sessionContext(event).parentToolUseId) continue; + if (!includeNested && isNestedSessionEvent(event)) continue; data ??= {}; for (const [key, value] of Object.entries(event.data)) { if (value !== undefined) data = { ...data, [key]: structuredClone(value) }; @@ -571,7 +576,7 @@ function sessionTokenTotal(usage) { function observedSessionModel(events, { includeNested = false } = {}) { let model; for (const event of events) { - if (!includeNested && sessionContext(event).parentToolUseId) continue; + if (!includeNested && isNestedSessionEvent(event)) continue; const value = event?.type === "system" && event.subtype === "init" ? event.model @@ -587,6 +592,7 @@ module.exports = { sessionContext, sessionScopeKey, isSingleNestedSession, + isNestedSessionEvent, isSessionEvent, isTokenCount, isMetric, diff --git a/actions/setup/js/agent_session.test.cjs b/actions/setup/js/agent_session.test.cjs index 805e0109432..8ba36c20dda 100644 --- a/actions/setup/js/agent_session.test.cjs +++ b/actions/setup/js/agent_session.test.cjs @@ -10,6 +10,10 @@ import { sessionToolSuccess, sessionTokenTotal, sessionContext, + isNestedSessionEvent, + isSingleNestedSession, + projectSessionInitialization, + observedSessionModel, } from "./agent_session.cjs"; import { scopedAgentSessions } from "./unified_session_render.cjs"; import { @@ -62,6 +66,66 @@ const canonical = freeze([ ]); describe("Unified Agent Session 1.0.0 conformance", () => { + it("retains observed assistant reasoning alongside provider refusals", () => { + const source = freeze({ + object: "chat.completion", + id: "response", + choices: [{ message: { role: "assistant", reasoning_text: "observed reasoning\n", refusal: "declined\n" } }, { message: { role: "user", reasoning_text: "not assistant reasoning", content: "prompt" } }], + }); + const events = normalizeAgentSession([source]); + expect(events.map(event => event.type)).toEqual(["assistant.reasoning", "assistant.refusal"]); + expect(events[0].data.content).toBe("observed reasoning\n"); + expect(events[1].data).toMatchObject({ reason: "refusal", content: "declined\n" }); + expect(events.every(event => event.id === "response")).toBe(true); + expect(normalizeAgentSession(events)).toEqual(events); + }); + + it("separates agentId-only child evidence without inventing a parent tool ID", () => { + const child = [ + { type: "session.init", data: { sourceEngine: "pi", agentId: "legacy:pi:worker:1", model: "child-model" } }, + { type: "assistant.message", agentId: "legacy:pi:worker:1", data: { content: "child answer" } }, + { type: "session.result", data: { agentId: "legacy:pi:worker:1", usage: { input_tokens: 99 } } }, + ]; + const root = [ + { type: "session.init", data: { sourceEngine: "pi", model: "root-model" } }, + { type: "assistant.message", data: { content: "root answer" } }, + { type: "session.result", data: { usage: { input_tokens: 2 } } }, + ]; + const events = [...root, ...child]; + expect(isSingleNestedSession(child)).toBe(true); + expect(isSingleNestedSession(events)).toBe(false); + expect(isNestedSessionEvent({ type: "subagent.started", agentId: "target", data: {} })).toBe(false); + expect(sessionContext(child[1])).toEqual({ agentId: "legacy:pi:worker:1" }); + expect(projectSessionResult(events).usage.input_tokens).toBe(2); + expect(projectSessionInitialization(events).model).toBe("root-model"); + expect(observedSessionModel(events)).toBe("root-model"); + expect(observedSessionModel(child, { includeNested: true })).toBe("child-model"); + const groups = scopedAgentSessions(events); + expect(groups).toHaveLength(2); + expect(groups[0].events).toEqual(root); + expect(groups[1].events).toEqual(child); + expect(groups[1].label).toContain("agentId=legacy:pi:worker:1"); + expect(groups[1].label).not.toContain("parentToolUseId"); + for (const render of [generatePlainTextSummary, generateCopilotCliStyleSummary]) { + const output = render(events); + expect(output).toContain("agentId=legacy:pi:worker:1"); + expect(output.indexOf("root answer")).toBeLessThan(output.indexOf("agentId=legacy:pi:worker:1")); + expect(output.indexOf("child answer")).toBeGreaterThan(output.indexOf("agentId=legacy:pi:worker:1")); + expect(render(child)).toContain("child answer"); + expect(render(child)).toContain("99"); + } + }); + + it("does not aggregate agentId-only Claude child snapshots into root sessions", () => { + const events = [ + { type: "session.result", data: { sourceEngine: "claude", sessionId: "first", usage: { input_tokens: 2 } } }, + { type: "session.result", data: { sourceEngine: "claude", sessionId: "second", usage: { input_tokens: 3 } } }, + { type: "session.result", data: { sourceEngine: "claude", sessionId: "child", agentId: "worker", usage: { input_tokens: 99 }, errors: ["child-only"] } }, + ]; + expect(projectSessionResult(events).usage.input_tokens).toBe(5); + expect(projectSessionResult(events).errors).toBeUndefined(); + }); + it("keeps Pi parent tool-call relationships in the root session group", () => { const events = [ { type: "session.init", data: { sourceEngine: "pi", sessionId: "pi-root" } }, diff --git a/actions/setup/js/log_parser_format.cjs b/actions/setup/js/log_parser_format.cjs index 7039ee79c01..f9689db99ea 100644 --- a/actions/setup/js/log_parser_format.cjs +++ b/actions/setup/js/log_parser_format.cjs @@ -1,7 +1,7 @@ // @ts-check const { buildStepSummaryDetailsSection } = require("./log_parser_step_summary_builder.cjs"); -const { normalizeSessionUsage, sessionTokenTotal, sessionOutputText, observedSessionModel, projectSessionResult, sessionContext, isSingleNestedSession } = require("./agent_session.cjs"); +const { normalizeSessionUsage, sessionTokenTotal, sessionOutputText, observedSessionModel, projectSessionResult, isNestedSessionEvent, isSingleNestedSession } = require("./agent_session.cjs"); const { collapseStreamedMessages, escapeSummaryText, renderInitializationLines, toolOutcome, boundSummaryLines } = require("./agent_session_render.cjs"); const { isUnifiedSessionTrace, publicationAgentSessions, renderUnifiedSession } = require("./unified_session_render.cjs"); const { renderSubagentSummary } = require("./subagent_session_render.cjs"); @@ -190,7 +190,7 @@ function createLogParserFormatters(deps) { } const groups = publicationAgentSessions(logEntries); - if (groups.length > 1 && groups.some(group => group.events.some(event => sessionContext(event).parentToolUseId))) { + if (groups.length > 1 && groups.some(group => group.events.some(isNestedSessionEvent))) { const commandSummary = []; for (const group of groups) { const section = generateConversationMarkdown(group.events, { ...options, summaryTracker: createSummaryTracker() }); @@ -672,7 +672,7 @@ function createLogParserFormatters(deps) { function generateSummaryLines(logEntries, includeStatistics = true) { const groups = publicationAgentSessions(logEntries); - if (groups.length > 1 && groups.some(group => group.events.some(event => sessionContext(event).parentToolUseId))) { + if (groups.length > 1 && groups.some(group => group.events.some(isNestedSessionEvent))) { return groups.flatMap(group => [`Agent conversation: ${group.label.replace(/[\r\n]/g, " ")}`, "", ...generateSummaryLines(group.events, includeStatistics), ""]); } const renderEntries = normalizeEntriesForRendering(logEntries); diff --git a/actions/setup/js/subagent_session_render.cjs b/actions/setup/js/subagent_session_render.cjs index 90eede0fc5a..d7a8cc33028 100644 --- a/actions/setup/js/subagent_session_render.cjs +++ b/actions/setup/js/subagent_session_render.cjs @@ -1,6 +1,6 @@ // @ts-check -const { isMetric, isTokenCount, sessionOutputText, sessionContext } = require("./agent_session.cjs"); +const { isMetric, isTokenCount, sessionOutputText, isNestedSessionEvent } = require("./agent_session.cjs"); const { collectArtifactSecretValues, redactManifestValue } = require("./safe_output_manifest.cjs"); const { ERR_VALIDATION } = require("./error_codes.cjs"); @@ -24,7 +24,7 @@ function renderSubagentSummary(events) { let sessionId; for (const event of redacted) { const data = event.data ?? {}; - const nested = !!sessionContext(event).parentToolUseId; + const nested = isNestedSessionEvent(event); if (["session.start", "session.init"].includes(event.type) && !event.agentId && !nested) { if ((data.sessionId !== undefined && data.sessionId !== sessionId) || (event.type === "session.init" && data.sessionId === undefined && data.sourceEngine === "copilot")) { agents.clear(); diff --git a/actions/setup/js/types/unified_session.d.ts b/actions/setup/js/types/unified_session.d.ts index 754d7372eda..36073415e97 100644 --- a/actions/setup/js/types/unified_session.d.ts +++ b/actions/setup/js/types/unified_session.d.ts @@ -427,6 +427,9 @@ export interface UnifiedSessionEventDataMap { durationMs?: JsonValue; status?: JsonValue; command?: JsonValue; + taskId?: string; + taskType?: string; + error?: JsonValue; } & UnifiedSessionContextData; "tool.execution_complete": Pick< ToolExecutionCompleteData, diff --git a/actions/setup/js/unified_session_payload.cjs b/actions/setup/js/unified_session_payload.cjs index a44628af8f6..bc3add58467 100644 --- a/actions/setup/js/unified_session_payload.cjs +++ b/actions/setup/js/unified_session_payload.cjs @@ -190,6 +190,9 @@ const EVENT_FIELDS = { durationMs: ["durationMs"], status: ["status"], command: ["command"], + taskId: ["taskId", "task_id"], + taskType: ["taskType", "task_type"], + error: ["error"], }, "tool.execution_complete": { ...TOOL_FIELDS, diff --git a/actions/setup/js/unified_session_payload.test.cjs b/actions/setup/js/unified_session_payload.test.cjs index 059b5ba4aec..5c177853e7d 100644 --- a/actions/setup/js/unified_session_payload.test.cjs +++ b/actions/setup/js/unified_session_payload.test.cjs @@ -14,6 +14,21 @@ import { dynamicWorkflow } from "./fixtures/claude_dynamic_workflow.cjs"; import { DYNAMIC_WORKFLOW_EVENT_TYPES } from "./dynamic_workflow_session.cjs"; describe("essential unified session payloads", () => { + it("retains background task correlation and observed errors on tool updates", () => { + const source = { + type: "tool.execution_update", + data: { toolCallId: "shell", task_id: "background", task_type: "local_bash", status: "failed", output: "observed progress\n", error: "observed failure", nativeEnvelope: { omitted: true } }, + }; + const original = structuredClone(source); + const [event] = mergeSessionSources([{ component: "agent", phase: "agent", path: "tasks.jsonl", events: [source] }]); + expect(event.data).toEqual({ toolCallId: "shell", taskId: "background", taskType: "local_bash", status: "failed", output: "observed progress\n", error: "observed failure" }); + expect(event.data).not.toHaveProperty("success"); + expect(normalizeUnifiedSessionEvent(event).data).toEqual(event.data); + const validate = createSessionValidator("unified").event; + expect(validate(event), JSON.stringify(validate.errors)).toBe(true); + expect(source).toEqual(original); + }); + it.each([true, false])("retains final model result and BYOK=%s through persisted unified projection", isByok => { const source = { type: "model.call_final_result", diff --git a/actions/setup/js/unified_session_render.cjs b/actions/setup/js/unified_session_render.cjs index 5a370236bd5..2478cb0a476 100644 --- a/actions/setup/js/unified_session_render.cjs +++ b/actions/setup/js/unified_session_render.cjs @@ -1,7 +1,7 @@ // @ts-check const fs = require("fs"); -const { sessionOutputText, sessionContext, sessionScopeKey } = require("./agent_session.cjs"); +const { sessionOutputText, sessionContext, sessionScopeKey, isNestedSessionEvent } = require("./agent_session.cjs"); const { collapseStreamedMessages, boundSummaryLines, escapeSummaryText, redactSessionForPublication } = require("./agent_session_render.cjs"); const { collectArtifactSecretValues, redactManifestValue } = require("./safe_output_manifest.cjs"); const { getErrorMessage } = require("./error_helpers.cjs"); @@ -214,8 +214,11 @@ function scopedAgentSessions(events) { if (source ? source.component !== "agent" : RUNTIME_TYPES.has(event.type)) continue; const context = sessionContext(event); const baseLabel = source ? `${source.phase}/${source.path}` : "agent"; - const label = context.parentToolUseId ? `${baseLabel} sessionId=${context.sessionId ?? "unavailable"} parentToolUseId=${context.parentToolUseId}${context.agentId ? ` agentId=${context.agentId}` : ""}` : baseLabel; - const key = JSON.stringify([source?.phase, source?.path, context.parentToolUseId ? sessionScopeKey(event) : undefined]); + const nested = isNestedSessionEvent(event); + const label = nested + ? `${baseLabel} sessionId=${context.sessionId ?? "unavailable"}${context.parentToolUseId ? ` parentToolUseId=${context.parentToolUseId}` : ""}${context.agentId !== undefined ? ` agentId=${context.agentId}` : ""}` + : baseLabel; + const key = JSON.stringify([source?.phase, source?.path, nested ? sessionScopeKey(event) : undefined]); if (!groups.has(key)) groups.set(key, { label, events: [] }); groups.get(key).events.push(event); } diff --git a/docs/public/schemas/unified-session.schema.json b/docs/public/schemas/unified-session.schema.json index e5d99c2168f..bc523c84dc7 100644 --- a/docs/public/schemas/unified-session.schema.json +++ b/docs/public/schemas/unified-session.schema.json @@ -355,6 +355,9 @@ "durationMs": { "$ref": "#/definitions/JsonValue" }, "status": { "$ref": "#/definitions/JsonValue" }, "command": { "$ref": "#/definitions/JsonValue" }, + "taskId": { "type": "string" }, + "taskType": { "type": "string" }, + "error": { "$ref": "#/definitions/JsonValue" }, "toolCallId": { "type": "string" }, "stepIndex": { "$ref": "#/definitions/SessionCount" }, "toolName": { "type": "string" }, diff --git a/docs/src/content/docs/specs/unified-agent-session-specification.md b/docs/src/content/docs/specs/unified-agent-session-specification.md index b8904c4b66d..85191ad1ee8 100644 --- a/docs/src/content/docs/specs/unified-agent-session-specification.md +++ b/docs/src/content/docs/specs/unified-agent-session-specification.md @@ -237,7 +237,7 @@ opaque because its essential fields are not defined by this specification. | Agent messages and reasoning | Exact `content`, without duplicate text blocks or the original message envelope. | | Agent session errors | Observed diagnostic fields, including `errorType`, `code`, and `statusCode`; absent status codes remain absent, and unrelated native error context is omitted. | | Agent policy refusals | Structured `reason`, exact available `content`, `policyCategory`, `explanation`, and streaming `partial` flag; no duplicated provider envelope. | -| Agent tool lifecycle | Correlation IDs, tool/server names, one `input` or `output` field, command, outcome/error signals, duration, and exit code. | +| Agent tool lifecycle | Correlation IDs, tool/server names, one `input` or `output` field, command, outcome/error signals, duration, and exit code. Background tool updates retain observed `taskId` and `taskType`; progress and task notifications do not imply a tool completion. | | Agent accounting | Turns, duration, cost, observed terminal `status` and `sourceType`, normalized `usage` including reported reasoning tokens, errors, and permission denials. | | Agent execution diagnostics | Unique harness/compiler `categories`, native `errorCodes` and `errorTypes`, and the observed final process `exitCode`; no diagnostic messages or duplicated engine envelopes. | | MCP | Server, direction, RPC/call/request IDs, method, tool name, duration, sizes, status, reason, and error code/message; no RPC arguments, response bodies, or error context. | @@ -1347,6 +1347,13 @@ counts, per-source agent statistics and conversations, and a chronological trace agent-only inputs retain their earlier rendering behavior except that nested conversations are labeled separately. +Caller `agentId` alone identifies a nested conversation when the source does not +provide a parent tool ID, as in Pi subagent streams. Its messages, tool pairing, +model, and accounting remain separate from the parent. A subagent lifecycle +envelope's target `agentId` does not identify the emitting caller. Readers must +not invent parent tool IDs to distinguish these scopes; a view containing only +one nested scope can select that scope's initialization and accounting explicitly. + Actions publishes this view once in a plain-titled `Unified session` disclosure, using a fenced CLI-style transcript like the Claude conversation summary rather than a Markdown table. Gateway diagnostics do not append a second unified event From 46ec702bad48ca6ae666eea62d14bcb53586aab9 Mon Sep 17 00:00:00 2001 From: pelikhan Date: Sun, 11 Oct 2026 09:18:45 -0700 Subject: [PATCH 2/2] fix: normalize Pi traces directly into canonical session events Preserve scoped child observations, native persisted entries, and unknown event content while retaining historical Pi compatibility. Cover current release event additions and the authoritative artifact pipeline. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../pi_agent_core_driver_sample_node.cjs | 2 +- actions/setup/js/fixtures/pi_ci_stream.cjs | 32 ++++- actions/setup/js/parse_pi_log.cjs | 26 +--- actions/setup/js/pi_legacy_session.test.cjs | 2 +- actions/setup/js/pi_session.cjs | 60 +++++++-- actions/setup/js/pi_session.test.cjs | 115 +++++++++++++++++- actions/setup/js/pi_session_pipeline.test.cjs | 78 ++++++++++++ 7 files changed, 282 insertions(+), 33 deletions(-) create mode 100644 actions/setup/js/pi_session_pipeline.test.cjs diff --git a/.github/drivers/pi_agent_core_driver_sample_node.cjs b/.github/drivers/pi_agent_core_driver_sample_node.cjs index a20dc40244e..e1e63c66dd6 100644 --- a/.github/drivers/pi_agent_core_driver_sample_node.cjs +++ b/.github/drivers/pi_agent_core_driver_sample_node.cjs @@ -5,7 +5,7 @@ /** * Self-contained Pi coding-agent SDK driver example. * - * Declare @earendil-works/pi-coding-agent@1.0.0 as a project dependency and + * Declare @earendil-works/pi-coding-agent@1.1.0 as a project dependency and * install it in setup-steps before the agent runs. Select this file with * engine.driver: .github/drivers/pi_agent_core_driver_sample_node.cjs. * diff --git a/actions/setup/js/fixtures/pi_ci_stream.cjs b/actions/setup/js/fixtures/pi_ci_stream.cjs index a58a7ff9019..eb74103c6e6 100644 --- a/actions/setup/js/fixtures/pi_ci_stream.cjs +++ b/actions/setup/js/fixtures/pi_ci_stream.cjs @@ -85,4 +85,34 @@ const failure = [ { type: "agent_settled" }, ]; -module.exports = { success, failure }; +// Shape from Smoke Pi Sub Agents run 37735099783, agent artifact +// 11531640894/pi-streaming.jsonl. Names, IDs, timestamps and content replaced. +// This historical wrapper has no native invocation or parent tool identity. +const childObservations = [ + { type: "gh_aw_subagent_dispatch", agent: "sanitized-reader", requested_model: "gpt-5-mini", resolved_model: "gpt-5-mini" }, + { + type: "gh_aw_subagent_event", + agent: "sanitized-reader", + event: { + type: "message_end", + message: { + role: "assistant", + content: [ + { type: "thinking", thinking: "Sanitized reasoning.", thinkingSignature: "sanitized-signature" }, + { type: "text", text: "Sanitized child answer.", textSignature: "sanitized-signature" }, + ], + api: "openai-responses", + provider: "aw-gateway", + model: "gpt-5-mini", + responseId: "sanitized-child-response", + timestamp: 6, + rawStopReason: "completed", + stopReason: "stop", + thinkingLevel: "minimal", + usage: { input: 3085, output: 136, cacheRead: 0, cacheWrite: 0, reasoning: 64, totalTokens: 3221, cost: { input: 0.00077125, output: 0.000272, cacheRead: 0, cacheWrite: 0, total: 0.00104325 } }, + }, + }, + }, +]; + +module.exports = { success, failure, childObservations }; diff --git a/actions/setup/js/parse_pi_log.cjs b/actions/setup/js/parse_pi_log.cjs index af869c3db7b..c47eeaf7b59 100644 --- a/actions/setup/js/parse_pi_log.cjs +++ b/actions/setup/js/parse_pi_log.cjs @@ -1,16 +1,7 @@ // @ts-check /// -const { - createEngineLogParser, - generateConversationMarkdown, - generateInformationSection, - buildStepSummaryDetailsSection, - formatInitializationSummary, - formatToolUse, - convertLegacyLogEntriesToCopilotEvents, - parseLogEntries, -} = require("./log_parser_shared.cjs"); +const { createEngineLogParser, generateConversationMarkdown, generateInformationSection, buildStepSummaryDetailsSection, formatInitializationSummary, formatToolUse, parseLogEntries } = require("./log_parser_shared.cjs"); const { transformFlatSessionEntries, projectSessionResult, selectSessionResult, reconcileSessionUsage } = require("./agent_session.cjs"); const { transformPiV3Entries, computePiV3Stats, normalizePiObservations } = require("./pi_session.cjs"); @@ -22,12 +13,8 @@ const main = createEngineLogParser({ /** * Parse Pi CLI JSONL streaming log output and format as markdown. - * Pi CLI emits one JSON object per line (JSONL) with typed events: - * - type "init": session initialization with model and session_id - * - type "assistant": agent message content (delta:true for streaming chunks) - * - type "tool_use": tool invocations with tool_name, tool_id, and parameters - * - type "tool_result": tool responses with tool_id, status, and output - * - type "result": final stats with token usage and duration + * Normalize native streaming events and historical flat records directly into + * canonical session events, then render the shared conversation and usage view. * @param {string} logContent - The raw log content to parse * @returns {{markdown: string, logEntries: Array, mcpFailures: Array, maxTurnsHit: boolean}} Parsed log data */ @@ -58,10 +45,8 @@ function parsePiLog(logContent) { // Detect which schema this log uses and transform accordingly so the step summary // renders the conversation and token stats for both. const useV3Schema = isPiV3Schema(rawEntries); - const logEntries = useV3Schema ? transformPiV3Entries(rawEntries) : transformPiEntries(rawEntries); - const stats = useV3Schema ? computePiV3Stats(rawEntries) : null; - const canonicalLogEntries = normalizePiObservations(convertLegacyLogEntriesToCopilotEvents(logEntries, { sourceEngine: "pi" })); + const canonicalLogEntries = transformPiV3Entries(rawEntries); if (stats) { const terminal = [...canonicalLogEntries].reverse().find(event => event.type === "session.result"); const selected = selectSessionResult(canonicalLogEntries); @@ -74,7 +59,7 @@ function parsePiLog(logContent) { }; if (terminal) { Object.assign(terminal.data, data); - if (stats.errors.length || stats.exposedErrors) terminal.data.errors = [...(terminal.data.errors ?? []), ...stats.errors]; + if (stats.errors.length || stats.exposedErrors) terminal.data.errors = [...(Array.isArray(terminal.data.errors) ? terminal.data.errors : []), ...stats.errors]; } else { canonicalLogEntries.push({ type: "session.result", data: { ...data, errors: stats.errors.length || stats.exposedErrors ? stats.errors : undefined } }); } @@ -143,6 +128,7 @@ function isPiV3Schema(rawEntries) { e.type === "message_update" || e.type === "message_start" || e.type === "message_end" || + (e.type === "message" && e.message && typeof e.message.role === "string") || (e.type === "session" && typeof e.version === "number") ) { return true; diff --git a/actions/setup/js/pi_legacy_session.test.cjs b/actions/setup/js/pi_legacy_session.test.cjs index 93a24bf11ef..895b65774e1 100644 --- a/actions/setup/js/pi_legacy_session.test.cjs +++ b/actions/setup/js/pi_legacy_session.test.cjs @@ -180,7 +180,7 @@ describe("historical Pi observations", () => { { type: "pi.subagent_event", data: { agent: "reader", invocation_id: "child", event: { message: { role: "assistant", model: "gpt-5.4-mini", usage: { input: 5, output: 2 } } } } }, { type: "pi.subagent_result", data: { agent: "reader", invocation_id: "child", outcome: "failed", error_code: "SUBAGENT_MODEL_UNAVAILABLE" } }, ]); - expect(events.map(event => event.type)).toEqual(["subagent.started", "subagent.configured", "subagent.request", "subagent.failed"]); + expect(events.map(event => event.type)).toEqual(["subagent.started", "subagent.configured", "subagent.request", "session.info", "subagent.failed"]); expect(events.every(event => event.agentId === "child")).toBe(true); expect(byType(events, "subagent.request")[0].data).toMatchObject({ inputTokens: 5, outputTokens: 2 }); expect(byType(events, "subagent.failed")[0].data).toMatchObject({ errorCode: "SUBAGENT_MODEL_UNAVAILABLE" }); diff --git a/actions/setup/js/pi_session.cjs b/actions/setup/js/pi_session.cjs index 880435ee912..70ed3274b25 100644 --- a/actions/setup/js/pi_session.cjs +++ b/actions/setup/js/pi_session.cjs @@ -137,6 +137,9 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { const events = []; const subagentInvocations = new Map(); const subagentInvocationCounts = new Map(); + const subagentRecords = new Map(); + const subagentEvents = new Map(); + const subagentRequests = new Map(); const legacyCallIds = new Map(); const executionEnds = new Set(records.filter(r => r.type === "tool_execution_end" && r.toolCallId !== undefined).map(r => r.toolCallId)); const calls = new Map(); @@ -202,7 +205,10 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { const value = usage[source] ?? usage[target]; if (Number.isSafeInteger(value) && value >= 0) data[target] = value; } - emit(raw, "subagent.request", data, { agentId: invocationId }); + const key = JSON.stringify([invocationId, messageIdentity(message) ?? message]); + const previous = subagentRequests.get(key); + if (previous) Object.assign(previous.data, data); + else subagentRequests.set(key, emit(raw, "subagent.request", data, { agentId: invocationId })); }; const emitText = (raw, state, kind, index, text, delta, role = "assistant", metadata = {}) => { @@ -301,7 +307,14 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { }; const emitMessage = (raw, message, fallback) => { - if (!message || !["assistant", "user", "toolResult"].includes(message.role)) return; + if (!message || typeof message.role !== "string") return; + if (!["assistant", "user", "toolResult"].includes(message.role)) { + if (!snapshots.some(snapshot => isDeepStrictEqual(snapshot.message, message))) { + snapshots.push({ message: structuredClone(message), state: fallback }); + emit(raw, "session.info", { sourceType: "message_snapshot", role: message.role, content: message }); + } + return; + } if (message.role === "toolResult") { emitCompletion(raw, message); return; @@ -389,7 +402,33 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { emit(raw, "subagent.configured", { invocationId, model: raw.resolved_model ?? raw.resolvedModel }, { agentId: invocationId }); } } else if (raw.type === "gh_aw_subagent_event") { - emitSubagentRequest(raw, invocationIdentity(raw, false)); + const invocationId = invocationIdentity(raw, false); + emitSubagentRequest(raw, invocationId); + if (raw.event && typeof raw.event === "object" && !Array.isArray(raw.event) && typeof raw.event.type === "string") { + const childRecords = subagentRecords.get(invocationId) ?? []; + childRecords.push({ + ...structuredClone(raw.event), + ...(raw.provenance !== undefined ? { provenance: structuredClone(raw.provenance) } : {}), + }); + subagentRecords.set(invocationId, childRecords); + const previous = subagentEvents.get(invocationId) ?? []; + // Replay only this child's observations so repeated snapshots reconcile + // without sharing tool/message identities with the parent or other children. + const childEvents = transformPiV3Entries(childRecords).map(event => ({ + ...event, + agentId: event.agentId ?? invocationId, + data: { ...event.data, agentId: event.data.agentId ?? invocationId }, + })); + for (let index = 0; index < previous.length; index++) { + const position = events.indexOf(previous[index]); + if (position >= 0) { + if (index < childEvents.length) events[position] = childEvents[index]; + else events.splice(position, 1); + } + } + events.push(...childEvents.slice(previous.length)); + subagentEvents.set(invocationId, childEvents); + } else emit(raw, "session.info", { sourceType: raw.type, content: raw.event }, { agentId: invocationId }); } else if (raw.type === "gh_aw_subagent_result") { const invocationId = invocationIdentity(raw, false); const failed = raw.outcome !== "completed"; @@ -431,8 +470,9 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { if (call) call.data.argumentText = (call.data.argumentText ?? "") + update.delta; else emit(raw, "tool.execution_update", { input: update.delta, delta: true, partial: true, contentIndex: update.contentIndex }); } else if (update?.type === "done" || update?.type === "error") emitMessage(raw, update.message ?? update.error, assistantState); - else if (update && !["start", "text_start", "thinking_start"].includes(update.type)) emit(raw, "assistant.message_update", { ...update, usage: raw.usage }); - } else if (raw.type === "message_end") emitMessage(raw, raw.message, raw.message?.role === "assistant" ? assistantState : activeState); + else if (update && !["start", "text_start", "thinking_start"].includes(update.type)) emit(raw, "assistant.message_update", { ...update, content: update, usage: raw.usage }); + } else if (raw.type === "message" && raw.message) emitMessage(raw, raw.message, newMessageState()); + else if (raw.type === "message_end") emitMessage(raw, raw.message, raw.message?.role === "assistant" ? assistantState : activeState); else if (raw.type === "turn_end") { emitMessage(raw, raw.message, assistantState); for (const result of raw.toolResults ?? []) emitCompletion(raw, result); @@ -470,7 +510,11 @@ function transformPiV3Entries(records, mapLegacyEvent = event => event) { emitMessage(raw, message, index >= 0 ? snapshots[index].state : partialAssistant && position === lastAssistant ? assistantState : newMessageState()); } } else if (raw.type === "error") emit(raw, "session.error", { error: raw.error ?? raw.message }); - else events.push(...normalizeAgentSession(transformFlatSessionEntries([raw]), { sourceEngine: "pi" })); + else { + const flat = normalizeAgentSession(transformFlatSessionEntries([raw]), { sourceEngine: "pi" }); + if (flat.length) events.push(...flat); + else if (typeof raw.type === "string" && raw.type !== "") emit(raw, "session.info", { sourceType: raw.type, content: raw }); + } } return events; } @@ -566,10 +610,12 @@ function computePiV3Stats(records) { lastWasMessageUpdate = false; } else if (raw.type === "message_update" && ["done", "error"].includes(raw.assistantMessageEvent?.type)) { addMessage(raw, raw.assistantMessageEvent.message ?? raw.assistantMessageEvent.error); - } else if (raw.type === "message_end" || raw.type === "turn_end") { + } else if (raw.type === "message_end" || raw.type === "turn_end" || (raw.type === "message" && raw.message)) { addMessage(raw, raw.message); if (raw.message?.role === "toolResult") addAuxiliaryUsage(`tool:${raw.message.toolCallId}`, raw.message.usage); for (const result of raw.toolResults ?? []) addAuxiliaryUsage(`tool:${result.toolCallId}`, result.usage); + } else if (["usage", "compaction", "branch_summary"].includes(raw.type)) { + addAuxiliaryUsage(`${raw.type}:${raw.id}`, raw.usage); } else if (raw.type === "compaction_end") { addAuxiliaryUsage(`compaction:${compactionCount++}`, raw.result?.usage); if (raw.errorMessage) errors.push(raw.errorMessage); diff --git a/actions/setup/js/pi_session.test.cjs b/actions/setup/js/pi_session.test.cjs index f23a8f83d5e..684e66a2237 100644 --- a/actions/setup/js/pi_session.test.cjs +++ b/actions/setup/js/pi_session.test.cjs @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest"; import { parsePiLog } from "./parse_pi_log.cjs"; import { transformPiV3Entries, computePiV3Stats } from "./pi_session.cjs"; -import { success, failure } from "./fixtures/pi_ci_stream.cjs"; +import { success, failure, childObservations } from "./fixtures/pi_ci_stream.cjs"; import { normalizeAgentSession, selectSessionResult, sessionTokenTotal } from "./agent_session.cjs"; import { mergeSessionSources } from "./unified_session.cjs"; import { normalizeUnifiedSessionEvent } from "./unified_session_payload.cjs"; @@ -11,6 +11,110 @@ const parse = records => parsePiLog(records.map(record => JSON.stringify(record) const byType = (events, type) => events.filter(event => event.type === type); describe("Pi CI stream regressions", () => { + it("retains sampled child text and reasoning in their evidenced dispatch scope through unified projection", () => { + const original = structuredClone(childObservations); + const records = [...success, ...childObservations]; + const events = parse(records).logEntries; + const scope = "legacy:pi:sanitized-reader:1"; + const unified = mergeSessionSources([{ component: "agent", phase: "agent", path: "pi-streaming.jsonl", events }]); + expect(byType(unified, "assistant.reasoning")).toMatchObject([{ agentId: scope, data: { content: "Sanitized reasoning.", agentId: scope } }]); + expect(byType(unified, "assistant.message").find(event => event.agentId === scope)).toMatchObject({ + data: { content: "Sanitized child answer.", model: "gpt-5-mini", messageId: "sanitized-child-response", agentId: scope }, + }); + expect(byType(unified, "subagent.request")).toMatchObject([{ agentId: scope, data: { inputTokens: 3085, outputTokens: 136, cacheReadTokens: 0, cacheWriteTokens: 0 } }]); + expect(selectSessionResult(events)).toMatchObject({ numTurns: 2, usage: { input_tokens: 6427, output_tokens: 145 } }); + expect(byType(unified, "subagent.completed")).toEqual([]); + expect(byType(unified, "subagent.failed")).toEqual([]); + const validate = createSessionValidator("unified").event; + for (const event of unified) expect(validate(event), JSON.stringify(validate.errors)).toBe(true); + expect(childObservations).toEqual(original); + }); + + it("reconciles synthetic child streams without conflating parent tool IDs or repeated snapshots", () => { + const message = { role: "assistant", id: "child-answer", model: "fixture-model", content: [{ type: "text", text: "Child answer" }] }; + const wrap = event => ({ type: "gh_aw_subagent_event", agent: "reader", invocation_id: "child", event, provenance: { path: "pi-streaming.jsonl", index: 7 } }); + const records = [ + { type: "gh_aw_subagent_dispatch", agent: "reader", invocation_id: "child" }, + wrap({ type: "message_update", assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "Child " } }), + { type: "tool_execution_start", toolCallId: "same-id", toolName: "parent-tool", args: {} }, + wrap({ type: "tool_execution_start", toolCallId: "same-id", toolName: "child-tool", args: { child: true } }), + wrap({ type: "tool_execution_end", toolCallId: "same-id", result: { error: "Child failure" } }), + wrap({ type: "message_end", message }), + wrap({ type: "turn_end", message }), + wrap({ type: "agent_end", messages: [message] }), + wrap({ type: "error", message: "Child error" }), + ]; + const events = transformPiV3Entries(records); + expect(byType(events, "tool.execution_start").map(event => [event.agentId, event.data.toolName])).toEqual([ + [undefined, "parent-tool"], + ["child", "child-tool"], + ]); + expect(byType(events, "tool.execution_complete")).toMatchObject([{ agentId: "child", data: { success: false, error: "Child failure" } }]); + expect(byType(events, "assistant.message").map(event => event.data.content)).toEqual(["Child ", "answer"]); + expect(byType(events, "assistant.message").every(event => event.agentId === "child" && event.provenance.path === "pi-streaming.jsonl" && event.provenance.index === 7)).toBe(true); + expect(byType(events, "session.error")).toMatchObject([{ agentId: "child", data: { error: "Child error" } }]); + expect(byType(events, "subagent.request")).toHaveLength(1); + expect(transformPiV3Entries(JSON.parse(JSON.stringify(events)))).toEqual(JSON.parse(JSON.stringify(events))); + }); + + it("preserves native unknown observations and deduplicated system snapshots without new custom types", () => { + const message = { role: "system", content: "SANITIZED SYSTEM PROMPT", sections: ["sanitized"], timestamp: 1, toolsAdded: [] }; + const unknown = { type: "future_native_event", payload: { preserved: false }, timestamp: 2 }; + const update = { type: "future_update", payload: { preserved: 0 }, contentIndex: 1 }; + const records = [{ type: "message_start", message }, { type: "message_end", message }, unknown, { type: "message_update", assistantMessageEvent: update }, { type: "agent_end", messages: [message] }]; + const events = parse(records).logEntries; + const compact = events.map(event => normalizeUnifiedSessionEvent(event)); + expect(byType(compact, "session.info").map(event => event.data)).toEqual([ + { sourceType: "message_snapshot", role: "system", content: message }, + { sourceType: "future_native_event", content: unknown }, + ]); + expect(byType(compact, "assistant.message_update")).toMatchObject([{ data: { type: "future_update", content: update } }]); + expect(parse(records).markdown).not.toContain("SANITIZED SYSTEM PROMPT"); + expect(byType(events, "session.result")).toEqual([]); + }); + + // Official v1.1.0 agent/src/types.ts and coding-agent/src/core/agent-session.ts; + // synthetic observations, not a workflow run using the upgraded CLI. + it.each([true, false])("retains Pi 1.1.0 cancellation=%s and measured tool duration without fabricating a terminal result", aborted => { + const records = [ + { type: "session", version: 3, id: "release-contract" }, + { type: "tool_execution_start", toolCallId: "measured", toolName: "bash", args: { command: "sanitized" } }, + { type: "tool_execution_end", toolCallId: "measured", toolName: "bash", result: { content: [] }, isError: false, durationMs: 0 }, + { type: "agent_settled", aborted }, + ]; + const compact = parse(records).logEntries.map(event => normalizeUnifiedSessionEvent(event)); + expect(byType(compact, "tool.execution_complete")).toMatchObject([{ data: { durationMs: 0, success: true } }]); + expect(byType(compact, "session.idle")).toEqual([{ type: "session.idle", data: { aborted } }]); + expect(byType(compact, "session.result")).toEqual([]); + }); + + // Synthetic persisted entries following v1.1.0 core/session-manager.ts, + // not a downloaded persisted session (the sampled artifacts contain streams). + it("maps persisted native message envelopes through the same canonical content and tool mapping", () => { + const records = [ + { type: "session", version: 3, id: "persisted", cwd: "/sanitized" }, + { type: "message", id: "user-entry", parentId: null, timestamp: 0, message: { role: "user", content: "Sanitized prompt" } }, + { + type: "message", + id: "call-entry", + parentId: "user-entry", + timestamp: 1, + message: { role: "assistant", id: "call-message", content: [{ type: "toolCall", id: "tool", name: "bash", arguments: false }], usage: { input: 3, output: 1 } }, + }, + { type: "message", id: "result-entry", parentId: "call-entry", timestamp: 2, message: { role: "toolResult", toolCallId: "tool", content: 0, isError: false } }, + { type: "message", id: "answer-entry", parentId: "result-entry", timestamp: 3, message: { role: "assistant", id: "answer-message", content: [{ type: "text", text: "Sanitized answer" }], usage: { input: 2, output: 1 } } }, + { type: "usage", id: "auxiliary", parentId: "answer-entry", timestamp: 4, kind: "cache_warm", model: "fixture", provider: "fixture", usage: { input: 1, output: 0 } }, + ]; + const events = parse(records).logEntries; + expect(byType(events, "user.message")).toMatchObject([{ id: "user-entry", parentId: null, timestamp: 0, data: { content: "Sanitized prompt" } }]); + expect(byType(events, "tool.execution_start")).toMatchObject([{ id: "call-entry", data: { toolCallId: "tool", toolName: "bash", input: false } }]); + expect(byType(events, "tool.execution_complete")).toMatchObject([{ id: "result-entry", data: { output: 0, success: true } }]); + expect(byType(events, "assistant.message")).toMatchObject([{ id: "answer-entry", data: { content: "Sanitized answer" } }]); + expect(byType(events, "session.info")).toMatchObject([{ data: { sourceType: "usage", content: records.at(-1) } }]); + expect(selectSessionResult(events)).toMatchObject({ numTurns: 2, usage: { input_tokens: 6, output_tokens: 2 } }); + expect(parse(records.slice(1, -1)).logEntries).toHaveLength(events.length - 2); + }); + it.each([ ["success", success], ["provider failure", failure], @@ -85,7 +189,12 @@ describe("Pi CI stream regressions", () => { expect(byType(events, "pi.subagent_dispatch")).toEqual([]); expect(byType(events, "pi.subagent_event")).toEqual([]); expect(byType(events, "pi.subagent_result")).toEqual([]); - expect(byType(events, "assistant.message").map(e => e.data.content)).toEqual(["Parent answer"]); + expect( + byType(events, "assistant.message") + .filter(e => !e.agentId) + .map(e => e.data.content) + ).toEqual(["Parent answer"]); + expect(byType(events, "assistant.message").find(e => e.agentId === "invocation-1")).toMatchObject({ data: { content: "Child answer", agentId: "invocation-1" } }); expect(computePiV3Stats(records).usage.input_tokens).toBe(10); }); @@ -499,7 +608,7 @@ describe("Pi CI stream regressions", () => { expect(logEntries.map(e => e.type)).toEqual(["assistant.message", "vendor.progress", "assistant.message", "session.result"]); expect(byType(logEntries, "assistant.message").map(e => e.data.content)).toEqual([" flat ", " v3 "]); expect(logEntries[1]).toMatchObject({ id: "native", data: { count: 0 } }); - expect(parsePiLog('{"type":"unknown","value":1}').logEntries).toEqual([]); + expect(parsePiLog('{"type":"unknown","value":1}').logEntries).toMatchObject([{ type: "session.info", data: { sourceType: "unknown", content: { type: "unknown", value: 1 } } }]); }); it("accounts for truncated message_end and terminal-only transcript snapshots", () => { diff --git a/actions/setup/js/pi_session_pipeline.test.cjs b/actions/setup/js/pi_session_pipeline.test.cjs new file mode 100644 index 00000000000..b85ba3d38d1 --- /dev/null +++ b/actions/setup/js/pi_session_pipeline.test.cjs @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { success, failure, childObservations } from "./fixtures/pi_ci_stream.cjs"; +import { parsePiLog } from "./parse_pi_log.cjs"; +import { runLogParser } from "./log_parser_bootstrap.cjs"; +import { writeUnifiedSession } from "./unified_session.cjs"; +import { normalizeUnifiedSessionEvent } from "./unified_session_payload.cjs"; +import { createSessionValidator } from "./scripts/validate_session.cjs"; + +describe("Pi native-to-unified artifact pipeline", () => { + let root; + let originalEnv; + let originalCore; + const readEvents = file => fs.readFileSync(file, "utf8").trimEnd().split("\n").map(JSON.parse); + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "gh-aw-pi-session-")); + originalEnv = { ...process.env }; + originalCore = global.core; + process.env.GH_AW_AGENT_OUTPUT = path.join(root, "pi-streaming.jsonl"); + delete process.env.GH_AW_SAFE_OUTPUTS; + global.core = { + info: vi.fn(), + debug: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + setOutput: vi.fn(), + setFailed: vi.fn(), + exportVariable: vi.fn(), + summary: { addRaw: vi.fn().mockReturnThis(), write: vi.fn().mockResolvedValue(undefined) }, + }; + }); + + afterEach(() => { + process.env = originalEnv; + global.core = originalCore; + fs.rmSync(root, { recursive: true, force: true }); + }); + + // Sanitized excerpts from separate runs, combined locally to exercise the + // collector. This is not a new live execution or an exact single-run fixture. + it.each([ + ["success with child observations", [...success, ...childObservations]], + ["provider failure", failure], + ])("publishes %s once with authoritative content, scope and provenance", async (_, records) => { + const raw = records.map(record => JSON.stringify(record)).join("\n") + "\n"; + fs.writeFileSync(process.env.GH_AW_AGENT_OUTPUT, raw); + await runLogParser({ parserName: "Pi", parseLog: parsePiLog, rootDir: root }); + expect(global.core.setFailed).not.toHaveBeenCalled(); + const canonical = readEvents(path.join(root, "agent-session.jsonl")); + const parsed = JSON.parse(JSON.stringify(parsePiLog(raw).logEntries)); + expect(canonical.filter(event => event.type !== "agent.execution")).toEqual(parsed); + + const unified = writeUnifiedSession({ rootDir: root, engine: "pi", warn: vi.fn() }); + const file = path.join(root, "usage/aw_session.jsonl"); + expect(readEvents(file)).toEqual(unified); + const agent = unified.filter(event => event.provenance?.path === "agent-session.jsonl" && event.type !== "agent.execution"); + expect(agent.map(event => event.type)).toEqual(parsed.map(event => event.type)); + expect(agent.map(event => event.data)).toEqual(parsed.map(event => normalizeUnifiedSessionEvent(event).data)); + for (const [index, event] of agent.entries()) { + expect(event.provenance).toMatchObject({ component: "agent", phase: "agent", path: "agent-session.jsonl", index }); + } + const validate = createSessionValidator("unified").event; + for (const event of unified) expect(validate(event), JSON.stringify(validate.errors)).toBe(true); + expect(unified.some(event => event.type.startsWith("pi."))).toBe(false); + expect(unified.some(event => event.type === "session.collection_warning")).toBe(false); + const bytes = fs.readFileSync(file, "utf8"); + writeUnifiedSession({ rootDir: root, engine: "pi", warn: vi.fn() }); + expect(fs.readFileSync(file, "utf8")).toBe(bytes); + expect(fs.readFileSync(process.env.GH_AW_AGENT_OUTPUT, "utf8")).toBe(raw); + + fs.unlinkSync(path.join(root, "agent-session.jsonl")); + const reconstructed = writeUnifiedSession({ rootDir: root, engine: "pi", warn: vi.fn() }); + expect(reconstructed.filter(event => event.provenance?.component === "agent" && event.type !== "agent.execution").map(event => event.data)).toEqual(agent.map(event => event.data)); + }); +});