typeclaw 0.48.5 → 0.48.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.5",
3
+ "version": "0.48.6",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -1038,7 +1038,7 @@ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
1038
1038
 
1039
1039
  function resolveExposableBashEnvNames(agentDir: string): { exposable: string[]; withheld: string[] } {
1040
1040
  const declaredEnv = readEnvFile(agentDir)
1041
- const exposable = resolveExposableEnvNames(declaredEnv)
1041
+ const exposable = resolveExposableEnvNames(declaredEnv, process.env)
1042
1042
  const exposableSet = new Set(exposable)
1043
1043
  const withheld = [...declaredEnv]
1044
1044
  .filter(([name, value]) => value.length > 0 && !exposableSet.has(name))
@@ -14,6 +14,9 @@ type PostGithubReviewDetails = {
14
14
  ok: boolean
15
15
  error?: string
16
16
  code?: string
17
+ fallback?: 'comment'
18
+ messageId?: string
19
+ messageIds?: readonly string[]
17
20
  reviewId?: number
18
21
  state?: string
19
22
  downgraded?: boolean
@@ -63,8 +66,32 @@ export function createPostGithubReviewTool(options: {
63
66
  workspace: origin.workspace,
64
67
  prNumber,
65
68
  verdict,
69
+ retainDuplicateLease: params.event === 'REQUEST_CHANGES',
66
70
  })
67
- if (blocked !== null) return denied(logger, blocked.reason)
71
+ if (blocked !== null) {
72
+ if (
73
+ params.event === 'REQUEST_CHANGES' &&
74
+ blocked.kind === 'duplicate' &&
75
+ blocked.duplicateSource === 'standing'
76
+ ) {
77
+ try {
78
+ return await postDuplicateRequestChangesComment({
79
+ router,
80
+ origin,
81
+ sessionId,
82
+ prNumber,
83
+ body: params.body,
84
+ comments: (params.comments ?? []).map(toReviewFinding),
85
+ logger,
86
+ })
87
+ } finally {
88
+ if (blocked.leaseRetained === true) {
89
+ await verdictGuard.release({ callId: coordinationCallId, succeeded: false })
90
+ }
91
+ }
92
+ }
93
+ return denied(logger, blocked.reason)
94
+ }
68
95
  }
69
96
  const request: SubmitReviewRequest = {
70
97
  adapter: 'github',
@@ -113,6 +140,79 @@ export function createPostGithubReviewTool(options: {
113
140
  })
114
141
  }
115
142
 
143
+ async function postDuplicateRequestChangesComment(args: {
144
+ router: ChannelRouter
145
+ origin: ChannelReplyOrigin
146
+ sessionId: string
147
+ prNumber: number
148
+ body: string
149
+ comments: readonly ReviewFinding[]
150
+ logger: ChannelToolLogger
151
+ }) {
152
+ const result = await args.router.send(
153
+ {
154
+ adapter: 'github',
155
+ workspace: args.origin.workspace,
156
+ chat: args.origin.chat,
157
+ thread: null,
158
+ text: renderFallbackComment(args.body, args.comments),
159
+ },
160
+ { accountingTarget: args.origin },
161
+ )
162
+ if (!result.ok) return denied(args.logger, result.error, result.code)
163
+
164
+ recordReviewOutput({
165
+ sessionId: args.sessionId,
166
+ workspace: args.origin.workspace,
167
+ prNumber: args.prNumber,
168
+ state: 'COMMENT',
169
+ })
170
+
171
+ const details: PostGithubReviewDetails = {
172
+ ok: true,
173
+ fallback: 'comment',
174
+ ...(result.messageId !== undefined ? { messageId: result.messageId } : {}),
175
+ ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
176
+ }
177
+ return {
178
+ content: [
179
+ {
180
+ type: 'text' as const,
181
+ text: fenceToolResult(
182
+ 'GitHub PR comment posted because the existing CHANGES_REQUESTED review is still active.',
183
+ ),
184
+ },
185
+ ],
186
+ details,
187
+ }
188
+ }
189
+
190
+ function renderFallbackComment(body: string, comments: readonly ReviewFinding[]): string {
191
+ if (comments.length === 0) return body
192
+ return [
193
+ body,
194
+ '',
195
+ '---',
196
+ '',
197
+ ...comments.flatMap((comment) => [`**${markdownCodeSpan(renderLocation(comment))}**`, '', comment.body, '']),
198
+ ]
199
+ .slice(0, -1)
200
+ .join('\n')
201
+ }
202
+
203
+ function renderLocation(comment: ReviewFinding): string {
204
+ const lines = comment.startLine !== undefined ? `${comment.startLine}-${comment.line}` : String(comment.line)
205
+ const side = comment.side === 'LEFT' ? ' (old revision)' : ''
206
+ return `${comment.path.replace(/[\r\n]+/g, ' ')}:${lines}${side}`
207
+ }
208
+
209
+ function markdownCodeSpan(value: string): string {
210
+ const longestRun = Math.max(0, ...Array.from(value.matchAll(/`+/g), (match) => match[0].length))
211
+ const delimiter = '`'.repeat(longestRun + 1)
212
+ const padded = value.startsWith('`') || value.endsWith('`') ? ` ${value} ` : value
213
+ return `${delimiter}${padded}${delimiter}`
214
+ }
215
+
116
216
  function parsePrNumber(chat: string): number | null {
117
217
  const match = /^pr:(\d+)$/.exec(chat)
118
218
  if (match?.[1] === undefined) return null
@@ -745,8 +745,9 @@ async function ensureMemoryFiles(agentDir: string): Promise<void> {
745
745
 
746
746
  // Force-add gitignored memory artifacts so the agent folder's git history
747
747
  // captures consolidation as a single recoverable snapshot. Skips silently when
748
- // the folder is not a git repo or bun is unavailable. Uses the user's global
749
- // git config for authorship.
748
+ // the folder is not a git repo or bun is unavailable. Uses Git's ambient
749
+ // identity: host config in host-stage calls, or the agent repo identity
750
+ // injected into the container process at start.
750
751
  //
751
752
  // After committing, the tracked memory artifacts get the `skip-worktree` index
752
753
  // flag set so manual `git status` / `git diff` ignore future runtime edits.
@@ -23,7 +23,13 @@ export type EffectiveApprovalResolver = (target: {
23
23
  // push-during-review still blocks a same-verdict duplicate for the lag window.
24
24
  export type HeadShaResolver = (target: { workspace: string; prNumber: number }) => Promise<string | null>
25
25
 
26
- export type ApproveBlock = { block: true; reason: string }
26
+ export type ApproveBlock = {
27
+ block: true
28
+ kind: 'concurrent' | 'duplicate'
29
+ reason: string
30
+ duplicateSource?: 'standing' | 'recent'
31
+ leaseRetained?: boolean
32
+ }
27
33
 
28
34
  export type ReviewVerdictGuard = {
29
35
  guard: (args: {
@@ -31,6 +37,7 @@ export type ReviewVerdictGuard = {
31
37
  workspace: string
32
38
  prNumber: number
33
39
  verdict: ReviewVerdict
40
+ retainDuplicateLease?: boolean
34
41
  }) => Promise<ApproveBlock | null>
35
42
  release: (args: { callId: string; succeeded: boolean }) => Promise<void>
36
43
  // Arms the read-after-write lag shield for a verdict that landed WITHOUT a prior
@@ -203,7 +210,7 @@ export function createApproveIdempotencyGuard(deps: {
203
210
  // reclaimable so a crash cannot permanently strand the PR.
204
211
  const held = inFlightByPr.get(key)
205
212
  if (held !== undefined && now() - held.createdAt < LEASE_TTL_MS) {
206
- return { block: true, reason: CONCURRENT_REASON }
213
+ return { block: true, kind: 'concurrent', reason: CONCURRENT_REASON }
207
214
  }
208
215
  const reservation: Reservation = {
209
216
  key,
@@ -232,8 +239,14 @@ export function createApproveIdempotencyGuard(deps: {
232
239
  // now: a blocked command never reaches tool.after, so release() won't run
233
240
  // for this callId. Leaving the lease set would resurrect the strand bug —
234
241
  // the GitHub read is authoritative for the standing case.
235
- releaseReservation(args.callId, reservation)
236
- return { block: true, reason: duplicateReason(args.verdict) }
242
+ if (args.retainDuplicateLease !== true) releaseReservation(args.callId, reservation)
243
+ return {
244
+ block: true,
245
+ kind: 'duplicate',
246
+ reason: duplicateReason(args.verdict),
247
+ duplicateSource: 'standing',
248
+ ...(args.retainDuplicateLease === true ? { leaseRetained: true } : {}),
249
+ }
237
250
  }
238
251
 
239
252
  // Layer 3 — duplicate-review cooldown. A recently-landed SAME verdict on the
@@ -254,7 +267,12 @@ export function createApproveIdempotencyGuard(deps: {
254
267
  recentlyLandedSame(key, args.verdict, headSha, now)
255
268
  ) {
256
269
  releaseReservation(args.callId, reservation)
257
- return { block: true, reason: duplicateReason(args.verdict) }
270
+ return {
271
+ block: true,
272
+ kind: 'duplicate',
273
+ reason: duplicateReason(args.verdict),
274
+ duplicateSource: 'recent',
275
+ }
258
276
  }
259
277
 
260
278
  return null
@@ -1286,6 +1286,10 @@ export type SendSource = 'tool' | 'system'
1286
1286
 
1287
1287
  export type SendOptions = {
1288
1288
  source?: SendSource
1289
+ // Apply tool-send accounting to the originating conversation while delivering
1290
+ // elsewhere. The outbound target remains unchanged; only per-turn cap/dedup,
1291
+ // output bookkeeping, and continuation state use this key.
1292
+ accountingTarget?: ChannelKey
1289
1293
  // Classifies what the human saw, independently of which router path sent it.
1290
1294
  // Tool calls omit this: substantive text is the default, while the shared
1291
1295
  // multilingual willingness detector recognizes status updates. System paths
@@ -4601,14 +4605,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4601
4605
  if (!flood.ok) return { ok: false, error: OUTBOUND_FLOOD_ERROR, code: 'outbound-flood' }
4602
4606
  }
4603
4607
 
4604
- const keyId = channelKeyId({
4608
+ const accountingTarget = opts?.accountingTarget ?? {
4605
4609
  adapter: msg.adapter,
4606
4610
  workspace: msg.workspace,
4607
4611
  chat: msg.chat,
4608
4612
  thread: msg.thread ?? null,
4609
- })
4613
+ }
4614
+ const deliveryMatchesAccounting =
4615
+ accountingTarget.adapter === msg.adapter &&
4616
+ accountingTarget.workspace === msg.workspace &&
4617
+ accountingTarget.chat === msg.chat &&
4618
+ accountingTarget.thread === (msg.thread ?? null)
4619
+ const keyId = channelKeyId(accountingTarget)
4610
4620
  const live = liveSessions.get(keyId)
4611
- const sendKey = consecutiveSendKey(msg.chat, msg.thread)
4621
+ const sendKey = consecutiveSendKey(accountingTarget.chat, accountingTarget.thread)
4612
4622
  // Tool-source sends consume the captured quote candidate exactly
4613
4623
  // once per turn — the intervening-observed check runs HERE against
4614
4624
  // the live buffer so the relevant signal is actual channel chatter
@@ -4618,7 +4628,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4618
4628
  // before the model's own first reply lands. Even when the decision
4619
4629
  // returns null (nothing intervened), the candidate is cleared — a
4620
4630
  // multi-part reply must not retroactively anchor chunk 2.
4621
- if (live && source === 'tool' && live.pendingQuoteCandidate !== null) {
4631
+ if (live && deliveryMatchesAccounting && source === 'tool' && live.pendingQuoteCandidate !== null) {
4622
4632
  const quoteCandidate = refreshQuoteCandidate(live.pendingQuoteCandidate, live.contextBuffer)
4623
4633
  const anchor = decideQuoteAnchor(quoteCandidate, now(), options.configForAdapter(msg.adapter))
4624
4634
  if (anchor !== null) {
@@ -4713,7 +4723,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4713
4723
  // The adapter needs the typing anchor to clear a flat-DM status (msg.thread
4714
4724
  // is null there, so a thread-keyed clear would no-op). Kept off msg.thread
4715
4725
  // to leave reply threading untouched.
4716
- if (live?.currentTurnTypingThread != null && msg.typingThread === undefined) {
4726
+ if (live?.currentTurnTypingThread != null && deliveryMatchesAccounting && msg.typingThread === undefined) {
4717
4727
  msg = { ...msg, typingThread: live.currentTurnTypingThread }
4718
4728
  }
4719
4729
 
@@ -344,10 +344,10 @@ function itemHint(item: ViewerItem): { hint: string } {
344
344
  return { hint: '(no prompt)' }
345
345
  }
346
346
 
347
- function sessionRowLabel(s: SessionSummary): string {
347
+ export function sessionRowLabel(s: SessionSummary): string {
348
348
  const id = shortSessionId(s.sessionId)
349
349
  const label = s.origin === null ? '(unknown origin)' : originLabel(s.origin)
350
- const when = s.live === true ? c.green('live · replying') : c.dim(formatRelative(s.mtimeMs))
350
+ const when = s.live === true ? c.green('live') : c.dim(formatRelative(s.mtimeMs))
351
351
  return `${c.cyan(id)} ${label} ${when}`
352
352
  }
353
353
 
@@ -8,6 +8,7 @@ import { migrateAgentMessengerConfigDir, resolveAgentMessengerConfigPolicy } fro
8
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
9
9
  import { applyBoundGcConfig } from '@/git/bound-gc-config'
10
10
  import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
11
+ import { resolveGitIdentity, type GitIdentity } from '@/git/resolve-identity'
11
12
  import { commitSystemFile as commitSystemFileShared } from '@/git/system-commit'
12
13
  import { send as sendToDaemon } from '@/hostd/client'
13
14
  import { ensureModels as ensureHostModels } from '@/hostd/models'
@@ -92,6 +93,7 @@ export type PlanStartOptions = {
92
93
  // POSIX identity whose ownership bind-mounted runtime writes must retain.
93
94
  // Omitted when unavailable (native Windows and unusual JS hosts).
94
95
  hostIdentity?: { uid: number; gid: number } | null
96
+ gitIdentity?: GitIdentity | null
95
97
  }
96
98
 
97
99
  export type HostDaemonControl = {
@@ -703,6 +705,7 @@ export async function planStart({
703
705
  tuiToken = null,
704
706
  platform = process.platform,
705
707
  hostIdentity = currentHostIdentity(),
708
+ gitIdentity,
706
709
  }: PlanStartOptions): Promise<StartPlan> {
707
710
  const containerName = containerNameFromCwd(cwd)
708
711
  const imageTag = imageTagFromCwd(cwd)
@@ -856,6 +859,19 @@ export async function planStart({
856
859
  if (existsSync(join(cwd, ENV_FILE))) {
857
860
  runArgs.push('--env-file', join(cwd, ENV_FILE))
858
861
  }
862
+ const resolvedGitIdentity = gitIdentity === undefined ? await resolveGitIdentity(cwd) : gitIdentity
863
+ if (resolvedGitIdentity !== null) {
864
+ runArgs.push(
865
+ '-e',
866
+ `GIT_AUTHOR_NAME=${resolvedGitIdentity.name}`,
867
+ '-e',
868
+ `GIT_AUTHOR_EMAIL=${resolvedGitIdentity.email}`,
869
+ '-e',
870
+ `GIT_COMMITTER_NAME=${resolvedGitIdentity.name}`,
871
+ '-e',
872
+ `GIT_COMMITTER_EMAIL=${resolvedGitIdentity.email}`,
873
+ )
874
+ }
859
875
  const agentMessengerPolicy = resolveAgentMessengerConfigPolicy(cwd)
860
876
  if (agentMessengerPolicy.override === null) {
861
877
  runArgs.push('-e', `AGENT_MESSENGER_CONFIG_DIR=${agentMessengerPolicy.containerDir}`)
@@ -0,0 +1,66 @@
1
+ import { resolveAgentGit } from './resolve-agent-git'
2
+ import { runGit } from './run'
3
+
4
+ export type GitIdentity = { name: string; email: string }
5
+
6
+ const GIT_CONFIG_ENV = {
7
+ GIT_CONFIG_GLOBAL: '/dev/null',
8
+ GIT_CONFIG_NOSYSTEM: '1',
9
+ GIT_TERMINAL_PROMPT: '0',
10
+ } as const
11
+
12
+ const GIT_REPOSITORY_ENV_NAMES = new Set([
13
+ 'GIT_COMMON_DIR',
14
+ 'GIT_DIR',
15
+ 'GIT_INDEX_FILE',
16
+ 'GIT_OBJECT_DIRECTORY',
17
+ 'GIT_WORK_TREE',
18
+ ])
19
+
20
+ export async function resolveGitIdentity(cwd: string): Promise<GitIdentity | null> {
21
+ const repo = resolveAgentGit(cwd)
22
+ if (repo === null) return null
23
+
24
+ const values = await readRepositoryIdentity(cwd, repo.gitArgs)
25
+ const name = values.get('user.name')?.at(-1)?.trim() || null
26
+ const email = values.get('user.email')?.at(-1)?.trim() || null
27
+ return name !== null && email !== null ? { name, email } : null
28
+ }
29
+
30
+ async function readRepositoryIdentity(cwd: string, gitArgs: readonly string[]): Promise<Map<string, string[]>> {
31
+ try {
32
+ const result = await runGit(Bun, cwd, [...gitArgs, 'config', '--null', '--get-regexp', '^user\\.(name|email)$'], {
33
+ env: { ...withoutGitOverrides(process.env), ...GIT_CONFIG_ENV },
34
+ })
35
+ if (result.exitCode !== 0) return new Map()
36
+ return parseNullConfigEntries(result.stdout)
37
+ } catch {
38
+ return new Map()
39
+ }
40
+ }
41
+
42
+ function parseNullConfigEntries(output: string): Map<string, string[]> {
43
+ const values = new Map<string, string[]>()
44
+ for (const entry of output.split('\0')) {
45
+ if (entry.length === 0) continue
46
+ const separator = entry.indexOf('\n')
47
+ if (separator < 0) continue
48
+ const key = entry.slice(0, separator)
49
+ const value = entry.slice(separator + 1)
50
+ const existing = values.get(key)
51
+ if (existing === undefined) values.set(key, [value])
52
+ else existing.push(value)
53
+ }
54
+ return values
55
+ }
56
+
57
+ function withoutGitOverrides(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
58
+ return Object.fromEntries(
59
+ Object.entries(env).filter(([name]) => {
60
+ const normalized = name.toUpperCase()
61
+ return !normalized.startsWith('GIT_CONFIG') && !GIT_REPOSITORY_ENV_NAMES.has(normalized)
62
+ }),
63
+ )
64
+ }
65
+
66
+ export const _internal = { withoutGitOverrides }
package/src/git/run.ts CHANGED
@@ -33,10 +33,12 @@ export async function runGit(
33
33
  bun: { spawn: typeof Bun.spawn },
34
34
  cwd: string,
35
35
  args: readonly string[],
36
+ options: { env?: NodeJS.ProcessEnv } = {},
36
37
  ): Promise<RunGitResult> {
37
38
  const proc = bun.spawn({
38
39
  cmd: ['git', ...hooklessGitArgs(args)],
39
40
  cwd,
41
+ env: options.env,
40
42
  stdout: 'pipe',
41
43
  stderr: 'pipe',
42
44
  })
@@ -4,8 +4,8 @@ import { resolveAgentGit } from './resolve-agent-git'
4
4
  // Commits TypeClaw-owned tracked files (.gitignore, package.json,
5
5
  // typeclaw.json) if any are dirty in git. Skips silently when the agent
6
6
  // folder is not a git repo, when Bun is unavailable, or when every named
7
- // file is clean. Uses the user's global git config for authorship —
8
- // TypeClaw does not impersonate the user here.
7
+ // file is clean. Uses Git's ambient identity: host config in host-stage calls,
8
+ // or the agent repo identity injected into the container process at start.
9
9
  //
10
10
  // Accepts a single file or an array; the array form produces a single
11
11
  // atomic commit covering all listed paths (used for migrations that touch
@@ -1,7 +1,5 @@
1
- import type { LiveSessionPayload } from '@/shared'
2
-
3
1
  import type { ViewerItem } from './item'
4
- import { listSessions, type ListSessionsOptions, mergeLiveSessions, type SessionSummary } from './session-list'
2
+ import { listSessions, type ListSessionsOptions, type SessionSummary } from './session-list'
5
3
 
6
4
  export type ListViewerItemsOptions = ListSessionsOptions & {
7
5
  containerRunning: boolean
@@ -16,9 +14,6 @@ export type ListViewerItemsOptions = ListSessionsOptions & {
16
14
  // (most-recent) tui transcript — and any older tui transcript the heuristic
17
15
  // would otherwise promote — must NOT be offered as a writable live row.
18
16
  allowWritable?: boolean
19
- // Registry sessions not yet flushed to disk, fetched by the CLI over the
20
- // /inspect WS. The lib layer stays I/O-free; the caller owns the connection.
21
- liveSessions?: LiveSessionPayload[]
22
17
  }
23
18
 
24
19
  export type ViewerList = {
@@ -34,11 +29,7 @@ export type ViewerList = {
34
29
  // `logs` row is appended last (container stdout, available offline) so it sits
35
30
  // below the divider in the picker.
36
31
  export async function listViewerItems(opts: ListViewerItemsOptions): Promise<ViewerList> {
37
- const diskSessions = await listSessions(opts)
38
- const sessions =
39
- opts.liveSessions !== undefined && opts.liveSessions.length > 0
40
- ? mergeLiveSessions(diskSessions, opts.liveSessions)
41
- : diskSessions
32
+ const sessions = await listSessions(opts)
42
33
  const allowWritable = opts.interactive && opts.allowWritable !== false
43
34
  const writableSessionId = opts.containerRunning && allowWritable ? pickWritableSession(sessions) : null
44
35
 
@@ -14,10 +14,9 @@ export type SessionSummary = {
14
14
  mtimeMs: number
15
15
  origin: MinimalSessionOrigin | null
16
16
  firstPrompt: string | null
17
- // True only for a registry-derived session with no .jsonl on disk yet (a
18
- // reply is in flight). Disk sessions leave this undefined. Selecting one tails
19
- // live-only: streamSessionEvents replays an empty file, then the WS delivers
20
- // events as they happen.
17
+ // True only for a registered session with no .jsonl on disk yet. Registration
18
+ // means the session is warm, not that a reply is currently in flight. Disk
19
+ // sessions leave this undefined.
21
20
  live?: boolean
22
21
  }
23
22
 
@@ -26,6 +25,7 @@ export type ListSessionsOptions = {
26
25
  limit?: number
27
26
  sinceMs?: number
28
27
  onWarn?: (msg: string) => void
28
+ liveSessions?: LiveSessionPayload[]
29
29
  }
30
30
 
31
31
  // pi-coding-agent writes session files as `${ISO_TIMESTAMP}_${SESSION_ID}.jsonl`,
@@ -72,17 +72,23 @@ type StatEntry = { path: string; basename: string; sessionId: string; mtimeMs: n
72
72
  // Split from listSessions so resolveSession can match ids first and peek only the
73
73
  // candidates, instead of reading every file body on disk. Reads no file content.
74
74
  async function statSessionFiles(opts: ListSessionsOptions): Promise<StatEntry[]> {
75
+ return (await scanSessionFiles(opts)).eligible
76
+ }
77
+
78
+ async function scanSessionFiles(
79
+ opts: ListSessionsOptions,
80
+ ): Promise<{ eligible: StatEntry[]; onDiskSessionIds: Set<string> }> {
75
81
  const entries = await readSessionFiles(opts.sessionsDir, opts.onWarn)
76
82
  const withStats = await mapConcurrent(entries, SESSION_IO_CONCURRENCY, async (entry) => {
77
83
  const s = await safeStat(entry.path)
78
84
  if (s === null) return null
79
85
  const mtimeMs = s.mtimeMs
80
- if (opts.sinceMs !== undefined && mtimeMs < opts.sinceMs) return null
81
86
  return { ...entry, mtimeMs }
82
87
  })
83
88
  const valid = withStats.filter((v): v is StatEntry => v !== null)
84
- valid.sort((a, b) => b.mtimeMs - a.mtimeMs)
85
- return valid
89
+ const eligible = opts.sinceMs === undefined ? valid : valid.filter((entry) => entry.mtimeMs >= opts.sinceMs!)
90
+ eligible.sort((a, b) => b.mtimeMs - a.mtimeMs)
91
+ return { eligible, onDiskSessionIds: new Set(valid.map((entry) => entry.sessionId)) }
86
92
  }
87
93
 
88
94
  async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void): Promise<SessionSummary> {
@@ -98,18 +104,25 @@ async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void):
98
104
  }
99
105
 
100
106
  export async function listSessions(opts: ListSessionsOptions): Promise<SessionSummary[]> {
101
- const valid = await statSessionFiles(opts)
102
- const limited = opts.limit !== undefined ? valid.slice(0, opts.limit) : valid
103
- return mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
107
+ const { eligible, onDiskSessionIds } = await scanSessionFiles(opts)
108
+ const limited = opts.limit !== undefined ? eligible.slice(0, opts.limit) : eligible
109
+ const disk = await mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
110
+ if (opts.liveSessions === undefined || opts.liveSessions.length === 0) return disk
111
+ return mergeLiveSessions(disk, opts.liveSessions, { onDiskSessionIds, limit: opts.limit })
104
112
  }
105
113
 
106
114
  // Overlay container-registry sessions onto the disk listing. A live session
107
- // already flushed to disk (post-reply) is dropped from the overlay — the disk
115
+ // already flushed to disk is dropped from the overlay — the disk
108
116
  // summary wins, carrying its real mtime and prompt preview. Only sessions with
109
117
  // no .jsonl yet become synthetic live rows, sorted to the top by registration
110
- // time so an in-flight reply surfaces above settled history.
111
- export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPayload[]): SessionSummary[] {
112
- const onDisk = new Set(disk.map((s) => s.sessionId))
118
+ // time. The final limit applies after merging, so registry-only rows displace
119
+ // older history rather than expanding the picker.
120
+ export function mergeLiveSessions(
121
+ disk: SessionSummary[],
122
+ live: LiveSessionPayload[],
123
+ opts: { onDiskSessionIds?: ReadonlySet<string>; limit?: number } = {},
124
+ ): SessionSummary[] {
125
+ const onDisk = opts.onDiskSessionIds ?? new Set(disk.map((s) => s.sessionId))
113
126
  const liveOnly = live
114
127
  .filter((l) => !onDisk.has(l.sessionId))
115
128
  .map(
@@ -123,7 +136,8 @@ export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPaylo
123
136
  live: true,
124
137
  }),
125
138
  )
126
- return [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
139
+ const merged = [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
140
+ return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged
127
141
  }
128
142
 
129
143
  export type ResolveResult =
@@ -54,6 +54,13 @@ const EXECUTION_CONTROL_ENV_NAMES = new Set<string>([
54
54
 
55
55
  const EXECUTION_CONTROL_ENV_PREFIXES = ['GIT_CONFIG', 'BASH_FUNC_'] as const
56
56
 
57
+ const GIT_IDENTITY_ENV_NAMES = [
58
+ 'GIT_AUTHOR_NAME',
59
+ 'GIT_AUTHOR_EMAIL',
60
+ 'GIT_COMMITTER_NAME',
61
+ 'GIT_COMMITTER_EMAIL',
62
+ ] as const
63
+
57
64
  // Withheld ONLY when the name would compromise sandbox integrity or claim a
58
65
  // host/container-injected runtime token — not for being credential-shaped. `.env`
59
66
  // is the operator's expose-to-the-agent surface: every value they declare there
@@ -66,18 +73,24 @@ function isWithheldEnvName(name: string): boolean {
66
73
  return EXECUTION_CONTROL_ENV_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix))
67
74
  }
68
75
 
69
- // Every name an operator declared in the `.env` FILE with a non-empty value,
70
- // minus the sandbox-integrity/broker withholds. Eligibility is decided from the
71
- // PARSED `.env` value, never process.env: an empty `.env` line (`X=`) is not an
72
- // operator expose-choice even if hydrateChannelEnvFromSecrets later fills
73
- // process.env[X] from secrets.json. The inherited VALUE is still snapshotted
74
- // from process.env at spawn time.
75
- export function resolveExposableEnvNames(declaredEnv: ReadonlyMap<string, string>): string[] {
76
+ // Every non-empty name declared in `.env`, minus sandbox-integrity/broker
77
+ // withholds, plus the four Git identity names that `typeclaw start` resolves
78
+ // from the agent repository and owns in the container environment. No other
79
+ // process.env-only name is eligible: an empty `.env` line (`X=`) remains hidden
80
+ // even if secrets.json hydration later fills process.env[X]. Inherited VALUES
81
+ // are snapshotted from process.env at spawn time.
82
+ export function resolveExposableEnvNames(
83
+ declaredEnv: ReadonlyMap<string, string>,
84
+ runtimeEnv: Readonly<Record<string, string | undefined>> = {},
85
+ ): string[] {
76
86
  const out: string[] = []
77
87
  for (const [name, fileValue] of declaredEnv) {
78
88
  if (fileValue.length === 0) continue
79
89
  if (isWithheldEnvName(name)) continue
80
90
  out.push(name)
81
91
  }
92
+ for (const name of GIT_IDENTITY_ENV_NAMES) {
93
+ if (runtimeEnv[name]?.length && !out.includes(name)) out.push(name)
94
+ }
82
95
  return out
83
96
  }
@@ -115,7 +115,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
115
115
 
116
116
  **The reviewer's `<review>` block is the only source of the verdict and the findings.** You do not review the PR yourself. Between spawning the reviewer and reading its result you do **no analysis of this PR** — do not run `gh pr diff`, do not read the changed files to form an opinion, do not draft a verdict. The reviewer runs on the `deep` model precisely so this judgment is not yours to make on the parent model. If you analyze the diff and post your own assessment while the reviewer is still running, you will post one verdict now and the reviewer's (often different) verdict when it completes — **two contradictory reviews on the same PR**, the exact failure this flow exists to prevent. Wait for the reviewer; post what it returns; nothing before that.
117
117
 
118
- **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
118
+ **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). **Narrow exception:** when `post_github_review` finds that this bot's identical `CHANGES_REQUESTED` verdict is already effective, the tool itself converts the redundant submission into one substantive root PR comment while the existing formal block remains authoritative. This is a successful tool-managed fallback, not permission to replace a failed or invalid formal review manually. If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
119
119
 
120
120
  1. **Minimal intake, then delegate immediately.** Capture only the repo, PR number, current head SHA, exact base OID, authorship, and the prior blocking context needed to identify a re-review. Do not inspect the diff or changed files. Batch the independent metadata/history reads where the tool interface permits.
121
121
 
@@ -185,7 +185,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
185
185
 
186
186
  **Operator approval policy.** If the inbound carries a note that PR approval is disabled (`channels.github.review.approve: false` — the adapter appends "Operator policy: PR approval is disabled for this agent" to the message), you must **not** submit an `APPROVE`. Map an `approve` verdict to `COMMENT` instead: post the same `<summary>` and all inline `comments[]` as a `COMMENT` review, just without the formal approval. `request-changes` and `comment` verdicts are unaffected (they never approve). Absent that note, approval is enabled and the table above applies unchanged.
187
187
 
188
- **Re-review.** If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block — never a top-level PR comment. The clearing mechanics depend on which form the prior block took:
188
+ **Re-review.** If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review. The clearing mechanics depend on which form the prior block took:
189
189
  - **Prior block was a formal `CHANGES_REQUESTED`.** It is sticky: **only** a fresh `APPROVE` from you, or a dismissal of your prior review, clears it. A plain issue comment does **not** clear it, and — critically — **neither does a `COMMENT` review.**
190
190
  - **Prior block was a flat comment** (no formal `CHANGES_REQUESTED` exists). There is no sticky GitHub state to clear, but the obligation is still yours to discharge as a **formal** review so the verdict finally lands as review state: submit `APPROVE` (resolved, approval enabled) or `REQUEST_CHANGES` (not resolved). Do not discharge a flat-comment block with another flat comment — that re-strands the verdict, the original bug.
191
191
 
@@ -218,11 +218,11 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
218
218
  })
219
219
  ```
220
220
 
221
- Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). The tool resolves the head SHA, validates anchors against the complete PR diff, moves out-of-diff findings into the top-level body, enforces approval policy, and verifies the exact returned review id/state. Its successful receipt is proof that the formal review landed. On failure, fix the payload or policy issue and retry; never post a flat comment claiming the review succeeded.
221
+ Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). The tool resolves the head SHA, validates anchors against the complete PR diff, moves out-of-diff findings into the top-level body, enforces approval policy, and verifies the exact returned review id/state. Its successful receipt is proof that the output landed. A receipt with `details.fallback === "comment"` means the prior `CHANGES_REQUESTED` remains live and the new review content landed as one root PR comment; treat that as complete and do not add a `channel_reply`. On failure, fix the payload or policy issue and retry; never post a flat comment claiming the review succeeded.
222
222
 
223
223
  5. **The decoy reviewer is dropped for you — no action needed.** Under **GitHub App** auth, the adapter automatically removes the decoy reviewer from the PR's requested-reviewers list the moment your formal review lands (it reacts to your own `pull_request_review.submitted` webhook). Why this matters: GitHub auto-adds **you** (the App account) to the PR's reviewers when your review posts, but the **decoy** account would otherwise stay pinned as a perpetual "review requested", as if the review never happened. You do **not** need to issue a `DELETE /requested_reviewers` yourself — and you should not, since it would race the adapter's own cleanup. The removal is self-loop-safe: the adapter's `DELETE` is authenticated as the App, so the `review_request_removed` webhook carries your bot actor (`slug[bot]`) as `sender`, which the classifier drops (see "Self-loop safety" below). This is a no-op under **PAT** auth (no decoy) and for **plain-language**/**team** requests (no decoy user was placed). See [GitHub decoy reviewer](/docs/internals/github-decoy-reviewer).
224
224
 
225
- 6. **End the turn with `skip_response`, not a trace reply.** The formal review from step 4 already landed _in this PR_ — it carries the summary, the verdict, and the inline comments. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the review it claims to point at. So once `post_github_review` confirms success, call `skip_response({ reason: "review posted via post_github_review" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** formal review to post — the zero-actionable-findings branch below uses `channel_reply` as the substantive reply.
225
+ 6. **End the turn with `skip_response`, not a trace reply.** The formal review or tool-managed duplicate fallback from step 4 already landed _in this PR_ — it carries the summary, verdict context, and findings. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the output it claims to point at. So once `post_github_review` confirms success, call `skip_response({ reason: "review posted via post_github_review" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** review output to post — the zero-actionable-findings branch below uses `channel_reply` as the substantive reply.
226
226
 
227
227
  ### Zero actionable findings
228
228