π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: sync agent git metadata from CLI commands (#16904)
Arvin Xu62baf66fef57
diff --git a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.tsindex 8aec36a479d..b3d562fe50e 100644--- a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts@@ -2,10 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { claudeCodeExecutor, codexExecutor } from '../heteroCli';-const detectMocks = vi.hoisted(() => ({ recordWorktreeAdd: vi.fn() }));+const detectMocks = vi.hoisted(() => ({ recordGitCommandEffects: vi.fn() }));vi.mock('../worktreeDetection', () => ({- recordWorktreeAdd: detectMocks.recordWorktreeAdd,+ recordGitCommandEffects: detectMocks.recordGitCommandEffects,}));const call = (over: Record<string, any> = {}) => ({@@ -30,8 +30,9 @@ describe('heteroCli executors', () => {it('records the worktree for a successful shell call, keyed by the run topic', async () => {await claudeCodeExecutor.onAfterCall!(call());- expect(detectMocks.recordWorktreeAdd).toHaveBeenCalledWith({+ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({command: 'git worktree add /wt',+ resultContent: '',topicId: 't1',});});@@ -44,20 +45,39 @@ describe('heteroCli executors', () => {params: { command: ['git', 'worktree', 'add', '/tmp/my wt'] },}),);- expect(detectMocks.recordWorktreeAdd).toHaveBeenCalledWith({+ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({command: ['git', 'worktree', 'add', '/tmp/my wt'],+ resultContent: '',+ topicId: 't1',+ });+ });++ it('passes shell output through for branch and PR detection', async () => {+ await claudeCodeExecutor.onAfterCall!(+ call({+ params: { command: 'gh pr create --title "fix thing"' },+ result: {+ content: 'https://github.com/lobehub/lobehub/pull/123',+ success: true,+ },+ }),+ );++ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({+ command: 'gh pr create --title "fix thing"',+ resultContent: 'https://github.com/lobehub/lobehub/pull/123',topicId: 't1',});});it('skips a failed call', async () => {await claudeCodeExecutor.onAfterCall!(call({ result: { content: 'fatal', success: false } }));- expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();});it('skips when there is no run topic', async () => {await claudeCodeExecutor.onAfterCall!(call({ topicId: undefined }));- expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();});it('is constrained to the shell tool β ignores other tools', async () => {@@ -65,13 +85,13 @@ describe('heteroCli executors', () => {await claudeCodeExecutor.onAfterCall!(call({ apiName: 'Write', params: { command: 'git worktree add /wt' } }),);- expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();});it('reads only command/cmd, never content', async () => {await claudeCodeExecutor.onAfterCall!(call({ params: { content: 'git worktree add /wt', file_path: 'a.md' } }),);- expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();});});diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.tsindex 84f386f7a34..b6b4f7fc170 100644--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts@@ -1,6 +1,10 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { parseWorktreeAddPath, recordWorktreeAdd } from '../worktreeDetection';+import {+ parseWorktreeAddPath,+ recordGitCommandEffects,+ recordWorktreeAdd,+} from '../worktreeDetection';const chatMocks = vi.hoisted(() => ({topics: {} as Record<string, { metadata?: Record<string, any> }>,@@ -23,6 +27,13 @@ describe('parseWorktreeAddPath', () => {expect(parseWorktreeAddPath('git worktree add wt', '/repo')).toBe('/repo/wt');});+ it('accepts absolute git executable paths', () => {+ expect(parseWorktreeAddPath('/usr/bin/git worktree add ../wt', '/repo')).toBe('/wt');+ expect(parseWorktreeAddPath(['/usr/bin/git', 'worktree', 'add', '/tmp/wt'], '/repo')).toBe(+ '/tmp/wt',+ );+ });+it('keeps an absolute path as-is', () => {expect(parseWorktreeAddPath('git worktree add /tmp/wt', '/repo')).toBe('/tmp/wt');});@@ -89,6 +100,27 @@ describe('recordWorktreeAdd', () => {});});+ it('records the explicit created branch from worktree add', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordWorktreeAdd({+ command: '/usr/bin/git worktree add -b codex/claude-task-notification-callback ../wt HEAD',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: {+ activeWorktree: '/wt',+ branch: 'codex/claude-task-notification-callback',+ isWorktree: true,+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });+it('targets the passed topicId, not the active one', async () => {chatMocks.topics = { other: PR_TOPIC, t1: PR_TOPIC };@@ -124,3 +156,135 @@ describe('recordWorktreeAdd', () => {expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();});});++describe('recordGitCommandEffects', () => {+ it('updates the topic branch when the agent switches branch with git switch', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: {+ branch: 'canary',+ github: {+ pullRequest: {+ number: 1,+ state: 'OPEN',+ title: 'old',+ url: 'https://github.com/lobehub/lobehub/pull/1',+ },+ pullRequestStatus: 'ok',+ },+ },+ path: '/repo',+ repoType: 'github',+ },+ },+ },+ };++ await recordGitCommandEffects({ command: 'git switch fix/topic', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { branch: 'fix/topic' },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('updates the topic branch from confirmed git checkout output', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({+ command: 'git checkout fix/from-output',+ resultContent: "Switched to branch 'fix/from-output'",+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { branch: 'fix/from-output' },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('does not infer ambiguous bare git checkout without confirming output', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({ command: 'git checkout package.json', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('binds a created GitHub PR from gh pr create output', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: { branch: 'fix/topic' },+ path: '/repo',+ repoType: 'github',+ },+ },+ },+ };++ await recordGitCommandEffects({+ command: 'gh pr create --title "Fix topic" --draft',+ resultContent: 'https://github.com/lobehub/lobehub/pull/456',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: {+ branch: 'fix/topic',+ github: {+ pullRequest: {+ isDraft: true,+ number: 456,+ state: 'OPEN',+ title: 'Fix topic',+ url: 'https://github.com/lobehub/lobehub/pull/456',+ },+ pullRequestStatus: 'ok',+ },+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('uses gh pr create --head as the topic branch when present', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({+ command: 'gh pr create --head arvinxx:fix/head-branch --title "Head branch"',+ resultContent: 'Created pull request: https://github.com/lobehub/lobehub/pull/789',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: {+ branch: 'fix/head-branch',+ github: {+ pullRequest: {+ number: 789,+ state: 'OPEN',+ title: 'Head branch',+ url: 'https://github.com/lobehub/lobehub/pull/789',+ },+ pullRequestStatus: 'ok',+ },+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.tsindex feb8d69b974..700062cd3c3 100644--- a/src/store/tool/slices/builtin/executors/heteroCli.ts+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts@@ -1,7 +1,7 @@import type { ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';-import { recordWorktreeAdd } from './worktreeDetection';+import { recordGitCommandEffects } from './worktreeDetection';/*** Hook-only executor for a heterogeneous CLI agent's tool identifier@@ -61,7 +61,7 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {const command = readShellCommand(params);if (command === undefined) return;- await recordWorktreeAdd({ command, topicId });+ await recordGitCommandEffects({ command, resultContent: result.content, topicId });};}diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex d2958dd3ad5..ee7fa7dfb74 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -1,4 +1,4 @@-import type { WorkingDirConfig } from '@lobechat/types';+import type { DeviceGitLinkedPullRequest, WorkingDirConfig } from '@lobechat/types';import { getWorkingDirSourcePath } from '@lobechat/types';import isEqual from 'fast-deep-equal';@@ -6,17 +6,73 @@ import { topicSelectors } from '@/store/chat/selectors';import { getChatStoreState } from '@/store/chat/store';/**- * Detect `git worktree add <path>` in a heterogeneous CLI agent's shell tool call- * and flip the active topic's working-directory state into that worktree.+ * Detect git / gh side effects in a heterogeneous CLI agent's successful shell+ * tool call and mirror them onto the run topic's working-directory metadata.*- * Runs from the `claude-code` / `codex` executor's `onAfterCall` hook (renderer-side,- * fired on `tool_end`). Mirrors what `WorktreeSwitcher` writes on a manual selection:- * only `git.activeWorktree` / `isWorktree` change β the CLI session cwd stays anchored- * to the source repo (hetero anchors cwd to source; the worktree is a record).+ * Runs from the `claude-code` / `codex` executor's `onAfterCall` hook+ * (renderer-side, fired on `tool_end`). The CLI session cwd stays anchored to+ * the source repo; selected worktree / branch / linked PR are topic metadata.*//** Flags on `git worktree add` that consume the following token as their value. */const VALUE_FLAGS = new Set(['-b', '-B', '--reason']);+const BRANCH_VALUE_FLAGS = new Set(['-b', '-B', '--orphan']);+const BRANCH_SWITCH_VALUE_FLAGS = new Set([+ '-b',+ '-B',+ '-c',+ '-C',+ '--create',+ '--force-create',+ '--orphan',+]);+const GIT_BRANCH_SWITCH_SUBCOMMANDS = new Set(['checkout', 'switch']);+const GIT_SWITCH_VALUE_FLAGS = new Set(['--conflict', '--pathspec-from-file']);+const GH_VALUE_FLAGS = new Set([+ '-B',+ '-H',+ '-R',+ '-t',+ '--base',+ '--body',+ '--body-file',+ '--head',+ '--label',+ '--milestone',+ '--project',+ '--recover',+ '--repo',+ '--reviewer',+ '--template',+ '--title',+]);+const GH_GLOBAL_VALUE_FLAGS = new Set([+ '-R',+ '--config-dir',+ '--git-protocol',+ '--hostname',+ '--repo',+]);+const GITHUB_PR_URL_PATTERN = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)/i;+const BRANCH_OUTPUT_PATTERNS = [+ /Switched to (?:a new )?branch ['"]([^'"\n]+)['"]/i,+ /Already on ['"]([^'"\n]+)['"]/i,+ /branch ['"]([^'"\n]+)['"] set up to track/i,+] as const;++interface WorktreeAddInfo {+ branch?: string;+ path: string;+}++interface BranchSwitchInfo {+ branch: string;+}++interface PullRequestCreateInfo {+ branch?: string;+ pullRequest: DeviceGitLinkedPullRequest;+}const stripQuotes = (token: string): string => {if (token.length >= 2) {@@ -32,6 +88,310 @@ const stripQuotes = (token: string): string => {const isAbsolute = (p: string): boolean =>p.startsWith('/') || p.startsWith('~') || /^[A-Z]:[\\/]/i.test(p) || p.startsWith('\\\\');+const getExecutableName = (token: string): string | undefined =>+ stripQuotes(token).split(/[\\/]/).at(-1)?.toLowerCase();++const isGitExecutable = (token: string): boolean => {+ const executable = getExecutableName(token);+ return executable === 'git' || executable === 'git.exe';+};++const isGhExecutable = (token: string): boolean => {+ const executable = getExecutableName(token);+ return executable === 'gh' || executable === 'gh.exe';+};++const normalizeBranch = (branch?: string): string | undefined => {+ const value = branch?.trim();+ if (!value || value === '-') return undefined;+ return value.includes(':') ? value.split(':').at(-1) : value;+};++const getInlineFlagValue = (token: string, flags: readonly string[]): string | undefined => {+ const stripped = stripQuotes(token);+ for (const flag of flags) {+ if (stripped.startsWith(`${flag}=`)) return stripped.slice(flag.length + 1);+ }+};++const getShortFlagValue = (token: string, flags: readonly string[]): string | undefined => {+ const stripped = stripQuotes(token);+ for (const flag of flags) {+ if (flag.length === 2 && stripped.startsWith(flag) && stripped.length > flag.length) {+ return stripped.slice(flag.length);+ }+ }+};++const isAssignment = (t: string) => /^[A-Z_]\w*=/i.test(t);++const consumeCommandPreamble = (tokens: string[]): number => {+ let i = 0;+ while (i < tokens.length && (isAssignment(tokens[i]) || WRAPPERS.has(stripQuotes(tokens[i])))) {+ i += 1;+ }+ return i;+};++const findInCommand = <T>(+ command: string | string[],+ parser: (tokens: string[]) => T | undefined,+): T | undefined => {+ if (Array.isArray(command)) {+ return command.every((t) => typeof t === 'string') ? parser(command) : undefined;+ }+ if (typeof command !== 'string') return undefined;++ for (const segment of command.split(/[\n;|&]/)) {+ const result = parser(tokenize(segment));+ if (result) return result;+ }+};++const parseBranchFromGitOutput = (content?: string): string | undefined => {+ if (!content) return undefined;++ for (const pattern of BRANCH_OUTPUT_PATTERNS) {+ const branch = normalizeBranch(pattern.exec(content)?.[1]);+ if (branch) return branch;+ }+};++const parsePrUrlFromOutput = (content?: string): { number: number; url: string } | undefined => {+ const match = content?.match(GITHUB_PR_URL_PATTERN);+ if (!match) return undefined;++ return { number: Number(match[1]), url: match[0] };+};++const getOptionValue = (tokens: string[], index: number, flags: readonly string[]) => {+ const token = tokens[index];+ const inlineValue = getInlineFlagValue(token, flags) ?? getShortFlagValue(token, flags);+ if (inlineValue !== undefined) return { value: stripQuotes(inlineValue) };+ if (flags.includes(stripQuotes(token))) {+ return { skipNext: true, value: stripQuotes(tokens[index + 1] ?? '') };+ }+ return {};+};++const parseGitSubcommand = (+ tokens: string[],+ cwd?: string,+): { args: string[]; baseCwd?: string; subcommand: string } | undefined => {+ let i = consumeCommandPreamble(tokens);+ if (!isGitExecutable(tokens[i] ?? '')) return undefined;+ i += 1;++ let baseCwd = cwd;+ while (i < tokens.length && tokens[i].startsWith('-')) {+ if (tokens[i] === '-C') {+ const dir = stripQuotes(tokens[i + 1] ?? '');+ if (dir) baseCwd = resolveWorktreePath(dir, baseCwd);+ i += 2;+ } else if (GIT_VALUE_OPTS.has(tokens[i])) {+ i += 2;+ } else {+ i += 1;+ }+ }++ const subcommand = stripQuotes(tokens[i] ?? '');+ if (!subcommand) return undefined;++ return { args: tokens.slice(i + 1), baseCwd, subcommand };+};++const parseGitBranchSwitchTokens = (tokens: string[]): BranchSwitchInfo | undefined => {+ const git = parseGitSubcommand(tokens);+ if (!git || !GIT_BRANCH_SWITCH_SUBCOMMANDS.has(git.subcommand)) return undefined;++ let branch: string | undefined;+ for (let i = 0; i < git.args.length; i += 1) {+ const token = git.args[i];+ const branchFlag = getOptionValue(git.args, i, [...BRANCH_SWITCH_VALUE_FLAGS]);+ if (branchFlag.value) {+ branch = normalizeBranch(branchFlag.value);+ break;+ }+ if (branchFlag.skipNext) {+ i += 1;+ continue;+ }++ const valueFlag = getOptionValue(git.args, i, [...GIT_SWITCH_VALUE_FLAGS]);+ if (valueFlag.skipNext) {+ i += 1;+ continue;+ }+ if (token === '--') break;+ if (token.startsWith('-')) continue;++ // `git checkout <name>` is path-or-branch ambiguous. Use command-only+ // inference only for `git switch <branch>`, whose operand is a branch.+ if (git.subcommand === 'switch') branch = normalizeBranch(token);+ break;+ }++ return branch ? { branch } : undefined;+};++const isGitBranchSwitchCommand = (tokens: string[]): boolean | undefined => {+ const git = parseGitSubcommand(tokens);+ return git && GIT_BRANCH_SWITCH_SUBCOMMANDS.has(git.subcommand) ? true : undefined;+};++const parseGitBranchSwitch = (+ command: string | string[],+ resultContent?: string,+): BranchSwitchInfo | undefined => {+ const outputBranch = parseBranchFromGitOutput(resultContent);+ if (outputBranch && findInCommand(command, isGitBranchSwitchCommand)) {+ return { branch: outputBranch };+ }++ return findInCommand(command, parseGitBranchSwitchTokens);+};++const parseGhPrCreateTokens = (+ tokens: string[],+ resultContent?: string,+): PullRequestCreateInfo | undefined => {+ const prUrl = parsePrUrlFromOutput(resultContent);+ if (!prUrl) return undefined;++ let i = consumeCommandPreamble(tokens);+ if (!isGhExecutable(tokens[i] ?? '')) return undefined;+ i += 1;++ while (i < tokens.length && tokens[i].startsWith('-')) {+ if (GH_GLOBAL_VALUE_FLAGS.has(stripQuotes(tokens[i]))) i += 2;+ else i += 1;+ }++ if (stripQuotes(tokens[i] ?? '') !== 'pr') return undefined;+ i += 1;+ if (stripQuotes(tokens[i] ?? '') !== 'create') return undefined;+ i += 1;++ let branch: string | undefined;+ let isDraft = false;+ let title: string | undefined;+ for (; i < tokens.length; i += 1) {+ const token = stripQuotes(tokens[i]);+ if (token === '--draft') {+ isDraft = true;+ continue;+ }++ const titleValue = getOptionValue(tokens, i, ['-t', '--title']);+ if (titleValue.value) {+ title = titleValue.value;+ if (titleValue.skipNext) i += 1;+ continue;+ }++ const headValue = getOptionValue(tokens, i, ['-H', '--head']);+ if (headValue.value) {+ branch = normalizeBranch(headValue.value) ?? branch;+ if (headValue.skipNext) i += 1;+ continue;+ }++ if (GH_VALUE_FLAGS.has(token)) {+ i += 1;+ continue;+ }+ }++ return {+ branch,+ pullRequest: {+ ...(isDraft ? { isDraft: true } : {}),+ number: prUrl.number,+ state: 'OPEN',+ title: title || `PR #${prUrl.number}`,+ url: prUrl.url,+ },+ };+};++const parseGhPrCreate = (+ command: string | string[],+ resultContent?: string,+): PullRequestCreateInfo | undefined =>+ findInCommand(command, (tokens) => parseGhPrCreateTokens(tokens, resultContent));++const applyBranchToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ branch: string,+): WorkingDirConfig => {+ const branchChanged = currentConfig?.git?.branch !== branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ branch,+ };++ delete git.detached;+ if (branchChanged) delete git.github;++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};++const applyPullRequestToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ info: PullRequestCreateInfo,+): WorkingDirConfig => {+ const branch = info.branch ?? currentConfig?.git?.branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ ...(branch ? { branch } : {}),+ github: {+ pullRequest: info.pullRequest,+ pullRequestStatus: 'ok',+ },+ };++ delete git.detached;++ return {+ ...currentConfig,+ git,+ path: source,+ repoType: 'github',+ };+};++const applyWorktreeAddToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ info: WorktreeAddInfo,+): WorkingDirConfig => {+ const branchChanged = !!info.branch && currentConfig?.git?.branch !== info.branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ activeWorktree: info.path,+ ...(info.branch ? { branch: info.branch } : {}),+ isWorktree: true,+ };++ if (info.branch) delete git.detached;+ if (branchChanged) delete git.github;++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};+/** Collapse `.`/`..` segments in a POSIX path without touching the filesystem. */const normalizePosix = (p: string): string => {const isAbs = p.startsWith('/');@@ -69,7 +429,6 @@ const GIT_VALUE_OPTS = new Set([]);/** Command wrappers that may precede the real `git` executable. */const WRAPPERS = new Set(['sudo', 'env', 'command', 'nice', 'nohup', 'time']);-const isAssignment = (t: string) => /^[A-Z_]\w*=/i.test(t);/*** If ONE command's tokens are a real `git β¦ worktree add <path>` invocation, return@@ -77,14 +436,14 @@ const isAssignment = (t: string) => /^[A-Z_]\w*=/i.test(t);* Requires the executable to actually be `git` β so `echo git worktree add β¦` or* `rg "git worktree add"` never match.*/-const parseGitWorktreeAddTokens = (tokens: string[], cwd?: string): string | undefined => {+const parseGitWorktreeAddTokens = (tokens: string[], cwd?: string): WorktreeAddInfo | undefined => {let i = 0;// Strip leading `VAR=val` assignments and command wrappers (sudo/env/β¦).while (i < tokens.length && (isAssignment(tokens[i]) || WRAPPERS.has(stripQuotes(tokens[i])))) {i += 1;}- if (stripQuotes(tokens[i] ?? '') !== 'git') return undefined;+ if (!isGitExecutable(tokens[i] ?? '')) return undefined;i += 1;// git global options; `-C <dir>` rebases relative worktree paths.@@ -108,14 +467,39 @@ const parseGitWorktreeAddTokens = (tokens: string[], cwd?: string): string | undi += 1;// First positional after `add` is the worktree path.+ let branch: string | undefined;for (; i < tokens.length; i += 1) {- if (VALUE_FLAGS.has(tokens[i])) {+ const token = tokens[i];+ if (BRANCH_VALUE_FLAGS.has(token)) {+ branch = stripQuotes(tokens[i + 1] ?? '') || branch;i += 1; // skip this flag's valuecontinue;}- if (tokens[i].startsWith('-')) continue; // other flags- const path = stripQuotes(tokens[i]);- if (path) return resolveWorktreePath(path, baseCwd);+ if (VALUE_FLAGS.has(token)) {+ i += 1; // skip this flag's value+ continue;+ }+ if (token.startsWith('-')) continue; // other flags+ const path = stripQuotes(token);+ if (path) return { branch, path: resolveWorktreePath(path, baseCwd) };+ }+ return undefined;+};++const parseWorktreeAddInfo = (+ command: string | string[],+ cwd?: string,+): WorktreeAddInfo | undefined => {+ if (Array.isArray(command)) {+ // Already-tokenized argv β a single command, boundaries preserved.+ return command.every((t) => typeof t === 'string')+ ? parseGitWorktreeAddTokens(command, cwd)+ : undefined;+ }+ if (typeof command !== 'string' || !/\bworktree\s+add\b/.test(command)) return undefined;+ for (const segment of command.split(/[\n;|&]/)) {+ const info = parseGitWorktreeAddTokens(tokenize(segment), cwd);+ if (info) return info;}return undefined;};@@ -133,18 +517,7 @@ export const parseWorktreeAddPath = (command: string | string[],cwd?: string,): string | undefined => {- if (Array.isArray(command)) {- // Already-tokenized argv β a single command, boundaries preserved.- return command.every((t) => typeof t === 'string')- ? parseGitWorktreeAddTokens(command, cwd)- : undefined;- }- if (typeof command !== 'string' || !/\bworktree\s+add\b/.test(command)) return undefined;- for (const segment of command.split(/[\n;|&]/)) {- const path = parseGitWorktreeAddTokens(tokenize(segment), cwd);- if (path) return path;- }- return undefined;+ return parseWorktreeAddInfo(command, cwd)?.path;};/**@@ -165,20 +538,51 @@ export const recordWorktreeAdd = async (params: {const currentConfig = topic?.metadata?.workingDirectoryConfig;const source = getWorkingDirSourcePath(currentConfig) ?? topic?.metadata?.workingDirectory;- const worktreePath = parseWorktreeAddPath(command, source);+ const worktreeInfo = parseWorktreeAddInfo(command, source);+ const worktreePath = worktreeInfo?.path;if (!worktreePath || !source || worktreePath === source) return;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- activeWorktree: worktreePath,- isWorktree: true,- };- const nextConfig: WorkingDirConfig = {- ...currentConfig,- git,- path: source,- ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),- };+ const nextConfig = applyWorktreeAddToConfig(currentConfig, source, worktreeInfo);++ if (isEqual(currentConfig, nextConfig)) return;+ await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });+};++/**+ * Record successful heterogeneous CLI shell side effects onto the run topic:+ * - `git worktree add` selects the created worktree and explicit branch.+ * - `git switch` / confirmed `git checkout` updates the branch snapshot.+ * - `gh pr create` binds the created PR URL to the topic.+ */+export const recordGitCommandEffects = async (params: {+ command: string | string[];+ resultContent?: string;+ topicId: string;+}): Promise<void> => {+ const { command, resultContent, topicId } = params;+ const state = getChatStoreState();++ const topic = topicSelectors.getTopicById(topicId)(state);+ const currentConfig = topic?.metadata?.workingDirectoryConfig;+ const source = getWorkingDirSourcePath(currentConfig) ?? topic?.metadata?.workingDirectory;+ if (!source) return;++ let nextConfig = currentConfig;++ const worktreeInfo = parseWorktreeAddInfo(command, source);+ if (worktreeInfo?.path && worktreeInfo.path !== source) {+ nextConfig = applyWorktreeAddToConfig(nextConfig, source, worktreeInfo);+ }++ const branchSwitch = parseGitBranchSwitch(command, resultContent);+ if (branchSwitch) {+ nextConfig = applyBranchToConfig(nextConfig, source, branchSwitch.branch);+ }++ const prCreate = parseGhPrCreate(command, resultContent);+ if (prCreate) {+ nextConfig = applyPullRequestToConfig(nextConfig, source, prCreate);+ }if (isEqual(currentConfig, nextConfig)) return;await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });