typeclaw 0.48.7 → 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 (104) 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/multimodal/read-redirect.ts +8 -9
  8. package/src/agent/plugin-tools.ts +283 -148
  9. package/src/agent/provider-error.ts +6 -1
  10. package/src/agent/reload-tool.ts +12 -5
  11. package/src/agent/retry-same-ref.ts +95 -36
  12. package/src/agent/session-origin.ts +13 -1
  13. package/src/agent/system-prompt.ts +14 -3
  14. package/src/agent/todo/continuation-policy.ts +3 -4
  15. package/src/agent/tool-file-safety.ts +36 -13
  16. package/src/agent/tools/channel-reply.ts +39 -2
  17. package/src/agent/tools/channel-send.ts +45 -2
  18. package/src/agent/tools/post-github-review.ts +31 -13
  19. package/src/agent/tools/spawn-subagent.ts +15 -0
  20. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  21. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  22. package/src/agent/turn-runner.ts +23 -19
  23. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  24. package/src/bundled-plugins/backup/subagents.ts +1 -1
  25. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  26. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  27. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  28. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  29. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  30. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  31. package/src/bundled-plugins/github-cli-auth/git-command.ts +209 -31
  32. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  33. package/src/bundled-plugins/github-cli-auth/index.ts +236 -38
  34. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  35. package/src/bundled-plugins/guard/index.ts +2 -25
  36. package/src/bundled-plugins/guard/keys.ts +8 -0
  37. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  38. package/src/bundled-plugins/guard/policy.ts +1 -7
  39. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  40. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  41. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  42. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  43. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  44. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  45. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  46. package/src/bundled-plugins/security/policy.ts +0 -8
  47. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  48. package/src/channels/adapters/discord-bot.ts +2 -1
  49. package/src/channels/adapters/discord-classify.ts +16 -4
  50. package/src/channels/adapters/discord.ts +20 -8
  51. package/src/channels/adapters/github/dedup.ts +37 -8
  52. package/src/channels/adapters/github/inbound.ts +241 -46
  53. package/src/channels/adapters/github/review-state.ts +13 -9
  54. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  55. package/src/channels/adapters/slack-classify.ts +40 -5
  56. package/src/channels/adapters/slack.ts +3 -9
  57. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  58. package/src/channels/adapters/webex-bot.ts +2 -4
  59. package/src/channels/adapters/webex-classify.ts +4 -33
  60. package/src/channels/adapters/webex-format.ts +36 -0
  61. package/src/channels/adapters/webex.ts +2 -4
  62. package/src/channels/continuation-willingness.ts +64 -39
  63. package/src/channels/github-rereview-guard.ts +20 -0
  64. package/src/channels/github-review-turn-ledger.ts +11 -1
  65. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  66. package/src/channels/github-verdict-activity.ts +14 -5
  67. package/src/channels/persistence.ts +89 -5
  68. package/src/channels/router.ts +1187 -254
  69. package/src/channels/types.ts +21 -5
  70. package/src/cli/compose-stats.ts +6 -7
  71. package/src/cli/compose-status.ts +6 -7
  72. package/src/cli/compose-usage.ts +6 -7
  73. package/src/cli/stats.ts +6 -7
  74. package/src/cli/status.ts +7 -8
  75. package/src/cli/ui.ts +4 -4
  76. package/src/container/start.ts +41 -1
  77. package/src/cron/consumer.ts +30 -9
  78. package/src/cron/scheduler.ts +24 -9
  79. package/src/doctor/channel-checks.ts +64 -0
  80. package/src/doctor/report.ts +8 -8
  81. package/src/dreams/render.ts +2 -2
  82. package/src/init/dockerfile.ts +8 -1
  83. package/src/inspect/render.ts +2 -2
  84. package/src/path-safety/real-intended-path.ts +14 -1
  85. package/src/permissions/permissions.ts +10 -2
  86. package/src/permissions/resolve.ts +8 -2
  87. package/src/plugin/core-tool-names.ts +15 -0
  88. package/src/plugin/hooks.ts +37 -3
  89. package/src/plugin/registry.ts +7 -3
  90. package/src/run/index.ts +33 -7
  91. package/src/sandbox/build.ts +19 -3
  92. package/src/sandbox/policy.ts +1 -0
  93. package/src/secrets/export-github-cli-store.ts +158 -0
  94. package/src/secrets/index.ts +19 -1
  95. package/src/secrets/provision-github-cli-store.ts +322 -0
  96. package/src/secrets/schema.ts +13 -7
  97. package/src/secrets/storage.ts +30 -0
  98. package/src/shared/index.ts +2 -0
  99. package/src/shared/style-text.ts +13 -0
  100. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  101. package/src/skills/typeclaw-config/SKILL.md +3 -1
  102. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  103. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  104. 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,12 +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
+
4
6
  import { mapVirtualTmpPath } from '@/sandbox'
5
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
+
6
30
  export type GitCommandDecision =
7
31
  | { kind: 'pass-through' }
8
32
  | { kind: 'block'; reason: string }
9
- | { kind: 'inject'; repoSlug: string; rewrittenCommand?: string }
33
+ | {
34
+ kind: 'inject'
35
+ repoSlug: string
36
+ access: GitRemoteAccess
37
+ pushProvenance?: GitPushProvenance
38
+ rewrittenCommand?: string
39
+ }
10
40
 
11
41
  export type GitRemoteResolver = (cwd: string, remote: string, forPush: boolean) => Promise<string | null>
12
42
  export type GitConfigResolver = (cwd: string, key: string) => Promise<string | null>
@@ -16,24 +46,67 @@ export type GitResolvers = {
16
46
  resolveRemoteUrl: GitRemoteResolver
17
47
  resolveConfig: GitConfigResolver
18
48
  resolveCurrentBranch: GitBranchResolver
49
+ resolvePushUrls?: (cwd: string, remote: string) => Promise<string[] | null>
50
+ resolveTopLevel?: (cwd: string) => Promise<string | null>
19
51
  }
20
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
+
21
57
  async function runGit(cwd: string, args: string[]): Promise<string | null> {
22
- const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
23
- if (!bun) return null
24
- try {
25
- const proc = bun.spawn({
26
- cmd: ['git', '-C', cwd, ...args],
27
- stdout: 'pipe',
28
- 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'],
29
62
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
30
63
  })
31
- if ((await proc.exited) !== 0) return null
32
- const out = (await new Response(proc.stdout).text()).trim()
33
- return out === '' ? null : out
34
- } catch {
35
- 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
+ }
36
108
  }
109
+ child.kill('SIGKILL')
37
110
  }
38
111
 
39
112
  export const defaultGitResolvers: GitResolvers = {
@@ -41,6 +114,11 @@ export const defaultGitResolvers: GitResolvers = {
41
114
  runGit(cwd, forPush ? ['remote', 'get-url', '--push', remote] : ['remote', 'get-url', remote]),
42
115
  resolveConfig: (cwd, key) => runGit(cwd, ['config', '--get', key]),
43
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']),
44
122
  }
45
123
 
46
124
  // Sandboxed bash sees the per-session scratch dir bound over `/tmp`
@@ -57,11 +135,18 @@ export function createSessionTmpGitResolvers(
57
135
  base: GitResolvers = defaultGitResolvers,
58
136
  ): GitResolvers {
59
137
  const backing = (cwd: string): string => mapVirtualTmpPath(agentDir, sessionId, cwd) ?? cwd
60
- return {
138
+ const mapped: GitResolvers = {
61
139
  resolveRemoteUrl: (cwd, remote, forPush) => base.resolveRemoteUrl(backing(cwd), remote, forPush),
62
140
  resolveConfig: (cwd, key) => base.resolveConfig(backing(cwd), key),
63
141
  resolveCurrentBranch: (cwd) => base.resolveCurrentBranch(backing(cwd)),
64
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
65
150
  }
66
151
 
67
152
  const MULTI_OWNER_REASON =
@@ -69,6 +154,10 @@ const MULTI_OWNER_REASON =
69
154
  'token is scoped to one repo and cannot authenticate all of them. Split it into ' +
70
155
  'separate commands, one repository each.'
71
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
+
72
161
  const COMPOSITION_REASON =
73
162
  'A repo-targeting `git` command receives a minted GitHub App token via ' +
74
163
  'GIT_ASKPASS in its process environment, so it must run as a single bare ' +
@@ -78,17 +167,17 @@ const COMPOSITION_REASON =
78
167
  'which is rewritten to `git -C <path> …`. Run local Git commands separately, ' +
79
168
  'then retry the remote operation as a standalone `git -C <path> …` command.'
80
169
 
81
- const TAIL_STRIP_PREFIX =
82
- 'exec /usr/bin/env -u TYPECLAW_GIT_TOKEN -u GIT_ASKPASS -u GH_TOKEN -u GITHUB_TOKEN ' +
83
- '-u GIT_TERMINAL_PROMPT -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0 ' +
84
- '-u GIT_CONFIG_KEY_1 -u GIT_CONFIG_VALUE_1 -u GIT_CONFIG_KEY_2 -u GIT_CONFIG_VALUE_2 ' +
85
- '-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`
86
175
 
87
176
  type RemoteSubcommand = 'push' | 'fetch' | 'pull' | 'clone' | 'ls-remote'
88
177
 
89
178
  type TargetSpec =
90
- | { kind: 'default-push' }
91
- | { kind: 'single'; value: string; forPush: boolean }
179
+ | { kind: 'default-push'; refspecs: []; setUpstream: false }
180
+ | { kind: 'single'; value: string; forPush: boolean; refspecs?: string[]; setUpstream?: boolean }
92
181
  | { kind: 'multiple'; values: string[] }
93
182
 
94
183
  type MintableInvocation = {
@@ -101,6 +190,8 @@ type MintableInvocation = {
101
190
  type RepoEvidence = {
102
191
  slugs: string[]
103
192
  complete: boolean
193
+ blockReason?: string
194
+ pushProvenance?: GitPushProvenance
104
195
  }
105
196
 
106
197
  const EVIDENCE_GLOBAL_VALUE_OPTIONS = new Set([
@@ -161,12 +252,24 @@ async function decideStandalone(invocation: MintableInvocation, resolvers: GitRe
161
252
  const evidence = await resolveMintableEvidence(invocation, resolvers)
162
253
  const repos = new Set(evidence.slugs)
163
254
 
255
+ if (evidence.blockReason !== undefined) return { kind: 'block', reason: evidence.blockReason }
164
256
  // The order is deliberate: partial evidence may justify blocking a compound,
165
257
  // but it can never justify minting for a standalone command.
166
258
  if (repos.size === 0) return { kind: 'pass-through' }
167
259
  if (!evidence.complete) return { kind: 'pass-through' }
168
- if (repos.size > 1) return { kind: 'block', reason: MULTI_OWNER_REASON }
169
- 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'
170
273
  }
171
274
 
172
275
  function parseMintableGitInvocation(command: string, baseCwd: string): MintableInvocation | null {
@@ -227,9 +330,19 @@ function parseMintablePush(args: readonly string[]): TargetSpec | null {
227
330
  positionals.push(arg)
228
331
  }
229
332
 
230
- if (repository !== null) return { kind: 'single', value: repository, forPush: true }
231
- if (positionals.length > 0) return { kind: 'single', value: positionals[0] as string, forPush: true }
232
- 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 }
233
346
  }
234
347
 
235
348
  function parseMintableFetch(args: readonly string[]): TargetSpec | null {
@@ -325,12 +438,19 @@ async function resolveMintableEvidence(invocation: MintableInvocation, resolvers
325
438
  if (invocation.target.kind === 'default-push') {
326
439
  try {
327
440
  const remote = await resolveDefaultPushRemote(invocation.cwd, resolvers)
328
- return resolveOneTarget(remote, invocation.cwd, true, resolvers, false)
441
+ return resolveOneTarget(remote, invocation.cwd, true, resolvers, false, invocation.target)
329
442
  } catch {
330
443
  return noEvidence(false)
331
444
  }
332
445
  }
333
- 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
+ )
334
454
  }
335
455
 
336
456
  async function resolveFetchMultiple(
@@ -355,11 +475,59 @@ async function resolveOneTarget(
355
475
  forPush: boolean,
356
476
  resolvers: GitResolvers,
357
477
  nonGithubIsIncomplete: boolean,
478
+ targetSpec?: TargetSpec,
358
479
  ): Promise<RepoEvidence> {
359
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
+ }
360
528
  let url: string | null
361
529
  try {
362
- url = looksLikeUrl(target) ? target : await resolvers.resolveRemoteUrl(cwd, target, forPush)
530
+ url = explicitUrl ? target : await resolvers.resolveRemoteUrl(cwd, target, forPush)
363
531
  } catch {
364
532
  return noEvidence(false)
365
533
  }
@@ -370,6 +538,10 @@ async function resolveOneTarget(
370
538
  return { slugs: [], complete: !nonGithubIsIncomplete }
371
539
  }
372
540
 
541
+ function orderedCanonicalSlugs(slugs: readonly string[]): string[] {
542
+ return [...new Set(slugs.map((slug) => slug.toLocaleLowerCase()))]
543
+ }
544
+
373
545
  async function resolveDefaultPushRemote(cwd: string, resolvers: GitResolvers): Promise<string> {
374
546
  const branch = await resolvers.resolveCurrentBranch(cwd)
375
547
  if (branch !== null && branch !== '') {
@@ -377,7 +549,12 @@ async function resolveDefaultPushRemote(cwd: string, resolvers: GitResolvers): P
377
549
  if (perBranch !== null && perBranch !== '') return perBranch
378
550
  }
379
551
  const pushDefault = await resolvers.resolveConfig(cwd, 'remote.pushDefault')
380
- 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'
381
558
  }
382
559
 
383
560
  // Evidence discovery is intentionally not a shell parser. It recognizes only a
@@ -513,7 +690,7 @@ function parseEvidenceTarget(subcommand: RemoteSubcommand, args: readonly string
513
690
  }
514
691
  if (repository !== null) return { kind: 'single', value: repository, forPush: true }
515
692
  return positionals.length === 0
516
- ? { kind: 'default-push' }
693
+ ? { kind: 'default-push', refspecs: [], setUpstream: false }
517
694
  : { kind: 'single', value: positionals[0] as string, forPush: true }
518
695
  }
519
696
 
@@ -625,6 +802,7 @@ function analyzeCloneThenInspect(command: string): GitCommandDecision | null {
625
802
  return {
626
803
  kind: 'inject',
627
804
  repoSlug: parsed.repoSlug,
805
+ access: 'read',
628
806
  rewrittenCommand: `${canonicalHead} && ${TAIL_STRIP_PREFIX} ${posixSingleQuote(split.tail)}`,
629
807
  }
630
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
+ ])