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
@@ -1,10 +1,17 @@
1
- import { TYPECLAW_INTERNAL_BASH_ENV } from '@/agent/plugin-tools'
1
+ import {
2
+ TYPECLAW_INTERNAL_BASH_ENV,
3
+ TYPECLAW_INTERNAL_BASH_PREPARE,
4
+ TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV,
5
+ } from '@/agent/plugin-tools'
2
6
  import type { SessionOrigin } from '@/agent/session-origin'
7
+ import { recordVerifiedDismissal } from '@/channels/github-review-turn-ledger'
3
8
  import {
4
9
  configureReviewVerdictCoordinator,
5
10
  createSharedReviewVerdictGuard,
11
+ guardGithubReviewRoundDismissal,
12
+ releaseGithubReviewRoundDismissal,
6
13
  } from '@/channels/github-review-verdict-coordinator'
7
- import { hasEnvKey } from '@/init/env-file'
14
+ import { hasEnvKey, readEnvFile } from '@/init/env-file'
8
15
  import { CORE_PERMISSIONS } from '@/permissions/builtins'
9
16
  import { definePlugin } from '@/plugin'
10
17
 
@@ -15,16 +22,31 @@ import {
15
22
  effectiveGhTokensForAuthenticatedUserEndpoint,
16
23
  usesGhApiGraphqlEndpoint,
17
24
  } from './gh-command'
25
+ import { detectReviewDismissal } from './gh-review-detect'
26
+ import {
27
+ cleanupPreparedGithubStorePush,
28
+ GH_STORE_AMBIENT_AUTH_KEYS,
29
+ planGithubStorePush,
30
+ prepareGithubStorePush,
31
+ resolveGithubCliStoreToken,
32
+ } from './gh-store'
18
33
  import { ensureGitAskPassHelper, resolveSandboxGitAskPassPath } from './git-askpass'
19
- import { analyzeGitCommand, defaultGitResolvers, resolveGhDefaultRepoFromCwd } from './git-command'
34
+ import {
35
+ analyzeGitCommand,
36
+ createSessionTmpGitResolvers,
37
+ defaultGitResolvers,
38
+ resolveGhDefaultRepoFromCwd,
39
+ } from './git-command'
40
+ import { buildGitCredentialEnv, type GitRepoCredential } from './git-credential-env'
20
41
  import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
21
- import { commitReviewIfSucceeded, noteReviewCommand } from './review-recorder'
42
+ import { commitReviewIfSucceeded, dismissalMutationSucceeded, noteReviewCommand } from './review-recorder'
22
43
  import { classifyGhToken, shouldMintAppToken } from './token-class'
23
44
 
24
45
  export default definePlugin({
25
46
  plugin: async (ctx) => {
26
47
  const resolveTokenForRepo = ctx.github.resolveTokenForRepo
27
48
  const hasAppTokenResolver = ctx.github.hasAppTokenResolver
49
+ const trustedGitTransportEnv: NodeJS.ProcessEnv = { ...process.env }
28
50
 
29
51
  // Every model-driven bash masks the canonical credential files. A role may
30
52
  // still USE a PAT through this runtime-owned overlay, which injects one
@@ -72,6 +94,39 @@ export default definePlugin({
72
94
  return undefined
73
95
  }
74
96
 
97
+ // Stricter than sandboxInheritedGhToken(), and deliberately not merged with it.
98
+ // `gh` only needs to know WHICH token the sandbox will hand it, so the live
99
+ // value is the right answer there. Brokering to git asserts something stronger
100
+ // — that the operator deliberately exposed THIS value — and a declared NAME
101
+ // does not authenticate a live VALUE: PAT-mode channel auth overwrites
102
+ // process.env.GH_TOKEN at runtime (channels/adapters/github/index.ts), so a
103
+ // declared name can carry a credential the operator never wrote to `.env`.
104
+ // Compare against the same literal `readEnvFile` parse Docker's --env-file
105
+ // injects, and fail closed on any mismatch.
106
+ const declaredGhTokenForGitBroker = (): { envName: 'GH_TOKEN' | 'GITHUB_TOKEN'; value: string } | undefined => {
107
+ const inherited = sandboxInheritedGhToken()
108
+ if (inherited === undefined) return undefined
109
+ const declared = readEnvFile(ctx.agentDir).get(inherited.envName)
110
+ if (declared === undefined || declared === '' || declared !== inherited.value) return undefined
111
+ return inherited
112
+ }
113
+
114
+ const declaredGitCredentialState = ():
115
+ | { kind: 'absent' }
116
+ | { kind: 'invalid' }
117
+ | { kind: 'pat'; envName: 'GH_TOKEN' | 'GITHUB_TOKEN'; value: string } => {
118
+ const inherited = declaredGhTokenForGitBroker()
119
+ if (inherited === undefined) {
120
+ return hasEnvKey(ctx.agentDir, 'GH_TOKEN') || hasEnvKey(ctx.agentDir, 'GITHUB_TOKEN')
121
+ ? { kind: 'invalid' }
122
+ : { kind: 'absent' }
123
+ }
124
+ const tokenClass = classifyGhToken(inherited.value)
125
+ return tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat'
126
+ ? { kind: 'pat', ...inherited }
127
+ : { kind: 'invalid' }
128
+ }
129
+
75
130
  // A process-only PAT (runtime/App-seeded process.env, NOT declared in `.env`)
76
131
  // is stripped by --clearenv for this role, and a PAT is not re-mintable per
77
132
  // repo, so there is no token to inject. Tell the AGENT (model-visible block)
@@ -87,6 +142,26 @@ export default definePlugin({
87
142
  'sandbox. Configure GitHub App auth (channels.github) for per-repo, short-lived tokens that work ' +
88
143
  'for sandboxed roles, or declare the PAT in `.env` to deliberately expose it to model bash.'
89
144
 
145
+ // Deliberately claims only what this process can prove: a resolver is absent.
146
+ // It cannot tell PAT-configured from App-configured-but-adapter-down, so it
147
+ // names both remedies instead of guessing one. The closing lines exist because
148
+ // a mute refusal here is indistinguishable from broken auth, so the caller
149
+ // retries credential-management commands that are themselves blocked.
150
+ const missingAppAuthForPushReason =
151
+ 'Pushing to github.com needs an eligible credential and validated destination, and TypeClaw has nothing it can give this git command. ' +
152
+ 'Operator remedy: declare `GH_TOKEN` in the agent `.env` and restart, configure GitHub App auth under ' +
153
+ '`channels.github` for per-repo short-lived tokens, or authenticate host `gh` with ' +
154
+ '`gh auth login --hostname github.com`; the next real `typeclaw start` or `typeclaw restart` automatically captures ' +
155
+ 'that active account into the trusted-runtime store (a start against an already-running container is a no-op). ' +
156
+ 'If App auth is already configured, the adapter failed to start — check ' +
157
+ '`typeclaw logs`. Do not retry with ' +
158
+ '`gh auth setup-git`, a credential helper, or a tokenized remote URL: those are blocked and the ' +
159
+ 'credential files are masked in this sandbox.'
160
+ const multiPushStoreReason =
161
+ 'The trusted GitHub CLI credential store can fund exactly one configured push repository. ' +
162
+ 'This remote has multiple GitHub push destinations; use an authoritative declared PAT or GitHub App auth, ' +
163
+ 'or configure exactly one push URL.'
164
+
90
165
  let warnedSandboxedPatWithheld = false
91
166
  const warnSandboxedPatWithheldOnce = (): void => {
92
167
  if (warnedSandboxedPatWithheld) return
@@ -117,15 +192,17 @@ export default definePlugin({
117
192
  const result = await resolveTokenForRepo(workspace)
118
193
  return result.kind === 'token' ? result.token : null
119
194
  }
195
+ const resolveEffectiveApproval = createGithubEffectiveApprovalResolver({
196
+ resolveToken,
197
+ selfLogin: ctx.github.getAppSelfLogin ?? (() => null),
198
+ isAppAuth: hasAppTokenResolver,
199
+ })
120
200
  configureReviewVerdictCoordinator({
121
- resolveEffectiveApproval: createGithubEffectiveApprovalResolver({
122
- resolveToken,
123
- selfLogin: ctx.github.getAppSelfLogin ?? (() => null),
124
- isAppAuth: hasAppTokenResolver,
125
- }),
201
+ resolveEffectiveApproval,
126
202
  resolveHeadSha: createGithubHeadShaResolver({ resolveToken }),
127
203
  })
128
204
  const verdictGuard = createSharedReviewVerdictGuard()
205
+ const pendingDismissals = new Map<string, { workspace: string; prNumber: number }>()
129
206
 
130
207
  type HookResult = void | { block: true; reason: string }
131
208
 
@@ -200,22 +277,42 @@ export default definePlugin({
200
277
  }
201
278
  }
202
279
 
203
- const review = await noteReviewCommand({ callId: event.callId, command })
204
280
  // guard() holds the lease expecting tool.after to release it. A later
205
281
  // tool.before block means tool.after never fires, so blockAfterLease()
206
282
  // releases the lease with succeeded:false. The static command analyzer runs
207
283
  // above and never claims a lease for a command it will reject.
208
284
  let leaseClaimed = false
285
+ let dismissalLeaseClaimed = false
209
286
  const blockAfterLease = async (block: HookResult & { block: true }): Promise<HookResult> => {
210
- if (leaseClaimed) await verdictGuard.release({ callId: event.callId, succeeded: false })
287
+ if (leaseClaimed) await verdictGuard.release({ callId: event.callId, outcome: 'failed' })
288
+ if (dismissalLeaseClaimed) releaseGithubReviewRoundDismissal(event.callId, false)
289
+ pendingDismissals.delete(event.callId)
211
290
  return block
212
291
  }
292
+ const dismissal = detectReviewDismissal(command)
293
+ if (dismissal !== null) {
294
+ const block = await guardGithubReviewRoundDismissal({
295
+ callId: event.callId,
296
+ workspace: dismissal.workspace,
297
+ prNumber: dismissal.prNumber,
298
+ ...(event.origin?.kind === 'channel' && event.origin.githubReviewRound !== undefined
299
+ ? { round: event.origin.githubReviewRound, thread: event.origin.thread }
300
+ : {}),
301
+ })
302
+ if (block !== null) return block
303
+ dismissalLeaseClaimed = event.origin?.kind === 'channel' && event.origin.githubReviewRound !== undefined
304
+ pendingDismissals.set(event.callId, dismissal)
305
+ }
306
+ const review = await noteReviewCommand({ callId: event.callId, command })
213
307
  if (review.detected !== null) {
214
308
  const block = await verdictGuard.guard({
215
309
  callId: event.callId,
216
310
  workspace: review.detected.workspace,
217
311
  prNumber: review.detected.prNumber,
218
312
  verdict: review.detected.verdict,
313
+ ...(event.origin?.kind === 'channel' && event.origin.githubReviewRound !== undefined
314
+ ? { round: event.origin.githubReviewRound, thread: event.origin.thread }
315
+ : {}),
219
316
  })
220
317
  if (block !== null) return block
221
318
  leaseClaimed = true
@@ -348,21 +445,113 @@ export default definePlugin({
348
445
  }
349
446
 
350
447
  const handleGitCommand = async (params: {
351
- event: { args: Record<string, unknown> }
448
+ event: { callId: string; args: Record<string, unknown>; origin?: SessionOrigin }
352
449
  command: string
353
450
  agentDir: string
451
+ sessionId: string
354
452
  }): Promise<HookResult> => {
355
- const { event, command, agentDir } = params
356
- const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
453
+ const { event, command, agentDir, sessionId } = params
454
+ const decision = await analyzeGitCommand(command, {
455
+ cwd: agentDir,
456
+ resolvers: createSessionTmpGitResolvers(agentDir, sessionId),
457
+ })
357
458
  if (decision.kind === 'pass-through') return
358
459
  if (decision.kind === 'block') return { block: true, reason: decision.reason }
359
460
 
360
- // Only a per-repo GitHub App token is brokered to git — never a PAT (git,
361
- // unlike gh, runs repo-local hooks/helpers, and a PAT is not repo-confined).
362
- // With no App minter, pass through so git fails honestly.
363
- if (!hasAppTokenResolver()) return
364
- const result = await resolveTokenForRepo(decision.repoSlug)
365
- if (result.kind === 'unavailable') return { block: true, reason: result.reason }
461
+ const buildGitCredentialOverlay = async (
462
+ credentials: readonly GitRepoCredential[],
463
+ existing: unknown,
464
+ options: { expectedRemote?: string; pushUrls?: readonly string[]; trustedEnv?: NodeJS.ProcessEnv } = {},
465
+ ): Promise<Record<string, string>> => {
466
+ const askpass = await ensureGitAskPassHelper(resolveSandboxGitAskPassPath())
467
+ const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
468
+ return {
469
+ ...overlay,
470
+ ...buildGitCredentialEnv(credentials, askpass, options),
471
+ }
472
+ }
473
+ const destinationRepos =
474
+ decision.pushProvenance?.kind === 'configured-remote'
475
+ ? decision.pushProvenance.repoSlugs
476
+ : [decision.repoSlug.toLocaleLowerCase()]
477
+
478
+ if (!hasAppTokenResolver()) {
479
+ const declared = declaredGitCredentialState()
480
+ if (
481
+ // The analyzer emits write access only for its push subcommand grammar.
482
+ decision.access === 'write' &&
483
+ declared.kind === 'pat' &&
484
+ canUsePat(event.origin)
485
+ ) {
486
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = await buildGitCredentialOverlay(
487
+ destinationRepos.map((repoSlug) => ({ repoSlug, token: declared.value })),
488
+ event.args[TYPECLAW_INTERNAL_BASH_ENV],
489
+ {
490
+ expectedRemote:
491
+ decision.pushProvenance?.kind === 'configured-remote' ? decision.pushProvenance.remote : undefined,
492
+ pushUrls:
493
+ decision.pushProvenance?.kind === 'configured-remote' ? decision.pushProvenance.pushUrls : undefined,
494
+ trustedEnv: trustedGitTransportEnv,
495
+ },
496
+ )
497
+ // Withhold wins only when the same ambient names are absent from the overlay.
498
+ event.args[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV] = ['GH_TOKEN', 'GITHUB_TOKEN']
499
+ if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
500
+ return
501
+ }
502
+ if (decision.access !== 'write') return
503
+ if (declared.kind !== 'absent') return { block: true, reason: missingAppAuthForPushReason }
504
+ if (destinationRepos.length !== 1) return { block: true, reason: multiPushStoreReason }
505
+
506
+ const askpass = await ensureGitAskPassHelper(resolveSandboxGitAskPassPath())
507
+ const plan = await planGithubStorePush(decision, { agentDir, sessionId, askpassPath: askpass })
508
+ if (plan === null) return { block: true, reason: missingAppAuthForPushReason }
509
+ const storeToken = await resolveGithubCliStoreToken()
510
+ if (storeToken === null) return { block: true, reason: missingAppAuthForPushReason }
511
+ const credentialEnv = await buildGitCredentialOverlay(
512
+ [{ repoSlug: plan.repo, token: storeToken }],
513
+ event.args[TYPECLAW_INTERNAL_BASH_ENV],
514
+ { expectedRemote: plan.remote, trustedEnv: {} },
515
+ )
516
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = credentialEnv
517
+ const inheritedNames = [
518
+ ...Object.keys(process.env),
519
+ ...Object.keys(credentialEnv),
520
+ 'SSH_ASKPASS',
521
+ 'SSH_AUTH_SOCK',
522
+ 'HTTP_PROXY',
523
+ 'HTTPS_PROXY',
524
+ 'ALL_PROXY',
525
+ 'http_proxy',
526
+ 'https_proxy',
527
+ 'all_proxy',
528
+ ]
529
+ event.args[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV] = [
530
+ ...new Set([
531
+ ...GH_STORE_AMBIENT_AUTH_KEYS,
532
+ ...inheritedNames.filter(
533
+ (name) => name.startsWith('GIT_') || name.startsWith('SSH_') || /proxy/i.test(name),
534
+ ),
535
+ ]),
536
+ ]
537
+ event.args[TYPECLAW_INTERNAL_BASH_PREPARE] = async () => {
538
+ const prepared = await prepareGithubStorePush(plan)
539
+ if (prepared === null) throw new Error(missingAppAuthForPushReason)
540
+ return {
541
+ command: prepared.command,
542
+ env: prepared.env,
543
+ mount: prepared.mount,
544
+ cleanup: async () => await cleanupPreparedGithubStorePush(prepared.backingGitDir),
545
+ }
546
+ }
547
+ return
548
+ }
549
+ const credentials: GitRepoCredential[] = []
550
+ for (const repoSlug of destinationRepos) {
551
+ const result = await resolveTokenForRepo(repoSlug)
552
+ if (result.kind === 'unavailable') return { block: true, reason: result.reason }
553
+ credentials.push({ repoSlug, token: result.token })
554
+ }
366
555
 
367
556
  // Deliver the token via GIT_ASKPASS (env, never argv/config). The analyzer
368
557
  // already constrained this to a single bare github git command, so the token
@@ -373,26 +562,17 @@ export default definePlugin({
373
562
  // belong in a separate agent (see docs/internals/sandbox.mdx).
374
563
  // Sandboxed bash: the helper must be on a sandbox-visible path (baked /usr),
375
564
  // not the unsandboxed /tmp default the tmpfs would hide.
376
- const askpass = await ensureGitAskPassHelper(resolveSandboxGitAskPassPath())
377
- const existing = event.args[TYPECLAW_INTERNAL_BASH_ENV]
378
- const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
379
- event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
380
- ...overlay,
381
- GIT_ASKPASS: askpass,
382
- TYPECLAW_GIT_TOKEN: result.token,
383
- GIT_TERMINAL_PROMPT: '0',
384
- GIT_CONFIG_COUNT: '4',
385
- GIT_CONFIG_KEY_0: 'core.hooksPath',
386
- GIT_CONFIG_VALUE_0: '/dev/null',
387
- GIT_CONFIG_KEY_1: 'credential.helper',
388
- GIT_CONFIG_VALUE_1: '',
389
- // Both ssh remote spellings fold to https so the askpass credential applies:
390
- // the scp short form (git@github.com:owner/repo) and the ssh:// URL form.
391
- GIT_CONFIG_KEY_2: 'url.https://github.com/.insteadOf',
392
- GIT_CONFIG_VALUE_2: 'git@github.com:',
393
- GIT_CONFIG_KEY_3: 'url.https://github.com/.insteadOf',
394
- GIT_CONFIG_VALUE_3: 'ssh://git@github.com/',
395
- }
565
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = await buildGitCredentialOverlay(
566
+ credentials,
567
+ event.args[TYPECLAW_INTERNAL_BASH_ENV],
568
+ {
569
+ expectedRemote:
570
+ decision.pushProvenance?.kind === 'configured-remote' ? decision.pushProvenance.remote : undefined,
571
+ pushUrls:
572
+ decision.pushProvenance?.kind === 'configured-remote' ? decision.pushProvenance.pushUrls : undefined,
573
+ trustedEnv: trustedGitTransportEnv,
574
+ },
575
+ )
396
576
  if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
397
577
  return
398
578
  }
@@ -410,18 +590,45 @@ export default definePlugin({
410
590
  }
411
591
 
412
592
  if (command.includes('git')) {
413
- return await handleGitCommand({ event, command, agentDir: ctx.agentDir })
593
+ return await handleGitCommand({ event, command, agentDir: ctx.agentDir, sessionId: event.sessionId })
414
594
  }
415
595
  return
416
596
  },
417
597
  'tool.after': async (event) => {
418
598
  checkGraphqlAuthNudge({ tool: event.tool, result: event.result })
599
+ const dismissal = pendingDismissals.get(event.callId)
600
+ pendingDismissals.delete(event.callId)
601
+ if (dismissal !== undefined) {
602
+ // Only an AUTHORITATIVELY verified dismissal may latch the round's
603
+ // one-attempt marker. Latching on a failed mutation — or on a
604
+ // succeeded mutation whose verifying read errored, where we cannot
605
+ // tell whether the block cleared — bars every retry AND suppresses
606
+ // carrier failover, stranding the round with all siblings gated
607
+ // forever. Unverified therefore releases the latch so the next
608
+ // attempt can re-read authoritative state.
609
+ let verified = false
610
+ try {
611
+ if (dismissalMutationSucceeded(event.result)) {
612
+ const effective = await resolveEffectiveApproval(dismissal)
613
+ if (effective.ok && effective.effective === 'DISMISSED') {
614
+ recordVerifiedDismissal({
615
+ sessionId: event.sessionId,
616
+ workspace: dismissal.workspace,
617
+ prNumber: dismissal.prNumber,
618
+ })
619
+ verified = true
620
+ }
621
+ }
622
+ } finally {
623
+ releaseGithubReviewRoundDismissal(event.callId, verified)
624
+ }
625
+ }
419
626
  const review = commitReviewIfSucceeded({
420
627
  sessionId: event.sessionId,
421
628
  callId: event.callId,
422
629
  result: event.result,
423
630
  })
424
- await verdictGuard.release({ callId: event.callId, succeeded: review.committed })
631
+ await verdictGuard.release({ callId: event.callId, outcome: review.committed ? 'formal-landed' : 'failed' })
425
632
  // A backstop-recovered verdict had no guard() reservation, so release()
426
633
  // could not arm the lag shield — do it explicitly here so the next
427
634
  // same-commit submission is deduped.
@@ -77,6 +77,11 @@ export type CommitReviewResult = {
77
77
  landedFromResult: DetectedReview | null
78
78
  }
79
79
 
80
+ export function dismissalMutationSucceeded(result: ToolResult): boolean {
81
+ const text = collectText(result.content)
82
+ return !FAILURE_MARKERS.some((marker) => text.includes(marker)) && /"state"\s*:\s*"DISMISSED"/.test(text)
83
+ }
84
+
80
85
  export function commitReviewIfSucceeded(args: {
81
86
  sessionId: string
82
87
  callId: string
@@ -1,29 +1,11 @@
1
1
  import { definePlugin } from '@/plugin'
2
2
 
3
- import {
4
- checkManagedConfigGuard,
5
- checkMemoryTopicsDeleteGuard,
6
- checkNonWorkspaceWriteGuard,
7
- checkSkillAuthoringGuard,
8
- checkUncommittedChangesAdvice,
9
- } from './policy'
3
+ import { checkMemoryTopicsDeleteGuard, checkUncommittedChangesAdvice } from './policy'
10
4
 
11
5
  export default definePlugin({
12
6
  plugin: async () => ({
13
7
  hooks: {
14
8
  'tool.before': async (event, ctx) => {
15
- const managedConfigResult = await checkManagedConfigGuard({
16
- tool: event.tool,
17
- args: event.args,
18
- agentDir: ctx.agentDir,
19
- })
20
- if (managedConfigResult) return managedConfigResult
21
- const skillResult = await checkSkillAuthoringGuard({
22
- tool: event.tool,
23
- args: event.args,
24
- agentDir: ctx.agentDir,
25
- })
26
- if (skillResult) return skillResult
27
9
  const memoryTopicsDeleteResult = checkMemoryTopicsDeleteGuard({
28
10
  tool: event.tool,
29
11
  args: event.args,
@@ -31,12 +13,7 @@ export default definePlugin({
31
13
  origin: event.origin,
32
14
  })
33
15
  if (memoryTopicsDeleteResult) return memoryTopicsDeleteResult
34
- return checkNonWorkspaceWriteGuard({
35
- tool: event.tool,
36
- args: event.args,
37
- agentDir: ctx.agentDir,
38
- origin: event.origin,
39
- })
16
+ return undefined
40
17
  },
41
18
  'tool.after': async (event, ctx) => {
42
19
  await checkUncommittedChangesAdvice({
@@ -0,0 +1,8 @@
1
+ // Keep this module import-free: acknowledgement folding runs during module
2
+ // evaluation, and cycles through key owners can throw a temporal-dead-zone ReferenceError.
3
+ export const ACKNOWLEDGE_GUARDS = 'acknowledgeGuards'
4
+ export const GUARD_IMAGE_READ_REDIRECT = 'imageReadRedirect'
5
+ export const GUARD_NON_WORKSPACE_WRITE = 'nonWorkspaceWrite'
6
+ export const GUARD_GLOBAL_INSTALL = 'globalInstall'
7
+ export const GUARD_NON_BUN_PACKAGE_MANAGER = 'nonBunPackageManager'
8
+ export const GUARD_NON_BUN_PACKAGE_RUNNER = 'nonBunPackageRunner'
@@ -1,14 +1,15 @@
1
1
  import { realpath } from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
 
4
+ import type { InternalGuardResult } from '@/agent/guard-types'
4
5
  import type { SessionOrigin } from '@/agent/session-origin'
5
6
  import { RECOVER_MISSING, realIntendedPath } from '@/path-safety/real-intended-path'
6
7
 
7
- import { ACKNOWLEDGE_GUARDS, type GuardBlock, isGuardAcknowledged } from '../policy'
8
+ import { GUARD_NON_WORKSPACE_WRITE } from '../keys'
8
9
  import { isMemoryTopicsWriteAllowed } from './memory-topics-write'
9
10
  import { isSkillAuthoringAllowed } from './skill-authoring'
10
11
 
11
- export const GUARD_NON_WORKSPACE_WRITE = 'nonWorkspaceWrite'
12
+ export { GUARD_NON_WORKSPACE_WRITE } from '../keys'
12
13
 
13
14
  const AGENT_ROOT_WRITE_ALLOWLIST = new Set([
14
15
  'AGENTS.md',
@@ -33,7 +34,7 @@ export async function checkNonWorkspaceWriteGuard(options: {
33
34
  args: Record<string, unknown>
34
35
  agentDir: string
35
36
  origin?: SessionOrigin
36
- }): Promise<GuardBlock | undefined> {
37
+ }): Promise<InternalGuardResult> {
37
38
  const { tool, args, agentDir, origin } = options
38
39
  if (tool !== 'write' && tool !== 'edit') return undefined
39
40
 
@@ -50,7 +51,7 @@ export async function checkNonWorkspaceWriteGuard(options: {
50
51
  ])
51
52
  if (await isOperatorOwnedPackageManifest(agentDir, targetPath, realTargetPath)) {
52
53
  return {
53
- block: true,
54
+ kind: 'block',
54
55
  reason: `Guard \`${GUARD_NON_WORKSPACE_WRITE}\` blocked a model write to operator-owned package manifest ${targetPath}.`,
55
56
  }
56
57
  }
@@ -68,14 +69,12 @@ export async function checkNonWorkspaceWriteGuard(options: {
68
69
  // and a `/tmp/link -> /agent/.env`) and must not land inside the agent dir
69
70
  // (a container/test agent dir can itself sit under /tmp).
70
71
  if (isTmpScratchWrite(rawPath, realTargetPath, realAgentDir, realTmpRoot)) return undefined
71
- if (isGuardAcknowledged(args, GUARD_NON_WORKSPACE_WRITE)) return undefined
72
-
73
72
  return {
74
- block: true,
73
+ kind: 'acknowledgement-required',
75
74
  reason: [
76
75
  `Guard \`${GUARD_NON_WORKSPACE_WRITE}\` blocked ${tool} outside the workspace: ${targetPath}.`,
77
76
  `The free-write zone is ${workspacePath}.`,
78
- `Retry with \`${ACKNOWLEDGE_GUARDS}.${GUARD_NON_WORKSPACE_WRITE}: true\` only if this write is intentional.`,
77
+ `Retry with \`acknowledgeGuards.guard.${GUARD_NON_WORKSPACE_WRITE}: true\` only if this write is intentional.`,
79
78
  ].join(' '),
80
79
  }
81
80
  }
@@ -1,13 +1,7 @@
1
- export const ACKNOWLEDGE_GUARDS = 'acknowledgeGuards'
1
+ export { ACKNOWLEDGE_GUARDS } from './keys'
2
2
 
3
3
  export type GuardBlock = { block: true; reason: string }
4
4
 
5
- export function isGuardAcknowledged(args: Record<string, unknown>, guard: string): boolean {
6
- const acknowledgements = args[ACKNOWLEDGE_GUARDS]
7
- if (!acknowledgements || typeof acknowledgements !== 'object') return false
8
- return (acknowledgements as Record<string, unknown>)[guard] === true
9
- }
10
-
11
5
  export { GUARD_MANAGED_CONFIG, checkManagedConfigGuard } from './policies/managed-config'
12
6
  export { GUARD_NON_WORKSPACE_WRITE, checkNonWorkspaceWriteGuard } from './policies/non-workspace-write'
13
7
  export {