The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix: track session branches independently of agent logs (#400)
Deee44c9ea3a7d4
diff --git a/.github/assets/session-git-context/README.md b/.github/assets/session-git-context/README.mdindex 07c864f8e..8aa1edc05 100644--- a/.github/assets/session-git-context/README.md+++ b/.github/assets/session-git-context/README.md@@ -5,9 +5,14 @@ The session, repository, branches and pull requests are fixtures, not live data.- [Desktop, 1000 × 720](desktop.png)- [Phone, 390 × 760](phone.png)+- [Desktop branch and PR view, 1000 × 720](recovered.png)-Both show the offline state to demonstrate retained work and pull-request+The original desktop and phone captures show the offline state to demonstrate retained work and pull-requesthistory. Generate fresh captures by setting `HARNESS_GIT_CONTEXT_CAPTURE_DIR`when running `desktop/test/session_work_dialog_test.dart` or`mobile/test/session_work_page_test.dart` with `flutter test` in the respectiveapplication directory.++The current desktop capture shows a checked-out branch and a previously recorded+branch with Open and Merged PRs. Temporary checkout paths are absent, including+when newer agent activity is unrecognized. All displayed data is synthetic.diff --git a/.github/assets/session-git-context/recovered.png b/.github/assets/session-git-context/recovered.pngnew file mode 100644index 000000000..444b37c95Binary files /dev/null and b/.github/assets/session-git-context/recovered.png differdiff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex 053a54d53..a48043a79 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -183,7 +183,8 @@ export async function agentFrame(): Promise<AgentFrame> {const home = agentProject(s.cwd)const context = gitContexts.read(JSON.stringify([s.agentId, s.sessionId, s.engine, s.codexHome, s.registeredAt]), async () => {- const value = await sessionGitContext(await home, tokenUsage?.work)+ const saved = await sessionGitHistory.get(s)+ const value = await sessionGitContext(await home, tokenUsage?.work, undefined, saved)value.history = await sessionGitHistory.observe(s, value)return value})diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.tsindex ec3080cf3..30b72ac9f 100644--- a/cli/src/lib/agentTokenUsage.ts+++ b/cli/src/lib/agentTokenUsage.ts@@ -16,7 +16,7 @@ type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath'type Buckets = [number, number, number, number]type CodexTotals = [number, number, number, number]type Checkpoint = {- version: 3; key: string; offset: number; size: number; mtime: number; inode: string;+ version: 4; key: string; offset: number; size: number; mtime: number; inode: string;boundary: string; total: number; observed: boolean; updatedAt: string | null;claude: Record<string, Buckets>; codex: CodexTotals | null; seen: Record<string, true>;output: OutputLedger;@@ -50,7 +50,7 @@ function targetSnapshot(s: Target): Target {codexHome: s.codexHome, cwd: s.cwd, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }}function empty(key: string): Checkpoint {- return { version: 3, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,+ return { version: 4, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,observed: false, updatedAt: null, claude: {}, codex: null, seen: {}, output: emptyOutputLedger(),work: emptySessionWork(), sourceSession: null }}@@ -223,7 +223,22 @@ export class AgentTokenUsageCache {const file = join(this.directory, `${key}.json`)if ((await stat(file)).size > MAX_CACHE_BYTES) return empty(key)const raw = JSON.parse(await readFile(file, 'utf8')) as Checkpoint- if (raw.version === 3 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0+ const version: number = raw.version+ if (version === 3 && raw.key === key) {+ const work = { ...raw.work, currentOrder: 0, failedOrder: 0 }+ if (validSessionWork(work)) {+ // Receipts may already have been compacted out of the transcript. Replay the available+ // bytes with the new parser while retaining only validated minimal history from v3.+ const next = empty(key)+ next.work.locations = work.locations+ next.work.pullRequests = work.pullRequests+ next.work.truncated = work.truncated+ next.work.uncertain = work.locations.length > 0+ return next+ }+ }+ // Replay old transcripts once: v3 skipped ordinary batched code-mode receipts, including PRs.+ if (raw.version === 4 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0&& typeof raw.observed === 'boolean'&& (raw.updatedAt === null || typeof raw.updatedAt === 'string' && Number.isFinite(Date.parse(raw.updatedAt)))&& Number.isSafeInteger(raw.size) && raw.size >= 0 && Number.isFinite(raw.mtime)diff --git a/cli/src/lib/fixtures/session-work-codex.jsonl b/cli/src/lib/fixtures/session-work-codex.jsonlnew file mode 100644index 000000000..b2c695f73--- /dev/null+++ b/cli/src/lib/fixtures/session-work-codex.jsonl@@ -0,0 +1,6 @@+{"timestamp":"2026-09-28T00:17:09.668Z","type":"response_item","payload":{"type":"custom_tool_call","call_id":"create","name":"exec","input":"text(await tools.apply_patch(\"*** Begin Patch\\n*** Add File: /scratch/pr-body.md\\n+PR description\\n*** End Patch\"));\ntext(await tools.exec_command({cmd:\"gh pr create --repo acme/app --base main --head multi-branch --title Fix --body-file /scratch/pr-body.md\",yield_time_ms:1000}));"}}+{"timestamp":"2026-09-28T00:17:18.778Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"create","output":[{"type":"input_text","text":"Script completed\nWall time 9.1 seconds\nOutput:\n"},{"type":"input_text","text":"{}"},{"type":"input_text","text":"{\"chunk_id\":\"2b68c2\",\"wall_time_seconds\":1.001110709,\"session_id\":68079,\"original_token_count\":0,\"output\":\"\"}"}]}}+{"timestamp":"2026-09-28T00:17:25.775Z","type":"response_item","payload":{"type":"custom_tool_call","call_id":"poll","name":"exec","input":"text(await tools.write_stdin({session_id:68079,chars:\"\",yield_time_ms:1000}));\ntext(await tools.exec_command({cmd:\"tail -40 /scratch/test.log\"}));"}}+{"timestamp":"2026-09-28T00:17:25.899Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"poll","output":[{"type":"input_text","text":"Script completed\nWall time 0.1 seconds\nOutput:\n"},{"type":"input_text","text":"{\"chunk_id\":\"c3894c\",\"wall_time_seconds\":2.416e-06,\"exit_code\":0,\"original_token_count\":14,\"output\":\"https://github.com/acme/app/pull/397\\n\"}"},{"type":"input_text","text":"{\"chunk_id\":\"4d4349\",\"wall_time_seconds\":2.333e-06,\"exit_code\":0,\"original_token_count\":439,\"output\":\"contents\\n\"}"}]}}+{"timestamp":"2026-09-28T00:24:30.335Z","type":"response_item","payload":{"type":"custom_tool_call","call_id":"parallel","name":"exec","input":"const results = await Promise.allSettled([\n tools.exec_command({cmd:\"git status --short\",workdir:\"/workspace/happy-owl\"}),\n tools.exec_command({cmd:\"pwd\",workdir:\"/workspace/happy-owl/cli\"}),\n tools.exec_command({cmd:\"git branch --show-current\",workdir:\"/workspace/happy-owl\"})\n]); for(let i=0;i<results.length;i++) text({i,...results[i]});"}}+{"timestamp":"2026-09-28T00:24:30.575Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"parallel","output":[{"type":"input_text","text":"Script completed\nWall time 0.2 seconds\nOutput:\n"},{"type":"input_text","text":"{\"i\":0,\"status\":\"fulfilled\",\"value\":{\"chunk_id\":\"27ca2f\",\"wall_time_seconds\":3.458e-06,\"exit_code\":0,\"original_token_count\":3699,\"output\":\"contents\\n\"}}"},{"type":"input_text","text":"{\"i\":1,\"status\":\"fulfilled\",\"value\":{\"chunk_id\":\"068b9f\",\"wall_time_seconds\":2.333e-06,\"exit_code\":0,\"original_token_count\":1034,\"output\":\"contents\\n\"}}"},{"type":"input_text","text":"{\"i\":2,\"status\":\"fulfilled\",\"value\":{\"chunk_id\":\"da7ab6\",\"wall_time_seconds\":0.035239167,\"exit_code\":0,\"original_token_count\":1824,\"output\":\"contents\\n\"}}"}]}}diff --git a/cli/src/lib/fixtures/session-work-codex.md b/cli/src/lib/fixtures/session-work-codex.mdnew file mode 100644index 000000000..bf217757d--- /dev/null+++ b/cli/src/lib/fixtures/session-work-codex.md@@ -0,0 +1,8 @@+# Batched Codex work receipts++`session-work-codex.jsonl` preserves the tool-call and output-block structure+recorded while creating PR #397 on 2026-09-28. It includes a sequential patch and+yielded PR creation, a later process poll and shell call, and a parallel+`Promise.allSettled` batch with indexed results. Session/call identifiers,+commands, paths, repository URLs and shell output are reduced to test fixtures.+No transcript prose, credentials or private project content is included.diff --git a/cli/src/lib/gitPullRequest.spec.ts b/cli/src/lib/gitPullRequest.spec.tsindex e53d8e195..5c2119766 100644--- a/cli/src/lib/gitPullRequest.spec.ts+++ b/cli/src/lib/gitPullRequest.spec.ts@@ -58,9 +58,12 @@ describe('worktree PR status', () => {it('coalesces lookups and invalidates when the checked-out branch changes', async () => {const f = fixture()await Promise.all([f.read('/worktree'), f.read('/worktree')])- expect(f.run.mock.calls.filter(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('/pulls?'))).toHaveLength(1)+ const queries = () => f.run.mock.calls.filter(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('/pulls?'))+ .map(([, args]) => new URLSearchParams(args.at(-1)!.split('?')[1]))+ expect(queries().map(q => q.get('state')).sort()).toEqual(['closed', 'open'])f.branch('another')await f.read('/worktree')+ expect(queries().filter(q => q.get('head') === 'acme:another').map(q => q.get('state')).sort()).toEqual(['closed', 'open'])expect(f.run.mock.calls.some(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('head=acme%3Aanother'))).toBe(true)})it('uses canonical repository identity after an origin rename', async () => {diff --git a/cli/src/lib/gitPullRequest.ts b/cli/src/lib/gitPullRequest.tsindex 09f24ca67..4239a5e34 100644--- a/cli/src/lib/gitPullRequest.ts+++ b/cli/src/lib/gitPullRequest.ts@@ -69,8 +69,66 @@ function prResult(pr: unknown, repo: string): PullRequestResult {...(label(head?.repo?.full_name) ? { headRepository: label(head?.repo?.full_name) } : {}),}}+/** Look up PRs for a branch already associated with a session, even after checkout/deletion. */+export function createBranchPullRequestReader(execute: Run = run, now = Date.now) {+ const cache = new Map<string, { until: number; value: Promise<PullRequestResult> }>()+ return async ({ branch, remote }: PullRequestIdentity, cwd = tmpdir()): Promise<PullRequestResult> => {+ const repo = remote && githubRepository(`https://${remote}`)+ if (!repo || !branch || branch.length > 256 || /[\x00-\x1f\x7f]/.test(branch)) return { status: 'unavailable' }+ const key = JSON.stringify([repo, branch])+ const previous = cache.get(key)+ if (previous && previous.until > now()) return previous.value+ const value = (async (): Promise<PullRequestResult> => {+ try {+ // GitHub redirects renamed repositories; compare against its canonical identity,+ // not a stale origin spelling (for example autonomous-harness → openharness).+ const metadata = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', '{full_name,fork,parent:{full_name:.parent.full_name}}', `repos/${repo}`], cwd))+ const canonical = typeof metadata?.full_name === 'string' ? metadata.full_name : ''+ if (!canonical || githubRepository(`https://github.com/${canonical}`) !== canonical) return { status: 'unavailable' }+ const parent = metadata.fork && typeof metadata.parent?.full_name === 'string'+ && githubRepository(`https://github.com/${metadata.parent.full_name}`) === metadata.parent.full_name+ ? metadata.parent.full_name as string : null+ const repositories = [...new Set([...(parent ? [parent] : []), canonical])]+ const found: FoundPullRequest[] = []+ let unavailable = false+ const deadline = Date.now() + 10_000+ for (const baseRepo of repositories) {+ try {+ // Ask for open work first, so a long history of closed PRs cannot hide an old open PR.+ for (const state of ['open', 'closed']) {+ if (Date.now() >= deadline) { unavailable = true; break }+ const query = new URLSearchParams({ state, head: `${canonical.split('/')[0]}:${branch}`, sort: 'updated', direction: 'desc', per_page: '100' })+ const rows: unknown = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', 'map({number,html_url,title,state,draft,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{ref:.base.ref}})', `repos/${baseRepo}/pulls?${query}`], cwd))+ if (!Array.isArray(rows)) { unavailable = true; break }+ const matches = rows.filter(p => p?.head?.ref === branch && p?.head?.repo?.full_name?.toLowerCase() === canonical.toLowerCase())+ for (const match of matches) {+ const result = prResult(match, baseRepo)+ if (result.status === 'found') {+ const duplicate = found.findIndex(p => p.url === result.url)+ if (duplicate < 0) found.push(result)+ else if (result.state === 'Open' || result.state === 'Draft') found[duplicate] = result+ } else unavailable = true+ }+ }+ } catch { unavailable = true }+ }+ const pr = found.find(p => p.state === 'Open' || p.state === 'Draft') ?? found[0]+ if (!pr) return { status: unavailable ? 'unavailable' : 'none' }+ const checkedAt = new Date(now()).toISOString()+ const related = found.filter(p => p !== pr).slice(0, 127).map(p => ({ ...p, checkedAt }))+ return { ...pr, checkedAt, ...(related.length ? { related } : {}) }+ } catch { return { status: 'unavailable' } }+ })()+ cache.set(key, { until: now() + 60_000, value })+ if (cache.size > 128) cache.delete(cache.keys().next().value!)+ return value+ }+}+export const readBranchPullRequest = createBranchPullRequestReader()+/** Read-only, on the machine owning the checkout. No shell, browser login, fetch or checkout. */export function createPullRequestReader(execute: Run = run, now = Date.now) {+ const readBranch = createBranchPullRequestReader(execute, now)const cache = new Map<string, { until: number; value: Promise<PullRequestResult> }>()return async (cwd: string, expected?: PullRequestIdentity): Promise<PullRequestResult> => {if (!validGitPath(cwd)) return { status: 'unavailable' }@@ -92,48 +150,7 @@ export function createPullRequestReader(execute: Run = run, now = Date.now) {const key = JSON.stringify([cwd, repo, branch])const previous = cache.get(key)if (previous && previous.until > now()) return await stillCurrent(await previous.value)- const value = (async (): Promise<PullRequestResult> => {- try {- // GitHub redirects renamed repositories; compare against its canonical identity,- // not a stale origin spelling (for example autonomous-harness → openharness).- const metadata = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', '{full_name,fork,parent:{full_name:.parent.full_name}}', `repos/${repo}`], cwd))- const canonical = typeof metadata?.full_name === 'string' ? metadata.full_name : ''- if (!canonical || githubRepository(`https://github.com/${canonical}`) !== canonical) return { status: 'unavailable' }- const parent = metadata.fork && typeof metadata.parent?.full_name === 'string'- && githubRepository(`https://github.com/${metadata.parent.full_name}`) === metadata.parent.full_name- ? metadata.parent.full_name as string : null- const repositories = [...new Set([...(parent ? [parent] : []), canonical])]- const found: FoundPullRequest[] = []- let unavailable = false- const deadline = Date.now() + 10_000- for (const baseRepo of repositories) {- try {- // Ask for open work first, so a long history of closed PRs cannot hide an old open PR.- for (const state of ['open', 'closed']) {- if (Date.now() >= deadline) { unavailable = true; break }- const query = new URLSearchParams({ state, head: `${canonical.split('/')[0]}:${branch}`, sort: 'updated', direction: 'desc', per_page: '100' })- const rows: unknown = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', 'map({number,html_url,title,state,draft,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{ref:.base.ref}})', `repos/${baseRepo}/pulls?${query}`], cwd))- if (!Array.isArray(rows)) { unavailable = true; break }- const matches = rows.filter(p => p?.head?.ref === branch && p?.head?.repo?.full_name?.toLowerCase() === canonical.toLowerCase())- for (const match of matches) {- const result = prResult(match, baseRepo)- if (result.status === 'found') {- const duplicate = found.findIndex(p => p.url === result.url)- if (duplicate < 0) found.push(result)- else if (result.state === 'Open' || result.state === 'Draft') found[duplicate] = result- } else unavailable = true- }- if (matches.length) break- }- } catch { unavailable = true }- }- const pr = found.find(p => p.state === 'Open' || p.state === 'Draft') ?? found[0]- if (!pr) return { status: unavailable ? 'unavailable' : 'none' }- const checkedAt = new Date(now()).toISOString()- const related = found.filter(p => p !== pr).slice(0, 127).map(p => ({ ...p, checkedAt }))- return { ...pr, checkedAt, ...(related.length ? { related } : {}) }- } catch { return { status: 'unavailable' } }- })()+ const value = readBranch({ branch, remote: canonicalRepository(remote) }, cwd)cache.set(key, { until: now() + 60_000, value })if (cache.size > 128) cache.delete(cache.keys().next().value!)return await stillCurrent(await value)diff --git a/cli/src/lib/literalToolCall.spec.ts b/cli/src/lib/literalToolCall.spec.tsindex dd6d9e00b..9e0fed515 100644--- a/cli/src/lib/literalToolCall.spec.ts+++ b/cli/src/lib/literalToolCall.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { literalToolCall } from './literalToolCall.js'+import { literalToolCall, literalToolCalls } from './literalToolCall.js'describe('code-mode literal tool calls', () => {it.each([@@ -26,3 +26,34 @@ describe('code-mode literal tool calls', () => {expect(Object.getPrototypeOf(parsed?.input)).toBeNull()})})++describe('unconditional code-mode batches', () => {+ it('maps sequential receipts separately and parallel receipts to one group', () => {+ const source = `text(await tools.apply_patch("patch"));+ const results = await Promise.allSettled([+ tools.exec_command({cmd:"pwd",workdir:"/one"}),+ tools.exec_command({cmd:"pwd",workdir:"/two"}),+ ]); for(let i=0;i<results.length;i++) { text({i,...results[i]}); }+ text(await tools.write_stdin({session_id:14,chars:""}));`+ expect(literalToolCalls(source)?.map(({ name, group, output }) => ({ name, group, output }))).toEqual([+ { name: 'apply_patch', group: 1, output: { block: 0 } },+ { name: 'exec_command', group: 2, output: { block: 1, index: 0, settled: true } },+ { name: 'exec_command', group: 2, output: { block: 2, index: 1, settled: true } },+ { name: 'write_stdin', group: 3, output: { block: 3 } },+ ])+ })+ it.each([+ 'if (false) text(await tools.exec_command({cmd:"pwd",workdir:"/fake"}));',+ 'text("await tools.exec_command({cmd: \'pwd\'})");',+ 'text(await tools.exec_command({cmd: dynamic, workdir:"/fake"}));',+ 'const results=await Promise.allSettled([tools.exec_command({cmd:"pwd"})]); for(let i=0;i<results.length;i++) text({i,...results[0]});',+ 'text(await tools.exec_command({cmd:"pwd"})); doSomethingElse();',+ 'const results=await Promise.all([tools.exec_command({cmd:"pwd"})]); for(const result of results) { if(false) text(result); }',+ 'text(await tools.exec_command({cmd:"pwd",...overrides}));',+ ])('rejects scripts whose execution/output cannot be established: %s', source => {+ expect(literalToolCalls(source)).toBeNull()+ })+ it('bounds a batch before reading its receipts', () => {+ expect(literalToolCalls('text(await tools.exec_command({cmd:"pwd"}));'.repeat(33))).toBeNull()+ })+})diff --git a/cli/src/lib/literalToolCall.ts b/cli/src/lib/literalToolCall.tsindex 1389e6634..0085eaff0 100644--- a/cli/src/lib/literalToolCall.ts+++ b/cli/src/lib/literalToolCall.ts@@ -1,5 +1,5 @@/** Read a small literal subset of code-mode calls. This never evaluates JavaScript. */-function literal(source: string): unknown {+function literal(source: string, prefix = false): { value: unknown; length: number } {let at = 0const fail = (): never => { throw new Error('Not a literal') }const space = () => { while (/\s/.test(source[at] ?? '') && at < source.length) at++ }@@ -72,8 +72,8 @@ function literal(source: string): unknown {return JSON.parse(primitive!)}const result = value()- space(); if (at !== source.length) fail()- return result+ space(); if (!prefix && at !== source.length) fail()+ return { value: result, length: at }}export function literalToolCall(raw: string): { name: string; input: unknown } | null {@@ -84,5 +84,76 @@ export function literalToolCall(raw: string): { name: string; input: unknown } |const assigned = /^(?:const|let)\s+([a-zA-Z_$][\w$]*)\s*=\s*await\s+tools\.(exec_command|apply_patch|write_stdin)\(([\s\S]*)\)\s*;\s*text\(\s*\1\s*\)\s*;?$/.exec(source)const name = wrapped?.[1] ?? assigned?.[2], argument = wrapped?.[2] ?? assigned?.[3]if (!name || argument === undefined) return null- try { return { name, input: literal(argument) } } catch { return null }+ try { return { name, input: literal(argument).value } } catch { return null }+}++export type ToolOutputSlot = { block: number; settled?: boolean; index?: number }+export type LiteralToolCall = { name: string; input: unknown; group: number; output?: ToolOutputSlot }++/** The ordinary code-mode orchestration grammar, not a JavaScript interpreter.+ * Accept complete unconditional statements and their exact output forwarding. Never search a+ * script for tool-looking substrings: those may be quoted, conditional, or never called.+ * Groups preserve parallelism; output slots associate each receipt with its own arguments. */+export function literalToolCalls(raw: string): LiteralToolCall[] | null {+ if (raw.length > 128 * 1024) return null+ let source = raw.replace(/^\s*\/\/ @exec:[^\n]*\n/, '').trim()+ const calls: LiteralToolCall[] = []+ let group = 0, block = 0+ const fail = (): never => { throw new Error('Unsupported orchestration') }+ const take = (pattern: RegExp): RegExpExecArray | null => {+ source = source.trimStart()+ const match = pattern.exec(source)+ if (match) source = source.slice(match[0].length)+ return match+ }+ const need = (pattern: RegExp) => take(pattern) ?? fail()+ const call = (): LiteralToolCall => {+ const name = need(/^tools\.([a-zA-Z_][\w]*)\s*\(/)[1]+ const argument = literal(source.trimStart(), true)+ source = source.trimStart().slice(argument.length)+ need(/^\)/)+ if (calls.length >= 32) fail()+ const value = { name, input: argument.value, group }+ calls.push(value)+ return value+ }+ try {+ while (source.trim()) {+ if (take(/^\/\/[^\n]*(?:\n|$)/) || take(/^;/)) continue+ group+++ if (take(/^text\s*\(\s*await\s+/)) {+ call().output = { block: block++ }+ need(/^\)/); take(/^;/)+ continue+ }+ if (take(/^await\s+(?=tools\.)/)) {+ call(); take(/^;/) // No forwarded result: intent only, never a successful receipt.+ continue+ }+ const variable = need(/^(?:const|let)\s+([a-zA-Z_]\w*)\s*=\s*await\s+/)[1]+ const batch = take(/^Promise\.(allSettled|all)\s*\(\s*\[/)+ if (!batch) {+ const value = call()+ need(/^;/)+ need(new RegExp(`^text\\s*\\(\\s*${variable}\\s*\\)`)); take(/^;/)+ value.output = { block: block++ }+ continue+ }+ const first = calls.length+ while (!take(/^\]/)) { call(); if (!take(/^,/)) { need(/^\]/); break } }+ need(/^\)/); need(/^;/)+ // Common forwarding loops. Their bodies can only print the corresponding result, either+ // directly or tagged with its index. Extra code, filters and conditional output are rejected.+ const loop = take(new RegExp(`^for\\s*\\(\\s*let\\s+([a-zA-Z_]\\w*)\\s*=\\s*0\\s*;\\s*\\1\\s*<\\s*${variable}\\.length\\s*;\\s*\\1\\+\\+\\s*\\)\\s*(\\{)?\\s*text\\s*\\(\\s*\\{\\s*\\1\\s*,\\s*\\.\\.\\.${variable}\\[\\1\\]\\s*\\}\\s*\\)\\s*;?\\s*`))+ const plain = loop ? null : take(new RegExp(`^for\\s*\\(\\s*const\\s+([a-zA-Z_]\\w*)\\s+of\\s+${variable}\\s*\\)\\s*(\\{)?\\s*text\\s*\\(\\s*\\1\\s*\\)\\s*;?\\s*`))+ if (!loop && !plain) fail()+ if (loop && loop[1] !== 'i') fail() // The indexed receipt contract names its field `i`.+ if ((loop ?? plain)![2]) need(/^\}/)+ calls.slice(first).forEach((value, index) => {+ value.output = { block: block++, ...(batch[1] === 'allSettled' ? { settled: true } : {}),+ ...(loop ? { index } : {}) }+ })+ }+ return calls.length ? calls : null+ } catch { return null }}diff --git a/cli/src/lib/sessionGitContext.spec.ts b/cli/src/lib/sessionGitContext.spec.tsindex e81926146..db29e76cb 100644--- a/cli/src/lib/sessionGitContext.spec.ts+++ b/cli/src/lib/sessionGitContext.spec.ts@@ -29,7 +29,7 @@ describe('Git context from observed session work', () => {expect(await slow).toEqual(fast)expect(await reader.read('hn', async () => next)).toEqual(fast)const other = await reader.read('other-session', async () => old)- expect(other.state).toBe('workspace')+ expect(other.state).toBe('unavailable')expect(other.version?.revision).toBeGreaterThan(fast.version!.revision)})it('reads the actual branch of ship-hn while retaining silent-beacon for launch/resume', async () => {@@ -44,8 +44,8 @@ describe('Git context from observed session work', () => {const observation = work([join(ship, 'tui')])const launch = await agentProject(home)const context = await sessionGitContext(launch, observation)- expect(context).toMatchObject({ state: 'observed', current: { branch: 'hn/preview-fix', worktree: true }, observedAt: at })- expect(context.current?.cwd).toBe(context.current?.root)+ expect(context).toMatchObject({ state: 'multiple', current: null })+ expect(context.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/preview-fix'])expect(launch?.branch).toBe('original')const session = { agentId: 'hn', sessionId: 's', engine: 'claude', cwd: home,registeredAt: 1, boundAt: 1, lastHookAt: 1, transcriptPath: null, runtimes: [],@@ -53,36 +53,54 @@ describe('Git context from observed session work', () => {const frame = await agentFrame(session, { selectedModel: null, terminalAvailable: false,tokenUsage: { totalTokens: null, updatedAt: at, work: observation } })expect(frame.project?.branch).toBe('original')- expect(frame.gitContext.current?.branch).toBe('hn/preview-fix')+ expect(frame.gitContext.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/preview-fix'])expect(session.cwd).toBe(home)})it('collapses different subfolders of one checkout without confusing two worktrees', async () => {const home = { name: 'app', cwd: '/home', root: '/home', branch: 'launch', remote: null }const read = async (cwd: string) => ({ ...home, cwd, root: cwd.startsWith('/one') ? '/one' : '/two', branch: 'topic' })- expect(await sessionGitContext(home, work(['/one/src', '/one/test']), read))- .toMatchObject({ state: 'observed', current: { cwd: '/one', branch: 'topic' } })- expect(await sessionGitContext(home, work(['/one/src', '/two/test']), read))+ expect(await sessionGitContext(null, work(['/one/src', '/one/test']), read))+ .toMatchObject({ state: 'observed', current: { cwd: '/one', branch: 'topic' }, locations: [{ cwd: '/one' }] })+ expect(await sessionGitContext(null, work(['/one/src', '/two/test']), read)).toMatchObject({ state: 'multiple', current: null })})+ it('resolves nested checkouts without replacing a fresh assigned-branch snapshot with a cached subfolder', async () => {+ const home = { name: 'app', cwd: '/home', root: '/home', branch: 'fresh', remote: 'github.com/acme/app' }+ const read = async (cwd: string) => cwd === '/home/nested'+ ? { ...home, cwd, root: cwd, branch: 'nested-topic' }+ : { ...home, cwd, branch: 'older-cache' }+ const context = await sessionGitContext(home, work(['/home/src', '/home/nested']), read)+ expect(context.state).toBe('multiple')+ expect(context.checkouts?.map(p => p.branch)).toEqual(['fresh', 'nested-topic'])+ })+it('keeps absent, unreadable, uncertain and non-Git contexts distinct', async () => {const home = { name: 'app', cwd: '/home', root: '/home', branch: 'launch', remote: null }expect(await sessionGitContext(home)).toMatchObject({ state: 'workspace', current: home })const read = vi.fn(async () => null)- expect(await sessionGitContext(home, work(['/gone']), read)).toMatchObject({ state: 'unavailable', current: null })+ expect(await sessionGitContext(home, work(['/gone']), read)).toMatchObject({ state: 'workspace', current: home })read.mockClear()- expect(await sessionGitContext(home, work(['/one'], { uncertain: true }), read)).toMatchObject({ state: 'uncertain', current: null })+ expect(await sessionGitContext(home, work([], { uncertain: true }), read)).toMatchObject({ state: 'workspace', current: home })expect(read).not.toHaveBeenCalled()expect(await sessionGitContext(home, work(['/folder']), async () => ({ ...home, cwd: '/folder', root: null, branch: null })))- .toMatchObject({ state: 'observed', current: { cwd: '/folder', branch: null } })+ .toMatchObject({ state: 'workspace', current: home })+ })++ it('reads associated Git branches independently of unresolved activity', async () => {+ const read = async (cwd: string) => ({ name: 'app', cwd, root: '/one', branch: 'topic', remote: null })+ const context = await sessionGitContext(null, work(['/one/src'], { uncertain: true,+ locations: [{ cwd: '/one/src', at }, { cwd: '/one/test', at }, { cwd: '/one-other', at }] }), read)+ expect(context).toMatchObject({ state: 'observed', current: { cwd: '/one', branch: 'topic' } })+ expect(context.locations.map(row => row.cwd)).toEqual(['/one', '/one-other'])})it('bounds Git work for a compound operation and preserves durable PR links without a checkout', async () => {const read = vi.fn(async () => null)const pullRequests = [{ url: 'https://github.com/acme/app/pull/12', cwd: '/gone', at }]const context = await sessionGitContext(null, work(Array.from({ length: 20 }, (_, i) => `/work/${i}`), { pullRequests }), read)- expect(context).toMatchObject({ state: 'multiple', current: null, truncated: true, pullRequests })- expect(read).not.toHaveBeenCalled()+ expect(context).toMatchObject({ state: 'unavailable', current: null, truncated: true, pullRequests })+ expect(read).toHaveBeenCalledTimes(8)})})diff --git a/cli/src/lib/sessionGitContext.ts b/cli/src/lib/sessionGitContext.tsindex b955469cd..259f3e2b4 100644--- a/cli/src/lib/sessionGitContext.ts+++ b/cli/src/lib/sessionGitContext.ts@@ -1,5 +1,6 @@import { stat } from 'node:fs/promises'import { randomUUID } from 'node:crypto'+import { sep } from 'node:path'import { agentProject, type AgentProject } from './agentProject.js'import type { SessionWork, WorkPullRequest } from './sessionWork.js'import type { GitHistory } from './sessionGitHistory.js'@@ -7,7 +8,11 @@ import type { GitHistory } from './sessionGitHistory.js'export type SessionGitContext = {state: 'workspace' | 'observed' | 'multiple' | 'uncertain' | 'unavailable'current: AgentProject | null+ /** Git snapshots of session-associated checkouts. Paths are internal identity, not UI labels. */+ checkouts?: AgentProject[]observedAt: string | null+ /** The location is confirmed historical work; newer tool activity could not yet be resolved. */+ activityUncertain?: boolean/** Paths describe observed work, never worktree ownership or deletion eligibility. */locations: Array<{ cwd: string; at: string }>pullRequests: WorkPullRequest[]@@ -59,24 +64,55 @@ async function inspect(cwd: string): Promise<AgentProject | null> {/** Display-only projection. Registry cwd and the legacy project keep their launch semantics. */export async function sessionGitContext(home: AgentProject | null, work?: SessionWork | null,- read: Inspect = inspect): Promise<SessionGitContext> {+ read: Inspect = inspect, history?: GitHistory): Promise<SessionGitContext> {const context: SessionGitContext = {state: 'workspace', current: home, observedAt: null,locations: work?.locations ?? [], pullRequests: work?.pullRequests ?? [], truncated: work?.truncated ?? false,+ checkouts: [],}- if (!work) return context- context.current = null- context.observedAt = work.current.reduce<string | null>((at, row) => at && at > row.at ? at : row.at, null)- if (work.uncertain || !work.current.length) return { ...context, state: 'uncertain' }- // One tool can touch many folders. Resolve only a bounded set; exceeding it cannot imply one.- if (work.current.length > 8) return { ...context, state: 'multiple', truncated: true }- const projects = await Promise.all(work.current.map(row => read(row.cwd).catch(() => null)))- if (projects.some(p => !p)) return { ...context, state: 'unavailable' }const roots = new Map<string, AgentProject>()- for (const project of projects) if (project) roots.set(project.root ?? project.cwd, project)- if (roots.size !== 1) return { ...context, state: 'multiple' }- const project = [...roots.values()][0]- // Working on src/ or tui/ should still identify the checkout, independent of the last file tool.- context.current = project.root ? { ...project, cwd: project.root } : project- return { ...context, state: 'observed' }+ const add = (project: AgentProject | null) => {+ if (project?.root && !roots.has(project.root)) roots.set(project.root, { ...project, cwd: project.root })+ }+ // The assigned checkout is authoritative for every engine, including engines without a+ // transcript reader. Tool receipts only add associations; they never invalidate Git facts.+ add(home)+ const paths = [...new Set([+ ...(work?.current.map(row => row.cwd) ?? []),+ ...(history?.branches.map(row => row.cwd) ?? []),+ ...(work?.locations.map(row => row.cwd) ?? []),+ ])]+ let reads = 0+ for (const cwd of paths) {+ if (roots.has(cwd)) continue+ // A subdirectory can itself be a nested repository/worktree. Resolve it through Git,+ // never assume path containment proves checkout identity. Bound additional lookups.+ if (reads++ === 8) { context.truncated = true; break }+ add(await read(cwd).catch(() => null))+ }+ // Different files in one checkout are one useful workspace in the details view. Only collapse+ // paths under roots Git actually resolved; similarly named sibling worktrees remain distinct.+ const knownRoots = [...new Set([...roots.values()].flatMap(p => p.root ? [p.root] : []))].sort((a, b) => b.length - a.length)+ const locations = new Map<string, { cwd: string; at: string }>()+ for (const row of context.locations) {+ const cwd = knownRoots.find(root => row.cwd === root || row.cwd.startsWith(root.endsWith(sep) ? root : root + sep)) ?? row.cwd+ const previous = locations.get(cwd)+ if (!previous || previous.at < row.at) locations.set(cwd, { ...row, cwd })+ }+ context.locations = [...locations.values()].sort((a, b) => b.at.localeCompare(a.at))+ context.checkouts = [...roots.values()]+ // Same repository + branch is one user-facing branch, even if it has several local copies.+ const branches = new Map<string, AgentProject>()+ for (const project of context.checkouts) if (!project.branchPending) {+ const key = JSON.stringify([project.remote ?? project.root, project.branch])+ if (!branches.has(key)) branches.set(key, project)+ }+ if (branches.size > 1) return { ...context, state: 'multiple', current: null }+ if (branches.size === 1) {+ context.current = [...branches.values()][0]+ context.state = context.current.root === home?.root ? 'workspace' : 'observed'+ return context+ }+ // A non-Git folder has no branch. Missing activity is never reported as a lost workspace.+ return { ...context, current: home, state: home ? 'workspace' : 'unavailable' }}diff --git a/cli/src/lib/sessionGitHistory.spec.ts b/cli/src/lib/sessionGitHistory.spec.tsindex 3c79805c5..b1a5f8eee 100644--- a/cli/src/lib/sessionGitHistory.spec.ts+++ b/cli/src/lib/sessionGitHistory.spec.ts@@ -65,12 +65,12 @@ describe('durable session Git history', () => {expect((await restarted.get({ ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: 2 })).branches).toEqual([])})- it('does not claim the launch branch or uncertain work as a branch worked on', async () => {+ it('records the assigned branch without requiring tool activity, without inventing unknown branches', async () => {const dir = await mkdtemp(join(tmpdir(), 'git-history-')); dirs.push(dir)const store = new SessionGitHistoryStore(dir)await store.observe(target, context('main', { state: 'workspace' }))await store.observe(target, context('maybe', { state: 'uncertain', current: null }))- expect((await store.get(target)).branches).toEqual([])- expect(await readdir(dir)).toEqual([])+ expect((await store.get(target)).branches.map(b => b.branch)).toEqual(['main'])+ await store.settled()})})diff --git a/cli/src/lib/sessionGitHistory.ts b/cli/src/lib/sessionGitHistory.tsindex cf0942b3a..c9f592685 100644--- a/cli/src/lib/sessionGitHistory.ts+++ b/cli/src/lib/sessionGitHistory.ts@@ -85,14 +85,15 @@ export class SessionGitHistoryStore {try {await entry.loadedconst before = JSON.stringify(entry.value)- const current = context.current- const branch = current?.branch- // The launch checkout is context, not evidence that this conversation worked on its branch.- if (context.state === 'observed' && current && branch && !branch.startsWith('Detached ')) {+ // This records branches checked out for the session, not authorship or proof of edits.+ // Engine logs are optional enrichment; direct Git observations work for every engine.+ for (const current of context.checkouts ?? (context.current ? [context.current] : [])) {+ const branch = current.branch+ if (!current.root || !branch || current.branchPending || branch.startsWith('Detached ')) continueconst same = (b: WorkBranch) => b.cwd === (current.root ?? current.cwd) && b.branch === branch && b.remote === current.remoteconst previous = entry.value.branches.find(same)// Retrospective tool receipts cannot establish when this branch was checked out.- const at = previous ? context.observedAt ?? previous.at : new Date().toISOString()+ const at = previous?.at ?? new Date().toISOString()if (!previous || previous.at < at) entry.value.branches = [{ cwd: current.root ?? current.cwd, branch, remote: current.remote, at }, ...entry.value.branches.filter(b => !same(b)),]@@ -119,7 +120,8 @@ export class SessionGitHistoryStore {const existing = candidates.sort((a, b) => (b.checkedAt ?? '').localeCompare(a.checkedAt ?? ''))[0]// Network failures preserve the last observed state, with its original observation time.if (result.status === 'unavailable' && existing) return- const source = existing?.checkedAt && existing.checkedAt > checkedAt ? existing : { ...pr, result, checkedAt }+ const source = existing?.checkedAt && existing.checkedAt > checkedAt ? existing+ : { ...pr, at: existing?.at ?? pr.at, cwd: existing?.cwd ?? pr.cwd, result, checkedAt }if (source === existing) url = existing.urlconst aliases = [...new Set([pr.url, ...candidates.flatMap(p => [p.url, ...(p.aliases ?? [])])])].filter(alias => alias !== url).slice(0, 16)const next = { ...source, url,diff --git a/cli/src/lib/sessionGitPullRequest.spec.ts b/cli/src/lib/sessionGitPullRequest.spec.tsindex 1573d506b..ad24798fc 100644--- a/cli/src/lib/sessionGitPullRequest.spec.ts+++ b/cli/src/lib/sessionGitPullRequest.spec.ts@@ -1,5 +1,5 @@import { execFileSync } from 'node:child_process'-import { appendFile, mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'+import { appendFile, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -65,8 +65,9 @@ describe('session work from transcript through Git and PR history', () => {vi.spyOn(sessionGitHistory, 'get').mockImplementation(target => history.get(target))vi.spyOn(sessionGitHistory, 'observe').mockImplementation((target, context) => history.observe(target, context))vi.spyOn(sessionGitHistory, 'recordPullRequest').mockImplementation((...args) => history.recordPullRequest(...args))- vi.spyOn(github, 'readGitPullRequest').mockImplementation(github.createPullRequestReader(execute))- vi.spyOn(github, 'readPullRequestUrl').mockImplementation(github.createPullRequestUrlReader(execute))+ vi.spyOn(github, 'readGitPullRequest').mockImplementation(github.createPullRequestReader(execute, () => now))+ vi.spyOn(github, 'readBranchPullRequest').mockImplementation(github.createBranchPullRequestReader(execute, () => now))+ vi.spyOn(github, 'readPullRequestUrl').mockImplementation(github.createPullRequestUrlReader(execute, () => now))rows = [pr(12, 'hn/nfc'), pr(13, 'hn/preview')]})afterEach(async () => {@@ -74,10 +75,55 @@ describe('session work from transcript through Git and PR history', () => {vi.restoreAllMocks(); await rm(directory, { recursive: true, force: true })})+ it.each(['claude', 'codex', 'grok'] as const)('tracks %s branches and PRs without any tool receipts', async engine => {+ agent.engine = engine+ agent.cwd = ship+ agent.transcriptPath = null+ const first = await frame()+ expect(first.gitContext).toMatchObject({ state: 'workspace', current: { branch: 'hn/nfc' },+ history: { branches: [{ branch: 'hn/nfc' }] } })+ expect(await readSessionGitPullRequest(agent, { history: true })).toMatchObject({+ history: { pullRequests: [{ result: { number: 12, state: 'Open' } }] },+ })+ git(ship, 'switch', '-c', 'hn/preview')+ forgetAgentProject(ship)+ const next = await frame()+ expect(next.gitContext.current?.branch).toBe('hn/preview')+ expect(next.gitContext.history?.branches.map(b => b.branch).sort()).toEqual(['hn/nfc', 'hn/preview'])+ rows[0] = pr(12, 'hn/nfc', true)+ now += 61_000+ const refreshed = await readSessionGitPullRequest(agent, { history: true })+ expect('history' in refreshed && refreshed.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))+ .toEqual([[13, 'Open'], [12, 'Merged']])+ // Another session's branch exists in the same repository, but has no association here.+ expect(next.gitContext.history?.branches.some(b => b.branch === 'original')).toBe(false)+ })++ it('discovers earlier PRs from saved branch identities even after the branch is deleted', async () => {+ agent.engine = 'grok'; agent.cwd = ship; agent.transcriptPath = null+ await frame() // Branch observed, but nobody opened its PR badge or details.+ git(ship, 'switch', '-c', 'hn/preview')+ git(ship, 'branch', '-D', 'hn/nfc')+ forgetAgentProject(ship)+ rows[0] = pr(12, 'hn/nfc', true)+ const result = await readSessionGitPullRequest(agent, { history: true })+ expect('history' in result && result.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))+ .toEqual([[13, 'Open'], [12, 'Merged']])+ })++ it('keeps completed PRs when the same branch also has open work', async () => {+ agent.cwd = ship; agent.transcriptPath = null+ rows = [pr(12, 'hn/nfc', true), pr(14, 'hn/nfc')]+ const result = await readSessionGitPullRequest(agent, { history: true })+ expect('history' in result && result.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))+ .toEqual([[14, 'Open'], [12, 'Merged']])+ })+it('shows the observed checkout, follows branch switches, and retains merged PRs after removal/restart', async () => {+ agent.cwd = shipawait receipt('nfc', join(ship, 'tui'), 12)const first = await frame()- expect(first.project?.branch).toBe('original')+ expect(first.project?.branch).toBe('hn/nfc')expect(first.gitContext.current).toMatchObject({ cwd: ship, branch: 'hn/nfc', worktree: true })const expected = { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' }expect(await readSessionGitPullRequest(agent, { expected })).toMatchObject({ status: 'found', number: 12, context: expected })@@ -89,13 +135,13 @@ describe('session work from transcript through Git and PR history', () => {expect(second.gitContext.version!.revision).toBeGreaterThan(first.gitContext.version!.revision)expect((await readSessionGitPullRequest(agent, { expected })).status).toBe('unavailable')expect(await readSessionGitPullRequest(agent)).toMatchObject({ status: 'found', number: 13 })- expect(agent.cwd).toBe(home)+ expect(agent.cwd).toBe(ship)git(home, 'worktree', 'remove', '--force', ship)git(home, 'branch', '-D', 'hn/nfc', 'hn/preview')rows = rows.map(p => pr(p.number, p.head.ref, true))const removed = await readSessionGitPullRequest(agent, { history: true })- expect(removed).toMatchObject({ status: 'unavailable', gitContext: { state: 'unavailable', current: null } })+ expect(removed).toMatchObject({ status: 'unavailable', gitContext: { checkouts: [] } })expect('history' in removed && removed.history.pullRequests.map(p => p.result?.status === 'found' && p.result.state)).toEqual(['Merged', 'Merged'])await history.settled()const restarted = await new SessionGitHistoryStore(join(directory, 'history')).get(agent)@@ -106,7 +152,28 @@ describe('session work from transcript through Git and PR history', () => {expect('history' in offline && offline.history.pullRequests).toEqual(restarted.pullRequests)})+ it('recovers recorded Codex batches into branch history and a merged PR despite later unknown activity', async () => {+ agent.engine = 'codex'+ const recorded = (await readFile(new URL('./fixtures/session-work-codex.jsonl', import.meta.url), 'utf8'))+ .replaceAll('/workspace/happy-owl/cli', `${ship}/tui`).replaceAll('/workspace/happy-owl', ship)+ await writeFile(agent.transcriptPath!, line({ timestamp: new Date(now).toISOString(), type: 'turn_context', payload: { cwd: ship } }) + recorded + [+ { timestamp: '2026-09-28T00:30:00Z', type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'unknown', name: 'exec', input: 'await arbitraryScript();' } },+ { timestamp: '2026-09-28T00:30:01Z', type: 'response_item', payload: { type: 'custom_tool_call_output', call_id: 'unknown', output: 'Script completed\nOutput:\n' } },+ ].map(line).join(''))+ usage.changed(agent); await usage.settled()+ rows = [pr(397, 'hn/nfc', true)]+ const value = await frame()+ expect(value.gitContext).toMatchObject({ state: 'multiple', current: null,+ history: { pullRequests: [{ url: 'https://github.com/acme/app/pull/397' }] } })+ expect(value.gitContext.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/nfc'])+ expect(value.gitContext.history?.branches.map(p => p.branch).sort()).toEqual(['hn/nfc', 'original'])+ const result = await readSessionGitPullRequest(agent, { history: true })+ expect(result).toMatchObject({ history: { pullRequests: [{ result: { status: 'found', number: 397, state: 'Merged' } }] } })+ expect(agent.cwd).toBe(home)+ })+it('rejects a badge if work moves while GitHub is answering', async () => {+ agent.cwd = shipawait receipt('nfc', ship)vi.mocked(github.readGitPullRequest).mockImplementation(async () => {await receipt('elsewhere', home)@@ -114,7 +181,7 @@ describe('session work from transcript through Git and PR history', () => {})expect(await readSessionGitPullRequest(agent, {expected: { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' },- })).toMatchObject({ status: 'unavailable', context: { cwd: home, branch: 'original' } })+ })).toMatchObject({ status: 'unavailable', context: null })})it('refreshes the visible open-first page, including multiple PRs for one branch', async () => {diff --git a/cli/src/lib/sessionGitPullRequest.ts b/cli/src/lib/sessionGitPullRequest.tsindex 194619836..8a5216f05 100644--- a/cli/src/lib/sessionGitPullRequest.ts+++ b/cli/src/lib/sessionGitPullRequest.ts@@ -1,9 +1,9 @@import type { RegisteredSession } from './registry.js'-import { agentProject } from './agentProject.js'+import { agentProject, forgetAgentProject } from './agentProject.js'import { agentTokenUsage } from './agentTokenUsage.js'import { sessionGitContext } from './sessionGitContext.js'import { sessionGitHistory } from './sessionGitHistory.js'-import { readGitPullRequest, readPullRequestUrl } from './gitPullRequest.js'+import { readBranchPullRequest, readGitPullRequest, readPullRequestUrl } from './gitPullRequest.js'export type ExpectedGitContext = { cwd: string; branch: string; remote: string | null }/** The branch badge and session history share the same resolved checkout. Existing callers may@@ -12,7 +12,14 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, optionexpected?: ExpectedGitContext; history?: boolean; offset?: number;} = {}) {const work = agentTokenUsage.get(agent)?.work- let context = await sessionGitContext(await agentProject(agent.cwd), work)+ const resolve = async (observed = work) => {+ const saved = await sessionGitHistory.get(agent)+ if (options.history) for (const cwd of [agent.cwd, ...saved.branches.map(b => b.cwd), ...(observed?.current.map(b => b.cwd) ?? [])]) {+ if (cwd) forgetAgentProject(cwd)+ }+ return sessionGitContext(await agentProject(agent.cwd), observed, undefined, saved)+ }+ let context = await resolve()await sessionGitHistory.observe(agent, context)const current = context.currentlet identity = current?.branch ? { cwd: current.cwd, branch: current.branch, remote: current.remote } : null@@ -22,7 +29,7 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, option? identity ? await readGitPullRequest(current.cwd, identity) : await readGitPullRequest(current.cwd): { status: 'unavailable' as const }const checkedAt = new Date().toISOString()- if (result.status === 'found' && context.state === 'observed') for (const pr of [result, ...(result.related ?? [])]) {+ if (result.status === 'found') for (const pr of [result, ...(result.related ?? [])]) {const { related: _, ...recorded } = prawait sessionGitHistory.recordPullRequest(agent,{ url: pr.url, cwd: current!.cwd, at: context.observedAt ?? checkedAt }, recorded, pr.checkedAt ?? checkedAt)@@ -30,7 +37,7 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, optionconst refreshMovedWork = async () => {const latest = agentTokenUsage.get(agent)?.workif (JSON.stringify(latest) === JSON.stringify(work)) return- context = await sessionGitContext(await agentProject(agent.cwd), latest)+ context = await resolve(latest)await sessionGitHistory.observe(agent, context)const project = context.currentidentity = project?.branch ? { cwd: project.cwd, branch: project.branch, remote: project.remote } : null@@ -41,8 +48,21 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, optionreturn options.expected ? { ...result, context: identity } : result}- const saved = await sessionGitHistory.get(agent)const offset = Number.isSafeInteger(options.offset) && options.offset! >= 0 ? Math.min(options.offset!, 128) : 0+ // Saved branch identities belong to this session and survive checkout changes. Query a+ // bounded page, including branches whose PR was never printed in any engine's transcript.+ const branches = [...new Map((await sessionGitHistory.get(agent)).branches.map(branch =>+ [JSON.stringify([branch.remote ?? branch.cwd, branch.branch]), branch])).values()]+ await Promise.all(branches.slice(offset, offset + 4).map(async project => {+ const found = await readBranchPullRequest({ branch: project.branch, remote: project.remote })+ if (found.status === 'found') for (const pr of [found, ...(found.related ?? [])]) {+ const { related: _, ...recorded } = pr+ await sessionGitHistory.recordPullRequest(agent, { url: pr.url, cwd: project.cwd, at: checkedAt },+ recorded, pr.checkedAt ?? checkedAt)+ }+ }))++ const saved = await sessionGitHistory.get(agent)const page = saved.pullRequests.slice(offset, offset + 4)const lookups = await Promise.all(page.map(async pr => {const answer = await readPullRequestUrl(pr.url)@@ -52,5 +72,5 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, optionawait refreshMovedWork()const history = await sessionGitHistory.get(agent)return { ...result, context: identity, gitContext: context, history, lookups,- nextOffset: offset + page.length < saved.pullRequests.length ? offset + page.length : null }+ nextOffset: offset + 4 < Math.max(saved.pullRequests.length, branches.length) ? offset + 4 : null }}diff --git a/cli/src/lib/sessionWork.spec.ts b/cli/src/lib/sessionWork.spec.tsindex cf3025a40..a25b5df2f 100644--- a/cli/src/lib/sessionWork.spec.ts+++ b/cli/src/lib/sessionWork.spec.ts@@ -1,4 +1,5 @@import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'import { emptySessionWork, ingestSessionWork, sessionWorkSnapshot, shellWorkLocations, validSessionWork } from './sessionWork.js'const at = '2026-09-27T13:00:00.000Z'@@ -125,7 +126,7 @@ describe('per-session work receipts', () => {f.start('search', { query: 'hello' }, 'WebSearch'); f.finish('search')expect(f.snapshot()?.uncertain).toBe(false)f.start('unknown', { command: 'cd "$TASK" && test' }); f.finish('unknown')- expect(f.snapshot()).toMatchObject({ current: [], locations: [{ cwd: '/one' }], uncertain: true })+ expect(f.snapshot()).toMatchObject({ current: [{ cwd: '/one' }], locations: [{ cwd: '/one' }], uncertain: true })})it('uses explicit Codex workdir and turn context, including code mode without evaluation', () => {@@ -142,7 +143,7 @@ describe('per-session work receipts', () => {f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'dynamic', name: 'exec',input: 'if (false) text(await tools.exec_command({"cmd":"test","workdir":"/fake"}));' } })f.finish('dynamic')- expect(f.snapshot()).toMatchObject({ current: [], uncertain: true })+ expect(f.snapshot()).toMatchObject({ current: [{ cwd: '/code' }], uncertain: true })})it('tracks file tools without treating a mentioned path as a checkout', () => {@@ -186,4 +187,69 @@ describe('per-session work receipts', () => {expect(validSessionWork({ ...f.state, current: [{ cwd: '/bad\n', at }] })).toBe(false)expect(validSessionWork({ ...f.state, pullRequests: [{ url: 'javascript:bad', cwd: null, at }] })).toBe(false)})++ it('recovers this session’s yielded PR creation and parallel work from recorded Codex blocks', () => {+ const f = fixture('codex')+ f.row({ type: 'turn_context', payload: { cwd: '/workspace/happy-owl' } })+ const rows = readFileSync(new URL('./fixtures/session-work-codex.jsonl', import.meta.url), 'utf8').trim().split('\n').map(line => JSON.parse(line))+ for (const row of rows) f.row(row)+ expect(f.snapshot()).toMatchObject({ uncertain: false,+ current: [{ cwd: '/workspace/happy-owl' }, { cwd: '/workspace/happy-owl/cli' }],+ pullRequests: [{ url: 'https://github.com/acme/app/pull/397', cwd: '/workspace/happy-owl' }] })+ expect(Object.keys(f.state.running)).toHaveLength(0)+ expect(validSessionWork(JSON.parse(JSON.stringify(f.state)))).toBe(true)+ // A later unsupported call cannot erase the checkout or PR we just verified.+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'unsupported', name: 'exec', input: 'await arbitraryScript();' } })+ f.finish('unsupported')+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [{ cwd: '/workspace/happy-owl' }, { cwd: '/workspace/happy-owl/cli' }] })+ expect(f.snapshot()?.pullRequests).toHaveLength(1)+ })++ it('retains confirmed work during pending and failed commands without claiming the attempted checkout', () => {+ const f = fixture('codex')+ f.start('known', { cmd: 'pwd', workdir: '/confirmed' }); f.finish('known', '{"exit_code":0}')+ f.start('attempt', { cmd: 'test', workdir: '/unconfirmed' })+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [{ cwd: '/confirmed' }] })+ f.finish('attempt', '{"exit_code":1}')+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [{ cwd: '/confirmed' }] })+ expect(f.snapshot()?.locations.map(row => row.cwd)).toEqual(['/confirmed'])+ })++ it('does not trust missing, misindexed or rejected parallel receipts', () => {+ for (const result of [{ i: 1, status: 'fulfilled', value: { exit_code: 0 } }, { i: 0, status: 'rejected', reason: 'failed' }, {}]) {+ const f = fixture('codex')+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'batch', name: 'exec',+ input: 'const results=await Promise.allSettled([tools.exec_command({cmd:"pwd",workdir:"/fake"})]); for(let i=0;i<results.length;i++) text({i,...results[i]});' } })+ f.finish('batch', [{ type: 'input_text', text: JSON.stringify(result) }])+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [], locations: [] })+ }+ })++ it('keeps parallel successes and failures distinct, regardless of output order', () => {+ const f = fixture('codex')+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'batch', name: 'exec',+ input: 'const results=await Promise.all([tools.exec_command({cmd:"test",workdir:"/failed"}),tools.exec_command({cmd:"pwd",workdir:"/confirmed"})]); for(const result of results) text(result);' } })+ f.finish('batch', [{ type: 'input_text', text: '{"exit_code":1}' }, { type: 'input_text', text: '{"exit_code":0}' }])+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [{ cwd: '/confirmed' }], locations: [{ cwd: '/confirmed' }] })+ f.start('next', { cmd: 'pwd', workdir: '/next' }); f.finish('next', '{"exit_code":0}')+ expect(f.snapshot()).toMatchObject({ uncertain: false, current: [{ cwd: '/next' }] })+ })++ it('correlates a partially yielded batch across checkpoint and cell/process waits', () => {+ const f = fixture('codex')+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'batch', name: 'exec',+ input: 'text(await tools.exec_command({cmd:"pwd",workdir:"/one"})); text(await tools.exec_command({cmd:"gh pr create",workdir:"/two"}));' } })+ f.finish('batch', [{ type: 'input_text', text: '{"exit_code":0,"output":"/one"}' },+ { type: 'input_text', text: 'Script running with cell ID cell-1' }])+ expect(f.snapshot()).toMatchObject({ uncertain: true, current: [{ cwd: '/one' }] })+ expect(validSessionWork(JSON.parse(JSON.stringify(f.state)))).toBe(true)+ f.start('cell-poll', { cell_id: 'cell-1' }, 'wait')+ f.finish('cell-poll', [{ type: 'input_text', text: 'Script completed\nOutput:\n' },+ { type: 'input_text', text: '{"session_id":77,"output":""}' }])+ f.start('process-poll', { session_id: 77, chars: '' }, 'write_stdin')+ f.finish('process-poll', '{"exit_code":0,"output":"https://github.com/acme/app/pull/12"}')+ expect(f.snapshot()).toMatchObject({ uncertain: false, current: [{ cwd: '/two' }],+ pullRequests: [{ url: 'https://github.com/acme/app/pull/12', cwd: '/two' }] })+ expect(Object.keys(f.state.running)).toHaveLength(0)+ })})diff --git a/cli/src/lib/sessionWork.ts b/cli/src/lib/sessionWork.tsindex 9f62d7f2b..59437bca2 100644--- a/cli/src/lib/sessionWork.ts+++ b/cli/src/lib/sessionWork.ts@@ -1,13 +1,14 @@/** Minimal, replayable work-location evidence. No Git, I/O, shell execution or raw output storage. */import { createHash } from 'node:crypto'import { dirname, isAbsolute, resolve } from 'node:path'-import { literalToolCall } from './literalToolCall.js'+import { literalToolCall, literalToolCalls, type ToolOutputSlot } from './literalToolCall.js'export type WorkLocation = { cwd: string; at: string }export type WorkPullRequest = { url: string; cwd: string | null; at: string }-type Operation = { paths: string[]; at: string; order: number; createsPr: boolean }+type Operation = { paths: string[]; at: string; order: number; createsPr: boolean;+ children?: Array<{ operation: Operation; output?: ToolOutputSlot }> }export type SessionWorkLedger = {- context: string | null; sequence: number; latest: number;+ context: string | null; sequence: number; latest: number; currentOrder: number; failedOrder: number;current: WorkLocation[]; locations: WorkLocation[]; pullRequests: WorkPullRequest[];pending: Record<string, Operation>; running: Record<string, Operation>; completed: string[];uncertain: boolean; truncated: boolean;@@ -24,7 +25,7 @@ export const validWorkPath = (v: unknown): v is string =>export const validPullRequestUrl = (v: unknown): v is string => typeof v === 'string'&& /^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/pull\/[1-9]\d*$/.test(v)&& new URL(v).href === v && Number.isSafeInteger(Number(v.split('/').at(-1)))-export const emptySessionWork = (): SessionWorkLedger => ({ context: null, sequence: 0, latest: 0,+export const emptySessionWork = (): SessionWorkLedger => ({ context: null, sequence: 0, latest: 0, currentOrder: 0, failedOrder: 0,current: [], locations: [], pullRequests: [], pending: {}, running: {}, completed: [], uncertain: false, truncated: false })export function validSessionWork(value: unknown): value is SessionWorkLedger {@@ -32,14 +33,21 @@ export function validSessionWork(value: unknown): value is SessionWorkLedger {const locations = (v: unknown) => Array.isArray(v) && v.length <= LIMIT&& v.every(x => validWorkPath(x?.cwd) && stamp(x?.at))const integer = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0+ const operation = (op: Operation, depth = 0): boolean => depth <= 4+ && Array.isArray(op?.paths) && op.paths.length <= LIMIT && op.paths.every(validWorkPath)+ && integer(op.order) && op.order <= Number(r?.sequence) && stamp(op.at) && typeof op.createsPr === 'boolean'+ && (op.children === undefined || Array.isArray(op.children) && op.children.length <= 32+ && op.children.every(child => operation(child?.operation, depth + 1) && (child.output === undefined+ || integer(child.output.block) && child.output.block < 32+ && (child.output.index === undefined || integer(child.output.index) && child.output.index < 32)+ && (child.output.settled === undefined || typeof child.output.settled === 'boolean'))))return !!r && (r.context === null || validWorkPath(r.context)) && integer(r.sequence) && integer(r.latest)- && Number(r.latest) <= Number(r.sequence) && locations(r.current) && locations(r.locations)+ && Number(r.latest) <= Number(r.sequence) && integer(r.currentOrder) && Number(r.currentOrder) <= Number(r.sequence)+ && integer(r.failedOrder) && Number(r.failedOrder) <= Number(r.sequence) && locations(r.current) && locations(r.locations)&& Array.isArray(r.pullRequests) && r.pullRequests.length <= LIMIT && r.pullRequests.every(p =>validPullRequestUrl(p?.url) && (p.cwd === null || validWorkPath(p.cwd)) && stamp(p?.at))&& [r.pending, r.running].every(operations => !!object(operations) && Object.keys(operations as object).length <= LIMIT- && Object.entries(operations as Record<string, Operation>).every(([id, op]) => /^[a-f0-9]{64}$/.test(id)- && Array.isArray(op?.paths) && op.paths.length <= LIMIT && op.paths.every(validWorkPath)- && integer(op.order) && op.order <= Number(r.sequence) && stamp(op.at) && typeof op.createsPr === 'boolean'))+ && Object.entries(operations as Record<string, Operation>).every(([id, op]) => /^[a-f0-9]{64}$/.test(id) && operation(op)))&& Array.isArray(r.completed) && r.completed.length <= RECEIPTS && r.completed.every(id => /^[a-f0-9]{64}$/.test(id))&& typeof r.uncertain === 'boolean' && typeof r.truncated === 'boolean'}@@ -182,28 +190,48 @@ function operation(name: string, raw: unknown, cwd: string | null): { paths: strreturn ['exec', 'apply_patch'].includes(tool) ? null : undefined}-function begin(state: SessionWorkLedger, id: unknown, name: unknown, input: unknown, cwd: string | null, at: string): void {- if (typeof id !== 'string' || typeof name !== 'string') return- const key = hash(id)- if (state.pending[key] || state.completed.includes(key)) return+function prepare(state: SessionWorkLedger, name: string, input: unknown, cwd: string | null, at: string,+ order?: number): Operation | null {const [tool, raw] = unwrap(name.replace(/^functions\./, ''), parse(input))const args = object(raw)const continuation = tool === 'write_stdin' && (typeof args?.session_id === 'number' || typeof args?.session_id === 'string')? hash(`process:${args.session_id}`) : tool === 'wait' && typeof args?.cell_id === 'string' ? hash(`cell:${args.cell_id}`) : nullif (continuation && state.running[continuation]) {- if (Object.keys(state.pending).length >= LIMIT) { state.uncertain = true; state.truncated = true; return }const running = state.running[continuation]delete state.running[continuation]// Input could change an interactive shell's directory. Only passive waits confirm an operation.- state.pending[key] = args?.terminate === true || typeof args?.chars === 'string' && args.chars.length > 0- ? { ...running, paths: [], createsPr: false } : running- return+ return args?.terminate === true || typeof args?.chars === 'string' && args.chars.length > 0+ ? { at: running.at, order: running.order, paths: [], createsPr: false } : running}const found = continuation ? null : operation(name, input, cwd)- if (found === undefined) return- const order = ++state.sequence+ if (found === undefined) return null+ return { paths: found?.paths ?? [], createsPr: found?.createsPr ?? false, order: order ?? ++state.sequence, at }+}++function begin(state: SessionWorkLedger, id: unknown, name: unknown, input: unknown, cwd: string | null, at: string): void {+ if (typeof id !== 'string' || typeof name !== 'string') return+ const key = hash(id)+ if (state.pending[key] || state.completed.includes(key)) returnif (Object.keys(state.pending).length >= LIMIT) { state.uncertain = true; state.truncated = true; return }- state.pending[key] = { paths: found?.paths ?? [], createsPr: found?.createsPr ?? false, order, at }+ const raw = parse(input)+ const calls = name.replace(/^functions\./, '') === 'exec' && typeof raw === 'string' ? literalToolCalls(raw) : null+ if (calls) {+ const orders = new Map<number, number>()+ const children: NonNullable<Operation['children']> = []+ for (const call of calls) {+ const order = orders.get(call.group) ?? state.sequence + 1+ const op = prepare(state, call.name, call.input, cwd, at, order)+ if (op) {+ state.sequence = Math.max(state.sequence, order)+ orders.set(call.group, order)+ children.push({ operation: op, ...(call.output ? { output: call.output } : {}) })+ }+ }+ if (children.length) state.pending[key] = { paths: [], at, order: state.sequence, createsPr: false, children }+ } else {+ const op = prepare(state, name, input, cwd, at)+ if (op) state.pending[key] = op+ }}function outputText(raw: unknown): string {@@ -220,7 +248,42 @@ function finish(state: SessionWorkLedger, id: unknown, raw: unknown, failed: boodelete state.pending[key]state.completed.push(key)if (state.completed.length > RECEIPTS) { state.completed.shift(); state.truncated = true }+ finishOperation(state, op, raw, failed, receipt)+}++/** Codex stores each text(...) output as a separate input_text block. Joining those JSON objects+ * destroys their boundaries and loses yielded process ids, exit codes and PR creation receipts. */+function outputBlocks(raw: unknown): unknown[] {+ const blocks = Array.isArray(raw) ? raw.map(row => object(row)?.text).filter((row): row is string => typeof row === 'string')+ : [typeof raw === 'string' ? raw : JSON.stringify(raw) ?? '']+ return blocks.map(text => text.replace(/^Script completed[\s\S]*?\nOutput:\n/, '').trim())+ .filter(text => text && !/^Script running with cell ID/.test(text)).map(parse)+}++function finishOperation(state: SessionWorkLedger, op: Operation, raw: unknown, failed: boolean, receipt?: unknown): void {let text = outputText(raw)+ if (op.children) {+ const blocks = outputBlocks(raw)+ const cell = /Script running with cell ID ([\w-]+)/.exec(text)?.[1]+ const remaining: NonNullable<Operation['children']> = []+ for (const child of op.children) {+ const slot = child.output+ if (cell && slot && slot.block >= blocks.length) {+ remaining.push({ ...child, output: { ...slot, block: slot.block - blocks.length } }); continue+ }+ let value = slot ? blocks[slot.block] : undefined+ const row = object(value)+ const invalid = !slot || value === undefined || slot.index !== undefined && row?.i !== slot.index+ || slot.settled && row?.status !== 'fulfilled'+ if (slot?.settled) value = row?.value+ finishOperation(state, child.operation, value, failed || !!invalid)+ }+ if (cell && remaining.length) {+ if (Object.keys(state.running).length < LIMIT) state.running[hash(`cell:${cell}`)] = { ...op, children: remaining }+ else { state.uncertain = true; state.truncated = true }+ }+ return+ }const wrapper = /^Script completed[\s\S]*?\nOutput:\n([\s\S]*)$/.exec(text)if (wrapper) text = wrapper[1]const result = object(parse(text)) ?? object(raw)@@ -240,11 +303,16 @@ function finish(state: SessionWorkLedger, id: unknown, raw: unknown, failed: booif (Object.keys(state.running).length < LIMIT) state.running[running] = opelse state.truncated = true}- if (op.order >= state.latest) {- state.latest = op.order- state.current = unsuccessful ? [] : op.paths.map(cwd => ({ cwd, at: op.at }))- state.uncertain = unsuccessful || !op.paths.length+ state.latest = Math.max(state.latest, op.order)+ if ((!running && unsuccessful) || !op.paths.length) state.failedOrder = Math.max(state.failedOrder, op.order)+ if (!unsuccessful && op.paths.length && op.order >= state.currentOrder) {+ // Keep the last successful location through failures, pending work and unsupported scripts.+ // Calls in one parallel group share an order, so several worktrees stay explicitly multiple.+ const previous = op.order === state.currentOrder ? state.current : []+ state.currentOrder = op.order+ state.current = [...previous, ...op.paths.filter(cwd => !previous.some(row => row.cwd === cwd)).map(cwd => ({ cwd, at: op.at }))].slice(0, LIMIT)}+ state.uncertain = state.currentOrder < state.latest || state.failedOrder === state.latestif (unsuccessful) returnfor (const cwd of op.paths) {const old = state.locations.find(p => p.cwd === cwd)diff --git a/cli/src/lib/sessionWorkCache.spec.ts b/cli/src/lib/sessionWorkCache.spec.tsindex 15bad19f8..f6c9ebdda 100644--- a/cli/src/lib/sessionWorkCache.spec.ts+++ b/cli/src/lib/sessionWorkCache.spec.ts@@ -75,11 +75,39 @@ describe('work evidence in the incremental transcript cache', () => {expect(await read()).toBeNull()})- it('rebuilds an older cache to recover work associations', async () => {+ it.each([2, 3])('rebuilds a version %s cache to recover work associations', async version => {await writeFile(target.transcriptPath!, lines(receipt('12'))); await read()const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])- const stored = JSON.parse(await readFile(file, 'utf8')); stored.version = 2; delete stored.work+ const stored = JSON.parse(await readFile(file, 'utf8')); stored.version = version; delete stored.workawait writeFile(file, JSON.stringify(stored)); cache.dispose(); cache = open()expect((await read())?.work?.current[0]?.cwd).toBe('/ship-hn/tui')})++ it('replays v3 code-mode history once to recover the already-created PR', async () => {+ target.engine = 'codex'; target.cwd = '/workspace/happy-owl'+ const recorded = await readFile(new URL('./fixtures/session-work-codex.jsonl', import.meta.url), 'utf8')+ await writeFile(target.transcriptPath!, recorded)+ expect((await read())?.work?.pullRequests[0]?.url).toBe('https://github.com/acme/app/pull/397')+ const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])+ const stored = JSON.parse(await readFile(file, 'utf8'))+ stored.version = 3; stored.work.current = []; stored.work.pullRequests = []; stored.work.uncertain = true+ await writeFile(file, JSON.stringify(stored)); cache.dispose(); cache = open()+ expect((await read())?.work?.pullRequests[0]?.url).toBe('https://github.com/acme/app/pull/397')+ const afterReplay = bytes+ cache.dispose(); cache = open()+ expect((await read())?.work?.current[0]?.cwd).toBe('/workspace/happy-owl')+ expect(bytes).toBe(afterReplay)+ })++ it('preserves validated v3 history whose receipts have already been compacted away', async () => {+ await writeFile(target.transcriptPath!, lines(receipt('12'))); await read()+ const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])+ const stored = JSON.parse(await readFile(file, 'utf8')); stored.version = 3+ delete stored.work.currentOrder; delete stored.work.failedOrder+ await writeFile(file, JSON.stringify(stored))+ await writeFile(target.transcriptPath!, lines([{ type: 'user', text: 'compacted' }]))+ cache.dispose(); cache = open()+ expect((await read())?.work).toMatchObject({ current: [], uncertain: true,+ pullRequests: [{ url: 'https://github.com/acme/app/pull/12' }] })+ })})diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex 05c9684d0..cff5c7395 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -104,11 +104,11 @@ shared app bar. A dependent viewer uses its owner's context. Keep internalworktree paths and machinery out of everyday labels.Machine opens the shared picker scoped to that machine. Project opens its harnesses across-known checkouts and machines. With session Git context, Branch opens Work details:-current observed checkout, launch workspace, observed branches and PR history.+known checkouts and machines. With session Git context, Branch opens Branches and pull requests: checked-out and recorded branches,+with PR history. Temporary checkout paths stay out of these labels and details.Older daemons keep exact-branch project search. Hide detached commit hashes from-the bar. Ambiguous or unavailable work is plain context text, without a branch-symbol. These are navigation actions; they do not check out a branch.+the bar. Multiple branches or unavailable Git data use plain context text, without a+branch symbol. These are navigation actions; they do not check out a branch.The PR label opens that PR. Each field gets its own accessible link, tooltip, andthe shared hover treatment, including in joined Agnoster segments.diff --git a/desktop/lib/core/agent_git_context.dart b/desktop/lib/core/agent_git_context.dartindex b8f32c735..03985b57e 100644--- a/desktop/lib/core/agent_git_context.dart+++ b/desktop/lib/core/agent_git_context.dart@@ -45,6 +45,14 @@ typedef AgentWorkPr = ({String? title,String? headBranch,String? baseBranch,+ String? headRepository,+});++typedef AgentBranchRow = ({+ String branch,+ String? repository,+ bool checkedOut,+ List<AgentWorkPr> pullRequests,});/// Display evidence from the owning machine. It never changes launch/resume cwd.@@ -52,7 +60,9 @@ class AgentGitContext {const AgentGitContext({required this.state,this.current,+ this.checkouts,this.observedAt,+ this.activityUncertain = false,this.locations = const [],this.branches = const [],this.pullRequests = const [],@@ -62,7 +72,9 @@ class AgentGitContext {});final String state;final AgentProject? current;+ final List<AgentProject>? checkouts;final DateTime? observedAt;+ final bool activityUncertain;final List<AgentWorkLocation> locations;final List<AgentWorkBranch> branches;final List<AgentWorkPr> pullRequests;@@ -70,20 +82,59 @@ class AgentGitContext {final String? epoch;final int revision;- String? get branchLabel => switch (state) {- 'multiple' => 'Multiple workspaces',- 'uncertain' => 'Work location unknown',- 'unavailable' => 'Workspace unavailable',- _ =>- current?.shownBranch ?? (current?.detached == true ? 'Detached' : null),- };+ List<AgentProject> get checkedOut => checkouts ?? [?current];++ /// Repository + branch is the visible identity. Paths only disambiguate local+ /// repositories without a remote; temporary folder names never become labels.+ List<AgentBranchRow> get branchRows {+ final rows = <(String, String), AgentBranchRow>{};+ void add(String branch, String? repository, String local, bool checkedOut) {+ final key = (repository ?? local, branch);+ final previous = rows[key];+ rows[key] = (+ branch: branch,+ repository: repository,+ checkedOut: checkedOut || previous?.checkedOut == true,+ pullRequests: previous?.pullRequests ?? <AgentWorkPr>[],+ );+ }++ for (final project in checkedOut) {+ if (project.shownBranch case final branch?) {+ add(branch, project.remote, project.root ?? project.cwd, true);+ }+ }+ for (final branch in branches) {+ add(branch.branch, branch.remote, branch.cwd, false);+ }+ for (final pr in pullRequests) {+ final branch = pr.headBranch;+ if (branch == null) continue;+ final repository =+ 'github.com/${pr.headRepository ?? pr.url.pathSegments.take(2).join('/')}'+ .toLowerCase();+ add(branch, repository, pr.cwd ?? '', false);+ rows[(repository, branch)]!.pullRequests.add(pr);+ }+ return rows.values.toList();+ }++ String? get branchLabel {+ final checked = branchRows.where((row) => row.checkedOut).toList();+ if (checked.length > 1) return '${checked.length} branches';+ if (checked.length == 1) return checked.single.branch;+ if (current?.detached == true) return 'Detached';+ if (branchRows.isNotEmpty || state == 'multiple' || state == 'uncertain') {+ return 'Branches';+ }+ return state == 'unavailable' ? 'Git unavailable' : null;+ }String get explanation => switch (state) {- 'observed' => 'Most recently observed work',- 'multiple' => 'The operation used more than one workspace.',- 'uncertain' => 'The current work location could not be confirmed.',- 'unavailable' => 'The observed workspace is no longer readable.',- _ => 'Session workspace; no other work location has been observed.',+ 'multiple' => 'Branches checked out for this session.',+ 'uncertain' || 'unavailable' =>+ 'Git is unavailable. Showing saved branches and pull requests.',+ _ => 'Branch checked out for this session.',};AgentProject? displayProject(AgentProject? launch) {@@ -114,7 +165,9 @@ class AgentGitContext {other is AgentGitContext &&state == other.state &¤t == other.current &&+ listEquals(checkouts, other.checkouts) &&observedAt == other.observedAt &&+ activityUncertain == other.activityUncertain &&truncated == other.truncated &&epoch == other.epoch &&revision == other.revision &&@@ -125,7 +178,9 @@ class AgentGitContext {int get hashCode => Object.hash(state,current,+ checkouts == null ? null : Object.hashAll(checkouts!),observedAt,+ activityUncertain,truncated,epoch,revision,@@ -212,6 +267,9 @@ class AgentGitContext {title: result is Map ? label(result['title'], 512) : null,headBranch: result is Map ? label(result['headBranch'], 256) : null,baseBranch: result is Map ? label(result['baseBranch'], 256) : null,+ headRepository: result is Map+ ? label(result['headRepository'], 512)+ : null,));if (prs.length == 128) break;}@@ -221,7 +279,15 @@ class AgentGitContext {current: const ['workspace', 'observed'].contains(raw['state'])? AgentProject.fromJson(raw['current']): null,+ checkouts: raw['checkouts'] is List+ ? List.unmodifiable(+ rows(raw['checkouts'])+ .map(AgentProject.fromJson)+ .whereType<AgentProject>(),+ )+ : null,observedAt: date(raw['observedAt']),+ activityUncertain: raw['activityUncertain'] == true,locations: List.unmodifiable(locations),branches: List.unmodifiable(branches),pullRequests: List.unmodifiable(prs),diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 193f3138e..29eea4542 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -854,7 +854,7 @@ class _SwarmScreenState extends State<SwarmScreen> {StatusLineField.branch: (label: focused.agent?.gitContext == null? 'Find harnesses on ${focused.branch} in ${focused.projectName}'- : 'Inspect session work · ${focused.branch}\n${focused.detail}',+ : 'Branches and pull requests · ${focused.branch}\n${focused.detail}',onPressed: _shortcutsEnabled? () =>_openContextResource(StatusLineField.branch, focused.pane.id)diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex f07d92644..5905db34c 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -342,7 +342,7 @@ final harnessCommands = <HarnessCommand>[const HarnessCommand('agent.rename', 'Rename Harness', ShortcutGroup.actions),const HarnessCommand('agent.work',- 'Inspect session work',+ 'Branches and pull requests',ShortcutGroup.actions,keywords: ['branch',diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dartindex 49bbd7e02..8f5a4c507 100644--- a/desktop/lib/state/workspace_status.dart+++ b/desktop/lib/state/workspace_status.dart@@ -1,5 +1,4 @@import '../core/models.dart';-import '../core/agent_git_context.dart';import '../shared/theme/prompt_style.dart';import '../shared/theme/status_line_style.dart';import '../widgets/engine_identity.dart';@@ -206,11 +205,7 @@ class WorkspacePaneContext {if (provider.isNotEmpty) provider,machineName,if (project != null) 'Project: ${project.label}',- if (project != null) project.cwd,- ?project?.branchDetail,if (agent?.gitContext case final git?) git.explanation,- if (agent?.gitContext?.observedAt case final at?)- 'Work observed ${localWorkTime(at)}',].join('\n'),);}diff --git a/desktop/lib/widgets/session_work_dialog.dart b/desktop/lib/widgets/session_work_dialog.dartindex f4550dfff..9de88dee9 100644--- a/desktop/lib/widgets/session_work_dialog.dart+++ b/desktop/lib/widgets/session_work_dialog.dart@@ -35,6 +35,7 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {AgentGitContext? _data;bool _loading = false;String? _error;+ int? _nextOffset;int _revision = 0, _visiblePrs = 4;final _unavailable = <String>{};@override@@ -61,6 +62,9 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {_loading = false;final raw = result['gitContext'];if (raw is Map && result['history'] is Map) {+ _nextOffset = result['nextOffset'] is int+ ? result['nextOffset'] as int+ : null;_data =AgentGitContext.fromJson({...raw, 'history': result['history']}) ??_data;@@ -116,8 +120,9 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {color: theme.foreground.withValues(alpha: .65),);final data = _data;- final current =- data?.current ?? (data == null ? widget.agent.project : null);+ final branchRows = data?.branchRows ?? <AgentBranchRow>[];+ final showRepositories =+ branchRows.map((row) => row.repository).toSet().length > 1;final prs = [...?data?.pullRequests];int rank(AgentWorkPr pr) => switch (pr.state) {'Open' || 'Draft' => 0,@@ -185,32 +190,43 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- line('${widget.agent.displayName} · Work'),+ line(+ '${widget.agent.displayName} · Branches and pull requests',+ ),line(widget.online- ? data?.explanation ?? 'Session workspace'- : 'Offline · last known work',+ ? data?.explanation ??+ 'Branches and pull requests for this session.'+ : 'Offline · saved branches and pull requests',dim: true,),SizedBox(height: cell.height),Expanded(child: ListView(children: [- line(- current?.branch ??- data?.branchLabel ??- 'No branch observed',- ),- if (current != null)- line(current.root ?? current.cwd, dim: true),- if (data?.observedAt case final at?)+ line('Branches (${branchRows.length})'),+ if (branchRows.isEmpty)line(- 'Work observed ${localWorkTime(at)}',+ data?.branchLabel ?? 'No branches recorded yet.',dim: true,),- SizedBox(height: cell.height),- line('Launch workspace', dim: true),- line(widget.agent.project?.cwd ?? 'Unavailable'),+ for (final branch in branchRows) ...[+ line(+ '${branch.branch}${branch.checkedOut ? ' · Checked out' : ''}',+ ),+ if (showRepositories && branch.repository != null)+ line(branch.repository!, dim: true),+ if (branch.pullRequests.isNotEmpty)+ line(+ branch.pullRequests+ .map(+ (pr) =>+ '#${pr.url.pathSegments.last} ${pr.state ?? 'State unknown'}',+ )+ .join(' · '),+ dim: true,+ ),+ ],SizedBox(height: cell.height),line('Pull requests (${prs.length})'),if (prs.isEmpty)@@ -276,7 +292,7 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {else if (pr.checkedAt case final at?)line('Checked ${localWorkTime(at)}', dim: true),],- if (prs.length > _visiblePrs)+ if (_nextOffset != null || prs.length > _visiblePrs)Align(alignment: Alignment.centerLeft,child: TerminalTextAction(@@ -284,7 +300,8 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {onPressed: _loading? null: () {- final offset = _visiblePrs;+ final offset =+ _nextOffset ?? _visiblePrs;setState(() => _visiblePrs += 4);if (widget.online) {unawaited(_refresh(offset));@@ -293,30 +310,10 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {),),SizedBox(height: cell.height),- line('Observed branches'),- if (data?.branches.isEmpty ?? true)- line('No branch history observed yet.', dim: true),- for (final branch- in data?.branches ?? <AgentWorkBranch>[]) ...[- line(- '${branch.branch}${branch.cwd == current?.root && branch.branch == current?.branch ? ' · current' : ''}',- ),- line(branch.cwd, dim: true),- ],- if (data?.state == 'multiple' ||- data?.state == 'uncertain' ||- data?.state == 'unavailable') ...[- SizedBox(height: cell.height),- line('Recent work locations'),- for (final location- in data?.locations ?? <AgentWorkLocation>[])- line(location.cwd, dim: true),- ],- SizedBox(height: cell.height),line(data?.truncated == true? 'Older observations are omitted.'- : 'History includes observed work; earlier work may be missing.',+ : 'History includes recorded branches and PRs; earlier activity may be missing.',dim: true,),],diff --git a/desktop/test/session_git_context_test.dart b/desktop/test/session_git_context_test.dartindex 20a2df9a9..5f07b1933 100644--- a/desktop/test/session_git_context_test.dart+++ b/desktop/test/session_git_context_test.dart@@ -92,6 +92,65 @@ Map<String, dynamic> manyPrFixture() {}void main() {+ test('multiple checked-out branches are named without exposing temporary folders', () {+ final fixture = gitFixture();+ final project = fixture['current'] as Map<String, dynamic>;+ fixture['state'] = 'multiple';+ fixture['current'] = null;+ fixture['checkouts'] = [+ project,+ {+ ...project,+ 'cwd': '/other-temp',+ 'root': '/other-temp',+ 'branch': 'hn/nfc',+ },+ {...project, 'cwd': '/duplicate-temp', 'root': '/duplicate-temp'},+ ];+ final context = AgentGitContext.fromJson(fixture)!;+ expect(context.branchLabel, '2 branches');+ expect(context.requestIdentity, isNull);+ expect(context.branchRows.map((b) => b.branch), [+ 'hn/preview-fix',+ 'hn/nfc',+ ]);+ expect(context.branchRows.every((b) => b.checkedOut), isTrue);+ expect(context.explanation, 'Branches checked out for this session.');+ });+ test(+ 'GitHub keeps a merged branch in history after its checkout disappears',+ () {+ final fixture = gitFixture();+ fixture['checkouts'] = <Object>[];+ fixture['current'] = null;+ fixture['state'] = 'unavailable';+ (fixture['history']['branches'] as List).clear();+ fixture['history']['pullRequests'][0]['result'].addAll({+ 'headBranch': 'hn/done',+ 'headRepository': 'acme/app',+ 'state': 'Merged',+ });+ final context = AgentGitContext.fromJson(fixture)!;+ expect(context.branchRows.single.branch, 'hn/done');+ expect(context.branchRows.single.checkedOut, isFalse);+ expect(context.branchRows.single.pullRequests.single.state, 'Merged');+ expect(context.branchLabel, 'Branches');+ },+ );+ test('unknown activity does not override a Git branch or its PR context', () {+ final fresh = AgentGitContext.fromJson(gitFixture())!;+ final saved = AgentGitContext.fromJson({+ ...gitFixture(),+ 'activityUncertain': true,+ })!;+ expect(saved.branchLabel, 'hn/preview-fix');+ expect(saved.explanation, 'Branch checked out for this session.');+ expect(saved.displayProject(null)?.branch, 'hn/preview-fix');+ expect(saved.requestIdentity?['cwd'], '/ship-hn');+ expect(saved.pullRequests.single.state, 'Open');+ expect(saved, isNot(fresh));+ expect(fresh.activityUncertain, isFalse);+ });test('renamed PR aliases do not duplicate the original creation receipt', () {final git = gitFixture();final row = (git['history']['pullRequests'] as List).single as Map;diff --git a/desktop/test/session_work_dialog_test.dart b/desktop/test/session_work_dialog_test.dartindex 2b4d17a08..48f38c063 100644--- a/desktop/test/session_work_dialog_test.dart+++ b/desktop/test/session_work_dialog_test.dart@@ -19,23 +19,84 @@ void main() {(tester) async {final opened = <Uri>[];final git = gitFixture();+ git['activityUncertain'] = true;+ git['history']['pullRequests'][0]['result'].addAll({+ 'headBranch': 'hn/preview-fix',+ 'baseBranch': 'main',+ 'headRepository': 'acme/app',+ 'title': 'Keep complete session previews',+ });+ git['history']['branches'].add({+ 'cwd': '/removed-temporary-checkout',+ 'remote': 'github.com/acme/app',+ 'branch': 'hn/nfc',+ 'at': '2026-09-26T13:00:00Z',+ });+ git['history']['pullRequests'].add({+ 'url': 'https://github.com/acme/app/pull/119',+ 'cwd': '/removed-temporary-checkout',+ 'at': '2026-09-26T13:00:00Z',+ 'checkedAt': '2026-09-27T13:01:00Z',+ 'result': {+ 'status': 'found',+ 'url': 'https://github.com/acme/app/pull/119',+ 'number': 119,+ 'state': 'Merged',+ 'headBranch': 'hn/nfc',+ 'baseBranch': 'main',+ 'headRepository': 'acme/app',+ 'title': 'Keep NFC conversations in order',+ },+ });+ final boundary = GlobalKey();+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1000, 720);+ addTearDown(tester.view.reset);await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SessionWorkDialog(- agent: workAgent(git: git),- read: (_) async => {'gitContext': git, 'history': git['history']},- open: (uri) async {- opened.add(uri);- return true;- },+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SessionWorkDialog(+ agent: workAgent(git: git),+ read: (_) async => {+ 'gitContext': git,+ 'history': git['history'],+ },+ open: (uri) async {+ opened.add(uri);+ return true;+ },+ ),),),),);await tester.pumpAndSettle();- expect(find.text('/silent-beacon'), findsOneWidget);- expect(find.text('hn/preview-fix'), findsOneWidget);+ expect(find.textContaining('/silent-beacon'), findsNothing);+ expect(find.textContaining('/ship-hn'), findsNothing);+ expect(find.text('hn/preview-fix · Checked out'), findsOneWidget);+ expect(find.text('Branch checked out for this session.'), findsOneWidget);+ expect(find.text('Work location unknown'), findsNothing);++ final output = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];+ if (output != null) {+ await tester.runAsync(() async {+ final render =+ boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final picture = await render.toImage(pixelRatio: 1);+ final bytes = await picture.toByteData(+ format: ui.ImageByteFormat.png,+ );+ await Directory(output).create(recursive: true);+ await File('$output/work-last-observed.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ picture.dispose();+ });+ }await tester.tap(find.byKey(const ValueKey('work-pr-https://github.com/acme/app/pull/12'),@@ -123,7 +184,10 @@ void main() {),);await tester.pumpAndSettle();- expect(find.text('Offline · last known work'), findsOneWidget);+ expect(+ find.text('Offline · saved branches and pull requests'),+ findsOneWidget,+ );expect(tester.takeException(), isNull);final output =Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];diff --git a/desktop/test/session_work_navigation_test.dart b/desktop/test/session_work_navigation_test.dartindex c406561f9..aca4a34b2 100644--- a/desktop/test/session_work_navigation_test.dart+++ b/desktop/test/session_work_navigation_test.dart@@ -64,7 +64,7 @@ void main() {}await tester.pumpAndSettle();expect(find.byType(SessionWorkDialog), findsOneWidget);- expect(find.text('/silent-beacon'), findsOneWidget);+ expect(find.textContaining('/silent-beacon'), findsNothing);expect(pane.session, same(session));expect(input, isEmpty);await tester.sendKeyEvent(LogicalKeyboardKey.escape);@@ -85,7 +85,7 @@ void main() {final context = WorkspacePaneContext.focused(app)!;for (final style in StatusLineStyle.values) {final parts = context.format(PromptPrefs(statusStyle: style));- expect(parts.text, contains('Multiple workspaces'));+ expect(parts.text, contains('Branches'));expect(parts.segments.any((s) => s.branchSymbol), isFalse);expect(parts.text, isNot(contains('original')));}diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartindex 94a8e4b2d..1eb724d9a 100644--- a/desktop/test/workspace_status_test.dart+++ b/desktop/test/workspace_status_test.dart@@ -610,7 +610,7 @@ void main() {app.activeSwarm.focusedPaneId = 1;final context = WorkspacePaneContext.focused(app)!;expect(context.text, 'Test host:api (fix)');- expect(context.detail, contains('/worktrees/random-name'));+ expect(context.detail, isNot(contains('/worktrees/random-name')));for (final style in StatusLineStyle.values) {final text = context.format(PromptPrefs(statusStyle: style)).text;expect(text, isNot(contains('random-name')));diff --git a/docs/plans/2026-09-27-session-git-context.md b/docs/plans/2026-09-27-session-git-context.mdindex 3ee331b2a..cd657b523 100644--- a/docs/plans/2026-09-27-session-git-context.md+++ b/docs/plans/2026-09-27-session-git-context.md@@ -1,5 +1,8 @@# Session Git context+The current product and data contract is [Session branches and pull requests](../worktree-pull-requests.md).+The original location-driven design below records the first delivery; it is superseded by the branch-first correction at the end.+## Product contractA session is a durable conversation, a worktree is a checkout, a branch is a@@ -9,6 +12,9 @@ branches and PRs without changing its name or launch directory.The focused context shows the branch read from Git in the most recentlyobserved work location. Its tooltip explains the location and observation time.+Pending, failed or unsupported newer activity retains that confirmed location+with a “last observed” qualifier. Unknown is reserved for sessions without a+confirmed location; an attempted command is never promoted to confirmed work.The session's original directory remains available as “Launch workspace”.If several locations occur in one operation, show “Multiple workspaces” andlet the user inspect them. Never select one by an arbitrary completion order.@@ -103,7 +109,7 @@ for files/index/HEAD rather than independent repositories.a static literal subset without evaluating code. Yielded processes and cellsare correlated with passive waits, including waits after checkpoint reload.- `agentTokenUsage.ts` maintains observations in its existing append-only reader- and v3 private checkpoint. No new transcript scanner or idle watcher is added.+ and v4 private checkpoint. No new transcript scanner or idle watcher is added.- `sessionGitContext.ts` resolves checkout roots and branches. `agentFrame.ts`includes the same additive context on list and push frames; stable daemonversions and client merge rules protect against response reordering.@@ -184,3 +190,51 @@ step; this change does not alter running agents' checkouts.The user-facing behavior and recommended Git workflow are documented in[Session work, branches, and pull requests](../worktree-pull-requests.md).++### Follow-up: recorded Codex batches++The session that created PR #397 exposed a gap in the original tests: its code+mode used multiple calls and emitted each result as a separate text block.+Treating the batch as unknown, and concatenating result blocks before parsing,+lost the yielded PR-creation receipt. A later unsupported call then erased the+last successful location before the daemon projected it into branch history.++The reader now accepts bounded unconditional sequential calls and literal+`Promise.all` / `Promise.allSettled` batches with exact result forwarding. It+keeps each result tied to its command, groups concurrent locations, and follows+partial cell output and subsequent process polls. Dynamic scripts remain+unconfirmed. Failed/unconfirmed work preserves the latest successful location;+desktop and phone qualify that context, including the branch-history marker.+Subfolders under a Git-verified root collapse into one recent workspace.++Version 3 checkpoints replay their available transcript once with the new reader,+retaining validated minimal history whose receipts were already compacted away.+Version 4 restarts resume append-only reads. The recorded regression fixture is+documented in `cli/src/lib/fixtures/session-work-codex.md`.++A read-only replay of this session's 26 MB transcript into temporary caches+resolved its actual `happy-owl` checkout, populated branch history, recovered+PR #397's creation URL, and verified its **Merged** state against GitHub. No+running daemon data was changed by that replay.++## Branch-first correction — September 28++Git, rather than transcript parsing, now supplies checked-out branch facts for+every engine. The assigned checkout is always inspected; validated historical+associations and successful activity add other checkouts. The projection emits+bounded Git snapshots, and history records branches even without tool receipts.+Unknown activity cannot clear a known branch. Multiple checked-out branches+produce a branch count; worktree paths are internal bookkeeping.++The desktop lists checked-out branches, recorded branches and PRs without+launch paths or recent subdirectory lists. GitHub head repository + branch+queries discover PRs from saved branch identities even after local deletion;+PR URL refresh preserves durable merged/closed history. Discovery and URL checks+share bounded pagination and retain actual cache check times.++Regression coverage includes real temporary Git repositories with Claude, Codex+and Grok registry rows and no transcripts, branch switches, another session's+unassociated branch, deleted branches before the first PR lookup, multiple+checkouts, offline preservation and the recorded Codex batch fixture. App tests+cover branch grouping, merged history, paths absent from the view, native and+Flutter navigation without terminal input, narrow layouts and large text.diff --git a/docs/worktree-pull-requests.md b/docs/worktree-pull-requests.mdindex 0c87dcb74..f9da23bda 100644--- a/docs/worktree-pull-requests.md+++ b/docs/worktree-pull-requests.md@@ -1,102 +1,83 @@-# Session work, branches, and pull requests+# Session branches and pull requests-A session has a stable name and launch workspace. Its current Git context follows-the checkout where work was most recently observed. Its PR history records output-across tasks. These identities have different lifetimes and should not be combined-into one permanent branch label.--For example, `hn` can launch in `silent-beacon`, run tools in `ship-hn/tui`, and-work on `hn/nfc` followed by `hn/preview`. The bar shows the branch Git reports for-`ship-hn`, while Work details retain both observed branches and their PRs.-`silent-beacon` remains the launch/resume workspace.+A session can use several branches and create several pull requests. The app+shows those branches and their PRs. Worktree directories are internal references+for locating code, not user-facing identities.## Display and navigation-The focused app bar shows the current named branch and a separate-`#123 Open / Draft / Merged / Closed` link. A dependent viewer uses its owner's-context. Native macOS and Flutter/web use the same formatter. The branch opens-**Work** details; the PR opens GitHub. **Inspect session work** is also available-through the command picker, including when there is no branch. Older daemons-retain their existing branch-scoped search behavior.+The focused bar shows the branch checked out for the session, plus its matching+PR link when there is one. If more than one branch is checked out in associated+checkouts, it shows `2 branches` (or the corresponding count). A historical branch+does not increase this count. A dependent viewer uses its owner's context.-On phone, the session menu offers **Branches and pull requests**. Both surfaces-show the current observation, launch workspace, observed branch history, and PRs-with repository, title, head/base branch, state, and check time. Open/draft work-appears before unknown and completed work. Four PRs are shown initially; Show more-expands the history. Refresh checks a bounded page; each PR keeps its own actual-GitHub check time, including when a cached answer is reused.+Click the branch, or use **Branches and pull requests** in the desktop command picker. Details list checked-out and previously recorded branches, followed+by their PR links, titles, head/base branches and GitHub states. Open and draft+PRs precede completed work. Temporary folder names and subdirectory lists are+not shown. Matching repository and branch names are one visible branch even+when several local copies exist; different repositories remain distinct.-| Evidence | Display |+| Fact | Source || --- | --- |-| Successful tools in one checkout | Its actual current branch |-| Several checkouts in one operation | Multiple workspaces |-| Unresolved execution or unsupported dynamic commands | Work location unknown |-| The observed directory has disappeared | Workspace unavailable |-| No tool observations yet | Session workspace, explicitly labeled in details |-| Machine offline | Last-known observations, labeled offline |--Paths and long values remain inspectable in details and accessibility text.-An unavailable lookup preserves saved PR links and their last-known status.-Nothing on this surface checks out, pushes, merges, deletes, or sends terminal input.-A push is not described as shipped; a merged PR is not evidence that a worktree-can safely be deleted.--## Evidence, privacy, and freshness--The daemon reuses its incremental Claude/Codex transcript reader. It accepts-successful literal shell/file/patch receipts, explicit tool workdirs, guarded-`cd … && …`, `git -C`, and a small static subset of Codex code-mode calls. Yielded-Codex processes/cells stay connected to passive completion polls. Concurrent-operations are ordered by their start, so a slow earlier operation cannot replace-newer work. Pending execution remains uncertain.--It never executes transcript text. Arbitrary scripts, shell substitutions,-interactive input, and unrecognized engine formats cannot establish a location.-Other engines show the registered workspace. History is explicitly partial: it-cannot reconstruct branches that were created and deleted between observations,-or receipts removed before the daemon saw them.--Registry `cwd` and the legacy `project` wire field retain launch semantics.-The additive `gitContext` carries display evidence on both list and push frames.-Daemon-scoped versions reject out-of-order snapshots without changing during-unchanged polling. PR replies are bound to checkout identity; session, machine,-focus, branch and repository changes discard stale replies.--Minimal histories live under `ADAPTER_DATA_DIR/session-git-history`, outside Git-worktrees, in private atomic JSON files. They contain validated locations, branch-observations, PR links and lookup results, never raw commands, credentials or-transcript output. Conversation identity separates histories and inherited fork-receipts are excluded. Deleting a checkout does not delete its history.--Histories retain at most 128 branches and 128 PRs per conversation, with an-explicit truncation message. Git inspection uses the existing 15-second bounded-cache. GitHub results are cached for 60 seconds; the focused badge refreshes once-a minute. Four GitHub/Git reader subprocesses can run simultaneously, with a-bounded queue and deadlines. History refreshes four saved PRs at a time. List-frames never query GitHub. Private paths travel through the existing encrypted-machine RPC.--GitHub lookup uses the owning machine's installed `gh` and existing sign-in.-Current PRs match both head repository and branch, including fork-to-parent PRs;-an open PR wins over older completed work. Every verified match can be retained-in history. Saved URLs resolve independently of deleted branches/worktrees and-follow GitHub repository renames. GitHub Enterprise and arbitrary fork-network-base repositories beyond the origin's parent are outside this reader's scope.--## Branch workflow for agents--Use one topic branch per independently reviewable change and one worktree per-concurrently edited checkout. A session can reuse its worktree for sequential-changes and keep several PRs open. Each active editing process needs its own-checkout; a shared repository still has shared refs, remotes and Git objects.--Start unrelated changes from updated `origin/main`. Deliberately stack dependent-changes, with the intended base branch made explicit. Put review fixes on the-original PR branch. After merging, retire the topic branch and create a new one-for subsequent work. Switch only after saving work and finishing processes that-still use that checkout. Keep PR history as the durable review/output record.--This follows [Git worktree semantics](https://git-scm.com/docs/git-worktree) and-[GitHub flow](https://docs.github.com/en/get-started/using-github/github-flow).-The [implementation plan and verification evidence](plans/2026-09-27-session-git-context.md)-cover the delivery contract and regression cases.+| Session's assigned checkout | Harness's saved launch/resume association |+| Checked-out branch | Git, read directly on the owning machine |+| Branch history | Saved Git observations for this conversation |+| Additional checkout association | Previously verified observations or successful tool activity |+| PR identity and state | GitHub, matched by head repository and branch, or a recorded PR URL |++The Git reader works for every engine, including Claude Code, Codex and Grok.+No transcript or successful tool receipt is required for the assigned branch,+branch switches, branch history, or PR lookup. Unknown, pending and failed tool+activity cannot erase Git facts. Looking up a saved branch can discover its PR+after that local branch or checkout has been deleted.++This is an association record, not an authorship claim. Harness does not attach+every branch in the shared repository to every agent, infer ownership from a+branch prefix or GitHub author, or pretend that the last command's directory is+the session's one current branch. Engine activity can add associations and PR+URLs. Formats the reader cannot understand add nothing and remove nothing.++## Freshness and history++The assigned checkout and previously associated checkouts are read through the+existing 15-second Git cache. An explicit details refresh clears their cached+Git snapshots. One projection inspects at most eight additional locations,+deduplicating resolved checkout roots. Nested checkouts are resolved through+Git rather than assumed to share their parent directory's branch. Incomplete+history is labeled. Short-lived branches switched away between observations,+and activity deleted before it was observed, cannot be reconstructed reliably.++Opening details checks a bounded page of four saved branch identities and four+PR URLs. **Show more** continues discovery and history refresh. GitHub results+are cached for 60 seconds with their actual check times. A failed lookup retains+saved PR state. Offline clients show saved data with an offline label. Deleted+checkouts do not delete branch/PR history. A merged PR is not proof of a release+or permission to delete a checkout.++Histories live in private atomic files under `ADAPTER_DATA_DIR/session-git-history`,+outside the Git checkout, with at most 128 branches and 128 PRs per conversation.+They contain validated locations, branch identities and PR metadata, never raw+commands, credentials or transcript output. Inherited fork receipts are excluded.+The optional Claude/Codex reader accepts bounded literal operations without+executing transcript text. Existing v3 checkpoints replay available transcripts+once to recover missed batched receipts; later v4 reads stay incremental.++Registry `cwd` and the legacy `project` field keep their launch/resume meaning.+The additive `gitContext.checkouts` contains verified Git snapshots. List and+push frames use the same projection and versions. Older clients remain readable;+the desktop groups the snapshots into branch identities. PR badge responses+are bound to the displayed repository, branch and checkout, and stale replies+are discarded. Readers run on the owning machine; private data uses the existing+encrypted machine RPC. No new dependencies or filesystem watchers are required.++This UI only inspects and navigates. It never checks out, pushes, merges,+deletes, or sends input to a terminal.++## Branch workflow++Use one topic branch per independently reviewable change and one isolated+checkout per concurrently editing agent. Sequential tasks can reuse a checkout+and produce several PRs. Start unrelated changes from updated `origin/main`;+make deliberate stacked dependencies explicit. Put review fixes on the original+PR branch. After merging, start a new branch for the next task, once changes are+saved and processes using the checkout have finished.