typeclaw 0.48.6 → 0.48.8

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.
Files changed (105) hide show
  1. package/auth.schema.json +15 -1
  2. package/package.json +1 -1
  3. package/secrets.schema.json +15 -1
  4. package/src/agent/guard-types.ts +25 -0
  5. package/src/agent/guards.ts +102 -0
  6. package/src/agent/index.ts +33 -3
  7. package/src/agent/live-subagents.ts +14 -0
  8. package/src/agent/multimodal/read-redirect.ts +8 -9
  9. package/src/agent/plugin-tools.ts +283 -148
  10. package/src/agent/provider-error.ts +6 -1
  11. package/src/agent/reload-tool.ts +12 -5
  12. package/src/agent/retry-same-ref.ts +95 -36
  13. package/src/agent/session-origin.ts +13 -1
  14. package/src/agent/system-prompt.ts +14 -3
  15. package/src/agent/todo/continuation-policy.ts +3 -4
  16. package/src/agent/tool-file-safety.ts +36 -13
  17. package/src/agent/tools/channel-reply.ts +39 -2
  18. package/src/agent/tools/channel-send.ts +45 -2
  19. package/src/agent/tools/post-github-review.ts +31 -13
  20. package/src/agent/tools/spawn-subagent.ts +15 -0
  21. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  22. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  23. package/src/agent/turn-runner.ts +23 -19
  24. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  25. package/src/bundled-plugins/backup/subagents.ts +1 -1
  26. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  27. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  28. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  29. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  30. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  31. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  32. package/src/bundled-plugins/github-cli-auth/git-command.ts +231 -30
  33. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  34. package/src/bundled-plugins/github-cli-auth/index.ts +249 -42
  35. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  36. package/src/bundled-plugins/guard/index.ts +2 -25
  37. package/src/bundled-plugins/guard/keys.ts +8 -0
  38. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  39. package/src/bundled-plugins/guard/policy.ts +1 -7
  40. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  41. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  42. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  43. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  44. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  45. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  46. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  47. package/src/bundled-plugins/security/policy.ts +0 -8
  48. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  49. package/src/channels/adapters/discord-bot.ts +2 -1
  50. package/src/channels/adapters/discord-classify.ts +16 -4
  51. package/src/channels/adapters/discord.ts +20 -8
  52. package/src/channels/adapters/github/dedup.ts +37 -8
  53. package/src/channels/adapters/github/inbound.ts +241 -46
  54. package/src/channels/adapters/github/review-state.ts +13 -9
  55. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  56. package/src/channels/adapters/slack-classify.ts +40 -5
  57. package/src/channels/adapters/slack.ts +3 -9
  58. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  59. package/src/channels/adapters/webex-bot.ts +2 -4
  60. package/src/channels/adapters/webex-classify.ts +4 -33
  61. package/src/channels/adapters/webex-format.ts +36 -0
  62. package/src/channels/adapters/webex.ts +2 -4
  63. package/src/channels/continuation-willingness.ts +64 -39
  64. package/src/channels/github-rereview-guard.ts +20 -0
  65. package/src/channels/github-review-turn-ledger.ts +11 -1
  66. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  67. package/src/channels/github-verdict-activity.ts +14 -5
  68. package/src/channels/persistence.ts +89 -5
  69. package/src/channels/router.ts +1223 -225
  70. package/src/channels/types.ts +21 -5
  71. package/src/cli/compose-stats.ts +6 -7
  72. package/src/cli/compose-status.ts +6 -7
  73. package/src/cli/compose-usage.ts +6 -7
  74. package/src/cli/stats.ts +6 -7
  75. package/src/cli/status.ts +7 -8
  76. package/src/cli/ui.ts +4 -4
  77. package/src/container/start.ts +41 -1
  78. package/src/cron/consumer.ts +30 -9
  79. package/src/cron/scheduler.ts +24 -9
  80. package/src/doctor/channel-checks.ts +64 -0
  81. package/src/doctor/report.ts +8 -8
  82. package/src/dreams/render.ts +2 -2
  83. package/src/init/dockerfile.ts +8 -1
  84. package/src/inspect/render.ts +2 -2
  85. package/src/path-safety/real-intended-path.ts +14 -1
  86. package/src/permissions/permissions.ts +10 -2
  87. package/src/permissions/resolve.ts +8 -2
  88. package/src/plugin/core-tool-names.ts +15 -0
  89. package/src/plugin/hooks.ts +37 -3
  90. package/src/plugin/registry.ts +7 -3
  91. package/src/run/index.ts +35 -15
  92. package/src/sandbox/build.ts +19 -3
  93. package/src/sandbox/policy.ts +1 -0
  94. package/src/secrets/export-github-cli-store.ts +158 -0
  95. package/src/secrets/index.ts +19 -1
  96. package/src/secrets/provision-github-cli-store.ts +322 -0
  97. package/src/secrets/schema.ts +13 -7
  98. package/src/secrets/storage.ts +30 -0
  99. package/src/shared/index.ts +2 -0
  100. package/src/shared/style-text.ts +13 -0
  101. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  102. package/src/skills/typeclaw-config/SKILL.md +3 -1
  103. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  104. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  105. package/src/usage/report.ts +3 -3
@@ -31,6 +31,31 @@ case "$1" in
31
31
  *//github.com/*|*//github.com\\'*|*//*@github.com/*|*//*@github.com\\'*) : ;;
32
32
  *) exit 1 ;;
33
33
  esac
34
+ if [ -n "$TYPECLAW_GIT_CREDENTIALS" ]; then
35
+ prompt=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
36
+ selected_token=''
37
+ while IFS=' ' read -r repo token; do
38
+ case "$prompt" in
39
+ *//github.com/"$repo"\\'*|*//github.com/"$repo".git\\'*|*//*@github.com/"$repo"\\'*|*//*@github.com/"$repo".git\\'*) selected_token=$token; break ;;
40
+ esac
41
+ done <<TYPECLAW_GIT_CREDENTIALS_EOF
42
+ $TYPECLAW_GIT_CREDENTIALS
43
+ TYPECLAW_GIT_CREDENTIALS_EOF
44
+ [ -n "$selected_token" ] || exit 1
45
+ case "$1" in
46
+ *Username*) printf '%s\\n' 'x-access-token' ;;
47
+ *) printf '%s\\n' "$selected_token" ;;
48
+ esac
49
+ exit 0
50
+ fi
51
+ if [ -n "$TYPECLAW_GIT_EXPECTED_REPO" ]; then
52
+ expected_repo=$(printf '%s' "$TYPECLAW_GIT_EXPECTED_REPO" | tr '[:upper:]' '[:lower:]')
53
+ prompt=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
54
+ case "$prompt" in
55
+ *//github.com/"$expected_repo"\\'*|*//github.com/"$expected_repo".git\\'*|*//*@github.com/"$expected_repo"\\'*|*//*@github.com/"$expected_repo".git\\'*) : ;;
56
+ *) exit 1 ;;
57
+ esac
58
+ fi
34
59
  case "$1" in
35
60
  *Username*) printf '%s\\n' 'x-access-token' ;;
36
61
  *) printf '%s\\n' "$TYPECLAW_GIT_TOKEN" ;;
@@ -1,10 +1,42 @@
1
1
  // Plain-`git` analog of analyzeGhCommand. Git names its target indirectly, so
2
2
  // this analyzer resolves configured remotes before selecting a per-repo token.
3
3
 
4
+ import { spawn, type ChildProcess } from 'node:child_process'
5
+
6
+ import { mapVirtualTmpPath } from '@/sandbox'
7
+
8
+ import { GIT_CREDENTIAL_ENV_KEYS } from './git-credential-env'
9
+
10
+ // GitHub refuses anonymous writes, so a `write` decision the broker cannot fund
11
+ // is already doomed — the caller turns that into a block with guidance rather
12
+ // than letting git die on a credential prompt. Reads stay fundable-but-optional:
13
+ // public clone/fetch/ls-remote succeed with no token at all.
14
+ export type GitRemoteAccess = 'read' | 'write'
15
+
16
+ export type GitPushProvenance =
17
+ | { kind: 'explicit-url'; complete: true }
18
+ | {
19
+ kind: 'configured-remote'
20
+ remote: string
21
+ pushUrls: string[]
22
+ repoSlugs: string[]
23
+ worktreeTopLevel: string | null
24
+ sourceCwd: string
25
+ refspecs: string[]
26
+ setUpstream: boolean
27
+ complete: boolean
28
+ }
29
+
4
30
  export type GitCommandDecision =
5
31
  | { kind: 'pass-through' }
6
32
  | { kind: 'block'; reason: string }
7
- | { kind: 'inject'; repoSlug: string; rewrittenCommand?: string }
33
+ | {
34
+ kind: 'inject'
35
+ repoSlug: string
36
+ access: GitRemoteAccess
37
+ pushProvenance?: GitPushProvenance
38
+ rewrittenCommand?: string
39
+ }
8
40
 
9
41
  export type GitRemoteResolver = (cwd: string, remote: string, forPush: boolean) => Promise<string | null>
10
42
  export type GitConfigResolver = (cwd: string, key: string) => Promise<string | null>
@@ -14,24 +46,67 @@ export type GitResolvers = {
14
46
  resolveRemoteUrl: GitRemoteResolver
15
47
  resolveConfig: GitConfigResolver
16
48
  resolveCurrentBranch: GitBranchResolver
49
+ resolvePushUrls?: (cwd: string, remote: string) => Promise<string[] | null>
50
+ resolveTopLevel?: (cwd: string) => Promise<string | null>
17
51
  }
18
52
 
53
+ const GIT_RESOLVER_TIMEOUT_MS = 2_000
54
+ const GIT_RESOLVER_STDOUT_LIMIT = 64 * 1024
55
+ const GIT_RESOLVER_KILL_SETTLE_MS = 250
56
+
19
57
  async function runGit(cwd: string, args: string[]): Promise<string | null> {
20
- const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
21
- if (!bun) return null
22
- try {
23
- const proc = bun.spawn({
24
- cmd: ['git', '-C', cwd, ...args],
25
- stdout: 'pipe',
26
- stderr: 'ignore',
58
+ return await new Promise((resolveResult) => {
59
+ const child = spawn('git', ['-C', cwd, ...args], {
60
+ detached: process.platform !== 'win32',
61
+ stdio: ['ignore', 'pipe', 'ignore'],
27
62
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
28
63
  })
29
- if ((await proc.exited) !== 0) return null
30
- const out = (await new Response(proc.stdout).text()).trim()
31
- return out === '' ? null : out
32
- } catch {
33
- return null
64
+ const chunks: Buffer[] = []
65
+ let bytes = 0
66
+ let settled = false
67
+ let settleTimer: ReturnType<typeof setTimeout> | undefined
68
+ let timeoutTimer: ReturnType<typeof setTimeout> | undefined
69
+ const finish = (value: string | null): void => {
70
+ if (settled) return
71
+ settled = true
72
+ if (timeoutTimer !== undefined) clearTimeout(timeoutTimer)
73
+ if (settleTimer !== undefined) clearTimeout(settleTimer)
74
+ resolveResult(value)
75
+ }
76
+ const terminate = (): void => {
77
+ if (settleTimer !== undefined || settled) return
78
+ killChildProcessGroup(child)
79
+ settleTimer = setTimeout(() => finish(null), GIT_RESOLVER_KILL_SETTLE_MS)
80
+ }
81
+ timeoutTimer = setTimeout(terminate, GIT_RESOLVER_TIMEOUT_MS)
82
+ child.stdout.on('data', (chunk: Buffer) => {
83
+ bytes += chunk.length
84
+ if (bytes > GIT_RESOLVER_STDOUT_LIMIT) {
85
+ terminate()
86
+ return
87
+ }
88
+ chunks.push(chunk)
89
+ })
90
+ child.on('error', () => finish(null))
91
+ child.on('close', (code) => {
92
+ if (code !== 0 || bytes > GIT_RESOLVER_STDOUT_LIMIT) return finish(null)
93
+ const output = Buffer.concat(chunks).toString('utf8').trim()
94
+ finish(output === '' ? null : output)
95
+ })
96
+ })
97
+ }
98
+
99
+ function killChildProcessGroup(child: ChildProcess): void {
100
+ if (process.platform !== 'win32' && child.pid !== undefined) {
101
+ try {
102
+ process.kill(-child.pid, 'SIGKILL')
103
+ return
104
+ } catch {
105
+ child.kill('SIGKILL')
106
+ return
107
+ }
34
108
  }
109
+ child.kill('SIGKILL')
35
110
  }
36
111
 
37
112
  export const defaultGitResolvers: GitResolvers = {
@@ -39,6 +114,39 @@ export const defaultGitResolvers: GitResolvers = {
39
114
  runGit(cwd, forPush ? ['remote', 'get-url', '--push', remote] : ['remote', 'get-url', remote]),
40
115
  resolveConfig: (cwd, key) => runGit(cwd, ['config', '--get', key]),
41
116
  resolveCurrentBranch: (cwd) => runGit(cwd, ['symbolic-ref', '--short', 'HEAD']),
117
+ resolvePushUrls: async (cwd, remote) => {
118
+ const output = await runGit(cwd, ['remote', 'get-url', '--push', '--all', remote])
119
+ return output === null ? null : output.split(/\r?\n/).filter((line) => line !== '')
120
+ },
121
+ resolveTopLevel: (cwd) => runGit(cwd, ['rev-parse', '--show-toplevel']),
122
+ }
123
+
124
+ // Sandboxed bash sees the per-session scratch dir bound over `/tmp`
125
+ // (applyBashSandbox), but these resolvers spawn `git` from the runtime process
126
+ // against the REAL container `/tmp` — so a repo the model cloned to `/tmp/foo`
127
+ // resolves to nothing here and the command falls through UNBROKERED, leaving git
128
+ // to die on a credential prompt it can never answer. Same class of bug the file
129
+ // tools solve with TMP_REDIRECT_TOOLS. Only the filesystem probe is redirected:
130
+ // the analyzer must keep reasoning in model-facing paths so `rewrittenCommand`
131
+ // stays valid inside the sandbox.
132
+ export function createSessionTmpGitResolvers(
133
+ agentDir: string,
134
+ sessionId: string,
135
+ base: GitResolvers = defaultGitResolvers,
136
+ ): GitResolvers {
137
+ const backing = (cwd: string): string => mapVirtualTmpPath(agentDir, sessionId, cwd) ?? cwd
138
+ const mapped: GitResolvers = {
139
+ resolveRemoteUrl: (cwd, remote, forPush) => base.resolveRemoteUrl(backing(cwd), remote, forPush),
140
+ resolveConfig: (cwd, key) => base.resolveConfig(backing(cwd), key),
141
+ resolveCurrentBranch: (cwd) => base.resolveCurrentBranch(backing(cwd)),
142
+ }
143
+ if (base.resolvePushUrls !== undefined) {
144
+ mapped.resolvePushUrls = (cwd, remote) => base.resolvePushUrls?.(backing(cwd), remote) ?? Promise.resolve(null)
145
+ }
146
+ if (base.resolveTopLevel !== undefined) {
147
+ mapped.resolveTopLevel = (cwd) => base.resolveTopLevel?.(backing(cwd)) ?? Promise.resolve(null)
148
+ }
149
+ return mapped
42
150
  }
43
151
 
44
152
  const MULTI_OWNER_REASON =
@@ -46,6 +154,10 @@ const MULTI_OWNER_REASON =
46
154
  'token is scoped to one repo and cannot authenticate all of them. Split it into ' +
47
155
  'separate commands, one repository each.'
48
156
 
157
+ const MIXED_PUSH_URLS_REASON =
158
+ 'This remote mixes GitHub push destinations with a malformed or non-GitHub push URL. ' +
159
+ 'TypeClaw cannot safely bind credentials to every destination, so the push is blocked.'
160
+
49
161
  const COMPOSITION_REASON =
50
162
  'A repo-targeting `git` command receives a minted GitHub App token via ' +
51
163
  'GIT_ASKPASS in its process environment, so it must run as a single bare ' +
@@ -55,17 +167,17 @@ const COMPOSITION_REASON =
55
167
  'which is rewritten to `git -C <path> …`. Run local Git commands separately, ' +
56
168
  'then retry the remote operation as a standalone `git -C <path> …` command.'
57
169
 
58
- const TAIL_STRIP_PREFIX =
59
- 'exec /usr/bin/env -u TYPECLAW_GIT_TOKEN -u GIT_ASKPASS -u GH_TOKEN -u GITHUB_TOKEN ' +
60
- '-u GIT_TERMINAL_PROMPT -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0 ' +
61
- '-u GIT_CONFIG_KEY_1 -u GIT_CONFIG_VALUE_1 -u GIT_CONFIG_KEY_2 -u GIT_CONFIG_VALUE_2 ' +
62
- '-u GIT_CONFIG_KEY_3 -u GIT_CONFIG_VALUE_3 /bin/bash -c'
170
+ const AMBIENT_GITHUB_TOKEN_ENV_KEYS = ['GH_TOKEN', 'GITHUB_TOKEN'] as const
171
+ const TAIL_STRIP_ENV_KEYS = GIT_CREDENTIAL_ENV_KEYS.flatMap((key) =>
172
+ key === 'GIT_ASKPASS' ? [key, ...AMBIENT_GITHUB_TOKEN_ENV_KEYS] : [key],
173
+ )
174
+ const TAIL_STRIP_PREFIX = `exec /usr/bin/env ${TAIL_STRIP_ENV_KEYS.map((key) => `-u ${key}`).join(' ')} /bin/bash -c`
63
175
 
64
176
  type RemoteSubcommand = 'push' | 'fetch' | 'pull' | 'clone' | 'ls-remote'
65
177
 
66
178
  type TargetSpec =
67
- | { kind: 'default-push' }
68
- | { kind: 'single'; value: string; forPush: boolean }
179
+ | { kind: 'default-push'; refspecs: []; setUpstream: false }
180
+ | { kind: 'single'; value: string; forPush: boolean; refspecs?: string[]; setUpstream?: boolean }
69
181
  | { kind: 'multiple'; values: string[] }
70
182
 
71
183
  type MintableInvocation = {
@@ -78,6 +190,8 @@ type MintableInvocation = {
78
190
  type RepoEvidence = {
79
191
  slugs: string[]
80
192
  complete: boolean
193
+ blockReason?: string
194
+ pushProvenance?: GitPushProvenance
81
195
  }
82
196
 
83
197
  const EVIDENCE_GLOBAL_VALUE_OPTIONS = new Set([
@@ -138,12 +252,24 @@ async function decideStandalone(invocation: MintableInvocation, resolvers: GitRe
138
252
  const evidence = await resolveMintableEvidence(invocation, resolvers)
139
253
  const repos = new Set(evidence.slugs)
140
254
 
255
+ if (evidence.blockReason !== undefined) return { kind: 'block', reason: evidence.blockReason }
141
256
  // The order is deliberate: partial evidence may justify blocking a compound,
142
257
  // but it can never justify minting for a standalone command.
143
258
  if (repos.size === 0) return { kind: 'pass-through' }
144
259
  if (!evidence.complete) return { kind: 'pass-through' }
145
- if (repos.size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
146
- return { kind: 'inject', repoSlug: [...repos][0] as string }
260
+ if (repos.size > 1 && evidence.pushProvenance?.kind !== 'configured-remote') {
261
+ return { kind: 'block', reason: MULTI_OWNER_REASON }
262
+ }
263
+ return {
264
+ kind: 'inject',
265
+ repoSlug: [...repos][0] as string,
266
+ access: remoteAccess(invocation.subcommand),
267
+ ...(evidence.pushProvenance === undefined ? {} : { pushProvenance: evidence.pushProvenance }),
268
+ }
269
+ }
270
+
271
+ function remoteAccess(subcommand: RemoteSubcommand): GitRemoteAccess {
272
+ return subcommand === 'push' ? 'write' : 'read'
147
273
  }
148
274
 
149
275
  function parseMintableGitInvocation(command: string, baseCwd: string): MintableInvocation | null {
@@ -204,9 +330,19 @@ function parseMintablePush(args: readonly string[]): TargetSpec | null {
204
330
  positionals.push(arg)
205
331
  }
206
332
 
207
- if (repository !== null) return { kind: 'single', value: repository, forPush: true }
208
- if (positionals.length > 0) return { kind: 'single', value: positionals[0] as string, forPush: true }
209
- return upstream ? null : { kind: 'default-push' }
333
+ if (repository !== null) {
334
+ return { kind: 'single', value: repository, forPush: true, refspecs: positionals, setUpstream: upstream }
335
+ }
336
+ if (positionals.length > 0) {
337
+ return {
338
+ kind: 'single',
339
+ value: positionals[0] as string,
340
+ forPush: true,
341
+ refspecs: positionals.slice(1),
342
+ setUpstream: upstream,
343
+ }
344
+ }
345
+ return upstream ? null : { kind: 'default-push', refspecs: [], setUpstream: false }
210
346
  }
211
347
 
212
348
  function parseMintableFetch(args: readonly string[]): TargetSpec | null {
@@ -302,12 +438,19 @@ async function resolveMintableEvidence(invocation: MintableInvocation, resolvers
302
438
  if (invocation.target.kind === 'default-push') {
303
439
  try {
304
440
  const remote = await resolveDefaultPushRemote(invocation.cwd, resolvers)
305
- return resolveOneTarget(remote, invocation.cwd, true, resolvers, false)
441
+ return resolveOneTarget(remote, invocation.cwd, true, resolvers, false, invocation.target)
306
442
  } catch {
307
443
  return noEvidence(false)
308
444
  }
309
445
  }
310
- return resolveOneTarget(invocation.target.value, invocation.cwd, invocation.target.forPush, resolvers, false)
446
+ return resolveOneTarget(
447
+ invocation.target.value,
448
+ invocation.cwd,
449
+ invocation.target.forPush,
450
+ resolvers,
451
+ false,
452
+ invocation.target,
453
+ )
311
454
  }
312
455
 
313
456
  async function resolveFetchMultiple(
@@ -332,11 +475,59 @@ async function resolveOneTarget(
332
475
  forPush: boolean,
333
476
  resolvers: GitResolvers,
334
477
  nonGithubIsIncomplete: boolean,
478
+ targetSpec?: TargetSpec,
335
479
  ): Promise<RepoEvidence> {
336
480
  if (target === null) return noEvidence(false)
481
+ const explicitUrl = looksLikeUrl(target)
482
+ if (forPush && explicitUrl) {
483
+ const slug = parseGithubRepoFromGitUrl(target)
484
+ return slug === null
485
+ ? { ...noEvidence(!nonGithubIsIncomplete), pushProvenance: { kind: 'explicit-url', complete: true } }
486
+ : { slugs: [slug], complete: true, pushProvenance: { kind: 'explicit-url', complete: true } }
487
+ }
488
+
489
+ if (forPush && !explicitUrl && resolvers.resolvePushUrls !== undefined) {
490
+ let pushUrls: string[] | null
491
+ try {
492
+ pushUrls = await resolvers.resolvePushUrls(cwd, target)
493
+ } catch {
494
+ return noEvidence(false)
495
+ }
496
+ if (pushUrls === null || pushUrls.length === 0) return noEvidence(false)
497
+ const parsedSlugs = pushUrls.map((url) => parseGithubRepoFromGitUrl(url))
498
+ const githubSlugs = parsedSlugs.filter((slug): slug is string => slug !== null)
499
+ if (githubSlugs.length === 0) return noEvidence(!nonGithubIsIncomplete && pushUrls.length === 1)
500
+ if (githubSlugs.length !== pushUrls.length) {
501
+ return { slugs: orderedCanonicalSlugs(githubSlugs), complete: false, blockReason: MIXED_PUSH_URLS_REASON }
502
+ }
503
+ const repoSlugs = orderedCanonicalSlugs(githubSlugs)
504
+ let worktreeTopLevel: string | null = null
505
+ if (resolvers.resolveTopLevel !== undefined) {
506
+ try {
507
+ worktreeTopLevel = await resolvers.resolveTopLevel(cwd)
508
+ } catch {
509
+ worktreeTopLevel = null
510
+ }
511
+ }
512
+ return {
513
+ slugs: repoSlugs,
514
+ complete: true,
515
+ pushProvenance: {
516
+ kind: 'configured-remote',
517
+ remote: target,
518
+ pushUrls,
519
+ repoSlugs,
520
+ worktreeTopLevel,
521
+ sourceCwd: cwd,
522
+ refspecs: targetSpec?.kind === 'single' ? (targetSpec.refspecs ?? []) : [],
523
+ setUpstream: targetSpec?.kind === 'single' ? (targetSpec.setUpstream ?? false) : false,
524
+ complete: worktreeTopLevel !== null,
525
+ },
526
+ }
527
+ }
337
528
  let url: string | null
338
529
  try {
339
- url = looksLikeUrl(target) ? target : await resolvers.resolveRemoteUrl(cwd, target, forPush)
530
+ url = explicitUrl ? target : await resolvers.resolveRemoteUrl(cwd, target, forPush)
340
531
  } catch {
341
532
  return noEvidence(false)
342
533
  }
@@ -347,6 +538,10 @@ async function resolveOneTarget(
347
538
  return { slugs: [], complete: !nonGithubIsIncomplete }
348
539
  }
349
540
 
541
+ function orderedCanonicalSlugs(slugs: readonly string[]): string[] {
542
+ return [...new Set(slugs.map((slug) => slug.toLocaleLowerCase()))]
543
+ }
544
+
350
545
  async function resolveDefaultPushRemote(cwd: string, resolvers: GitResolvers): Promise<string> {
351
546
  const branch = await resolvers.resolveCurrentBranch(cwd)
352
547
  if (branch !== null && branch !== '') {
@@ -354,7 +549,12 @@ async function resolveDefaultPushRemote(cwd: string, resolvers: GitResolvers): P
354
549
  if (perBranch !== null && perBranch !== '') return perBranch
355
550
  }
356
551
  const pushDefault = await resolvers.resolveConfig(cwd, 'remote.pushDefault')
357
- return pushDefault === null || pushDefault === '' ? 'origin' : pushDefault
552
+ if (pushDefault !== null && pushDefault !== '') return pushDefault
553
+ if (branch !== null && branch !== '') {
554
+ const branchRemote = await resolvers.resolveConfig(cwd, `branch.${branch}.remote`)
555
+ if (branchRemote !== null && branchRemote !== '') return branchRemote
556
+ }
557
+ return 'origin'
358
558
  }
359
559
 
360
560
  // Evidence discovery is intentionally not a shell parser. It recognizes only a
@@ -490,7 +690,7 @@ function parseEvidenceTarget(subcommand: RemoteSubcommand, args: readonly string
490
690
  }
491
691
  if (repository !== null) return { kind: 'single', value: repository, forPush: true }
492
692
  return positionals.length === 0
493
- ? { kind: 'default-push' }
693
+ ? { kind: 'default-push', refspecs: [], setUpstream: false }
494
694
  : { kind: 'single', value: positionals[0] as string, forPush: true }
495
695
  }
496
696
 
@@ -602,6 +802,7 @@ function analyzeCloneThenInspect(command: string): GitCommandDecision | null {
602
802
  return {
603
803
  kind: 'inject',
604
804
  repoSlug: parsed.repoSlug,
805
+ access: 'read',
605
806
  rewrittenCommand: `${canonicalHead} && ${TAIL_STRIP_PREFIX} ${posixSingleQuote(split.tail)}`,
606
807
  }
607
808
  }
@@ -0,0 +1,151 @@
1
+ export type GitRepoCredential = { repoSlug: string; token: string }
2
+ export type GitCredentialTransportOptions = {
3
+ expectedRemote?: string
4
+ pushUrls?: readonly string[]
5
+ trustedEnv?: NodeJS.ProcessEnv
6
+ }
7
+
8
+ export function buildGitCredentialEnv(
9
+ credentials: readonly GitRepoCredential[],
10
+ askpassPath: string,
11
+ options?: GitCredentialTransportOptions,
12
+ ): Record<string, string>
13
+ export function buildGitCredentialEnv(
14
+ token: string,
15
+ askpassPath: string,
16
+ expectedRepo?: string,
17
+ expectedRemote?: string,
18
+ ): Record<string, string>
19
+ export function buildGitCredentialEnv(
20
+ credentialsOrToken: readonly GitRepoCredential[] | string,
21
+ askpassPath: string,
22
+ expectedRepoOrOptions?: GitCredentialTransportOptions | string,
23
+ legacyExpectedRemote?: string,
24
+ ): Record<string, string> {
25
+ const expectedRepo = typeof expectedRepoOrOptions === 'string' ? expectedRepoOrOptions : undefined
26
+ const options =
27
+ typeof expectedRepoOrOptions === 'object'
28
+ ? expectedRepoOrOptions
29
+ : { expectedRemote: legacyExpectedRemote, trustedEnv: {} }
30
+ const credentials = normalizeCredentials(credentialsOrToken, expectedRepo)
31
+ const transport = resolveTrustedTransport(options.trustedEnv ?? {})
32
+ const config: Array<[string, string]> = [
33
+ ['core.hooksPath', '/dev/null'],
34
+ ['credential.helper', ''],
35
+ ['url.https://github.com/.insteadOf', 'git@github.com:'],
36
+ ['url.https://github.com/.insteadOf', 'ssh://git@github.com/'],
37
+ ['credential.useHttpPath', 'true'],
38
+ ]
39
+ const credentialUrls =
40
+ options.pushUrls === undefined
41
+ ? credentials.flatMap(({ repoSlug }) => [`https://github.com/${repoSlug}`, `https://github.com/${repoSlug}.git`])
42
+ : options.pushUrls.map(normalizeGithubPushUrl)
43
+ for (const url of new Set(credentialUrls)) {
44
+ config.push(
45
+ [`credential.${url}.helper`, ''],
46
+ [`http.${url}.proxy`, transport.proxy],
47
+ [`http.${url}.sslCAInfo`, transport.caInfo],
48
+ [`http.${url}.sslVerify`, 'true'],
49
+ )
50
+ }
51
+ if (options.expectedRemote !== undefined) config.push([`remote.${options.expectedRemote}.proxy`, transport.proxy])
52
+
53
+ const credentialVariables: Record<string, string> =
54
+ credentials.length === 1
55
+ ? {
56
+ TYPECLAW_GIT_TOKEN: credentials[0]?.token ?? '',
57
+ TYPECLAW_GIT_EXPECTED_REPO: credentials[0]?.repoSlug ?? '',
58
+ }
59
+ : credentials.length > 1
60
+ ? { TYPECLAW_GIT_CREDENTIALS: credentials.map(({ repoSlug, token }) => `${repoSlug}\t${token}`).join('\n') }
61
+ : {}
62
+
63
+ return {
64
+ ...credentialVariables,
65
+ GIT_ASKPASS: askpassPath,
66
+ GIT_TERMINAL_PROMPT: '0',
67
+ // Git applies local insteadOf rewrites after analysis; HTTPS-only blocks ext:: from inheriting the token.
68
+ GIT_ALLOW_PROTOCOL: 'https',
69
+ GIT_CONFIG_COUNT: String(config.length),
70
+ ...Object.fromEntries(
71
+ config.flatMap(([key, value], index) => [
72
+ [`GIT_CONFIG_KEY_${index}`, key],
73
+ [`GIT_CONFIG_VALUE_${index}`, value],
74
+ ]),
75
+ ),
76
+ }
77
+ }
78
+
79
+ function normalizeGithubPushUrl(raw: string): string {
80
+ const url = raw.trim()
81
+ const https = url.match(/^https:\/\/github\.com\/([^/\s:@]+)\/([^/\s?#]+?)(\.git)?\/?(?:[?#].*)?$/i)
82
+ const scp = url.match(/^git@github\.com:([^/\s:?#]+)\/([^/\s?#]+?)(\.git)?$/i)
83
+ const ssh = url.match(/^ssh:\/\/git@github\.com\/([^/\s]+)\/([^/\s?#]+?)(\.git)?\/?(?:[?#].*)?$/i)
84
+ const match = https ?? scp ?? ssh
85
+ if (match === null || match[1] === undefined || match[2] === undefined) {
86
+ throw new Error('invalid GitHub push URL')
87
+ }
88
+ return `https://github.com/${match[1]}/${match[2]}${match[3] ?? ''}`
89
+ }
90
+
91
+ function resolveTrustedTransport(env: NodeJS.ProcessEnv): {
92
+ proxy: string
93
+ caInfo: string
94
+ } {
95
+ const proxy = firstDefined(env, ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'])
96
+ const caInfo = firstNonEmpty(env, ['GIT_SSL_CAINFO', 'SSL_CERT_FILE', 'CURL_CA_BUNDLE'])
97
+ return {
98
+ proxy: proxy ?? '',
99
+ caInfo: caInfo ?? '/etc/ssl/certs/ca-certificates.crt',
100
+ }
101
+ }
102
+
103
+ function firstDefined(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {
104
+ for (const key of keys) {
105
+ if (env[key] !== undefined) return env[key]
106
+ }
107
+ return undefined
108
+ }
109
+
110
+ function firstNonEmpty(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {
111
+ for (const key of keys) {
112
+ const value = env[key]
113
+ if (value !== undefined && value !== '') return value
114
+ }
115
+ return undefined
116
+ }
117
+
118
+ function normalizeCredentials(
119
+ credentialsOrToken: readonly GitRepoCredential[] | string,
120
+ expectedRepo: string | undefined,
121
+ ): GitRepoCredential[] {
122
+ const source =
123
+ typeof credentialsOrToken === 'string'
124
+ ? expectedRepo === undefined
125
+ ? []
126
+ : [{ repoSlug: expectedRepo, token: credentialsOrToken }]
127
+ : [...credentialsOrToken]
128
+ return source.map((credential) => {
129
+ const repoSlug = credential.repoSlug.toLocaleLowerCase().replace(/\.git$/i, '')
130
+ if (!/^[a-z0-9_.-]+\/[a-z0-9_.-]+$/.test(repoSlug) || /[\t\r\n]/.test(credential.token)) {
131
+ throw new Error('invalid repository credential')
132
+ }
133
+ return { repoSlug, token: credential.token }
134
+ })
135
+ }
136
+
137
+ // Injection and clone-tail stripping share these keys so a new credential variable cannot leak into the tail shell.
138
+ export const GIT_CREDENTIAL_ENV_KEYS: readonly string[] = Object.freeze([
139
+ ...new Set([
140
+ ...Object.keys(buildGitCredentialEnv('', '', 'owner/repo')),
141
+ ...Object.keys(
142
+ buildGitCredentialEnv(
143
+ [
144
+ { repoSlug: 'owner/repo', token: '' },
145
+ { repoSlug: 'owner/other', token: '' },
146
+ ],
147
+ '',
148
+ ),
149
+ ),
150
+ ]),
151
+ ])