SLOPSHOPPER

shared-repo-guard

For repos where several AI agents (or you and an agent) work in the same folder: stops secret values from leaving your .env, pushes to public remotes, and git…

bandguardcommandtoastprocess
v0.1.4MITupdated 2026-10-12naoanao/shared-repo-guard
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · shared-repo-guard
› fix the failing auth test and add an audit log call ╭───────────────────────────────────────────╮ │ shared-repo-guard │ ⏺ Read(src/auth.ts) │ shared-repo-guard stopped: This prints a │ ⎿ Read 6 lines ╰───────────────────────────────────────────╯ ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(cat .env) ⎿ Denied by shared-repo-guard: shared-repo-guard: This prints a .env file. Read the value inside a script an ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /guard ⎿ shared-repo-guard: Secret values watched: 0 ⎿ shared-repo-guard: Public remotes: none set ⎿ shared-repo-guard: Stopped this session: 1 ⎿ shared-repo-guard: Uncommitted files this session did not write (protected): 1 ⎿ shared-repo-guard: src/auth.ts ⎿ shared-repo-guard: ?? src/auth.test.ts shared-repo-guard: 1 uncommitted file(s) from outside this session are protected (/guard) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
shared-repo-guard: 1 uncommitted file(s) from outside this session are protected (/guard)
README

shared-repo-guard

A Claude Code mod for repos where more than one AI agent works in the same folder.

I run Claude Code and a second coding agent on one repository, often at the same time and under the same git name. Over two years that setup produced these incidents:

  • An agent wrote a live API key straight into a shell command.
  • An admin secret ended up in a URL query string and was copied into a work report.
  • One agent cleaned up the working tree and deleted the other agent's uncommitted work. It could not be recovered.
  • A script rewrote line endings, and a 29-line change became a 2,356-line diff.

Popular guard collections already block reading .env and force-pushing to main. They don't cover the incidents above, so this mod handles those.

What it stops

What happensWhy
Secret valuesAny shell command, file write, or tool call (browser, MCP and others) that contains the actual value of a secret from your .env is refused. If a value turns up in a command's output, it is masked before the model sees it.Blocking the .env file isn't enough once the value has been copied somewhere else.
Other agents' workgit reset --hard, checkout ., restore, stash and clean -f are refused when the tree holds uncommitted files that this session did not write. It does not ask: in a desktop session in auto mode, a mod's question was seen to come back answered without any dialog, so a question cannot stand in for you. Run the command yourself in your own terminal when you mean it. git add -A (and the same thing written as ., ./, :/ or *) is refused in the same situation.Another agent's half-finished work looks like junk to the agent that didn't write it.
Public remotesPushes to remotes you mark as public are refused, and so are push --all and --mirror.A repo with a private origin and a public mirror is one typo away from publishing everything.
Printing .envcat .env and similar commands are refused, and so is opening .env with the Read tool. .env.example is allowed.

Commands

  • /guard shows how many secret values are watched, which remotes are marked public, what was stopped, and which uncommitted files are protected.
  • /preflight runs before you push. It checks unpushed commits for line-ending churn, secret-looking strings (Stripe, OpenAI/Anthropic, GitHub, Google, AWS, private keys, JWTs), committed .env files, and files this session did not write.

While protected files exist, a quiet line above the prompt shows how many there are.

Install

/plugin marketplace add naoanao/shared-repo-guard
/plugin install shared-repo-guard@shared-repo-guard

The install screen asks for two optional settings:

  • Public remotes: remote names that must never be pushed to, for example public, mirror.
  • Extra .env files: .env files below the repository root, for example apps/web/.env.local. Every .env* file at the root is watched automatically.

How it works

  • Secret values are read from your .env files when the session starts. They are kept in memory only and never written, logged, or shown. A key counts as a secret when its name contains SECRET, KEY, TOKEN, PASSWORD, PRIVATE, CREDENTIAL, WEBHOOK, SIGNING, AUTH, DSN or DATABASE_URL and its value is at least 12 characters long. Public build variables (NEXT_PUBLIC_, VITE_, PUBLIC_, EXPO_PUBLIC_, REACT_APP_) are skipped.
  • A file counts as "written by this session" when it was changed through Claude's Write or Edit tools. Every other uncommitted change is treated as someone else's. If this session changed a file through a shell command instead, you get a question rather than a silent loss.
  • Options between git and its command (git -C <dir>, -c key=value, --no-pager and the like) are looked through, so git -C other-repo add -A is caught too.
  • Commit messages are text, not commands, so words in them do not trigger a rule: the -m "..." of git commit, and a here-document given to git commit or written to a file. A message holding $(...) or backticks is still checked, because the shell runs those, unless the here-document tag is quoted (<<'EOF'), which keeps them as plain text.
  • If the guard itself fails while checking a shell command, the command does not run.

What it reads, runs, and sends

  • Sends nothing. The mod makes no network requests and does not upload, log, or store anything. It has no telemetry.
  • Reads:
  • .env* files in the repository root, plus any files you list under "Extra .env files". It reads them only to learn the secret values to watch for. The values stay in memory and are compared against what tools are about to run or return.
  • Each tool call's input and output (shell commands, file writes, and other tool arguments). It looks for those secret values there and masks them in output.
  • Runs: only git, through its own read-only queries:
  • git rev-parse --show-toplevel to find the repository root
  • git rev-parse --abbrev-ref --symbolic-full-name @{u} to find the upstream branch
  • git status --porcelain=v1 -z --untracked-files=all to list uncommitted files
  • git log <upstream>..HEAD, plus git diff (with --shortstat, --ignore-cr-at-eol --shortstat and --name-only against the upstream) for /preflight

None of these change your repository.

  • Changes:
  • It refuses tool calls, using the rules above.
  • It replaces secret values in tool output with [shared-repo-guard: secret hidden].
  • Hooks:
  • tool.call on Bash, PowerShell, Read, Write, Edit and every other tool, for the checks above
  • session.start and turn.complete to refresh the list of uncommitted files
  • ui.render for the one-line notice above the prompt
  • command.run for /guard and /preflight

How it differs from similar mods

  • blast-radius (Anthropic sample) holds rm -rf and force pushes. This mod targets a different loss: uncommitted work that belongs to someone else.
  • secret-redactor and claude-code-redact mask secrets in what the model reads. This mod also refuses commands, file writes and tool calls that would carry a secret value out.
  • Collision Guard asks before another chat edits a file that was changed recently. This mod covers other agents and tools that never pass through Claude Code. It protects any uncommitted file this session did not write.

Limits

  • It only sees what passes through Claude Code. Other agents and your own terminal are not covered.
  • Shell commands are parsed roughly: ;, &&, || and new lines are split, but quoting is not. That way it errs toward stopping.
  • It is not a secret scanner for your whole history. Use gitleaks or GitHub secret scanning for that.

Tests

claude plugin test .

There are 15 tests. They cover the rules plus the whole mod running in Claude Code's test engine, with a fake git and a fake .env. Each guard was broken on purpose once to confirm that its test fails for the right reason.

Also in this marketplace

  • context-saver: a line above the prompt with context and usage, a heads-up at 80% and one compaction at 90%, a stop on reading huge files whole, and long shell output cut to its head and tail. /plugin install context-saver@shared-repo-guard

About

Made by nao, an AI consultant who builds. I design and run AI automation for small businesses, from first conversation to production. Portfolio: https://growl-ai.com/portfolio/en

Also by me: agent-cross-check. When another coding agent commits to your repo, Claude notices and audits the commits by diff and tests, not by the agent's report.

MIT License.


日本語

同じフォルダで複数の AI に作業させている人のための、Claude Code の見張りです。

止めるものは次のとおりです。

  • 鍵の値:.env にある鍵の値が、コマンド・ファイル・ほかの道具に入ろうとしたら止めます。コマンドの出力に鍵の値が出たときは、伏せ字にしてから AI に渡します。
  • 別の AI の作業:このセッションが書いていない保存前の変更があるとき、git reset --hard などの消すコマンドを止めます(聞きません。デスクトップの自動モードでは、Mod の質問が窓を出さずに答えつきで返ることがあったため)。本当に必要なら、ご自分の端末で打ってください。git add -A(.・./・:/・* と書いた場合も)も同じ状況では止めます。保存のメモの中の文字では止めません($(…) を含むメモは確かめます)。
  • 公開の送り先:公開と指定した送り先への送信を止めます。
  • .env の表示:.env の中身を画面に出すことを止めます。

入れ方は上の「Install」と同じです。/guard で今の見張りの状態を、/preflight で送る前の点検(改行の変化・鍵らしい文字・.env の混入・別の AI の作業)を見られます。

同じ置き場に、会話を軽く保つ context-saver もあります(入力欄の上に使用量を出す・80%で知らせて90%で1回まとめる・巨大なファイルの丸読みを止める・長い出力を頭と末尾だけにする)。/plugin install context-saver@shared-repo-guard で入ります。

Source 2 files
hooks/register.tsx 187 lines
1import {
2  parseList, pushToPublic, addAll, destructiveGit, printsEnvFile, readsEnvFile,
3  secretValuesFrom, containsSecret, redact, statusPaths, relativeToRoot, foreignChanges,
4  secretPatternHits, lineEndingChurn,
5} from './rules.js'
6
7// Held only inside this module. Never written to the screen, a log or a file.
8let secrets = []
9let blocked = 0
10let root = ''
11let written = []
12let foreign = []
13let publicRemotes = []
14let extraEnvFiles = []
15
16async function git($, args) {
17  try {
18    const r = await $.process.run(['git', ...args], { cwd: root || undefined, timeoutMs: 20000 })
19    return r.exitCode === 0 ? String(r.stdout || '') : ''
20  } catch {
21    return ''
22  }
23}
24
25async function findRoot($) {
26  try {
27    const r = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 10000 })
28    root = r.exitCode === 0 ? String(r.stdout || '').trim() : ''
29  } catch {
30    root = ''
31  }
32}
33
34async function loadSecrets($) {
35  const found = new Set()
36  const base = root || (await $.session.cwd())
37  const files = new Set(extraEnvFiles.map((f) => base + '/' + f))
38  try {
39    for (const entry of await $.fs.list(base)) {
40      const n = String(entry?.name || '')
41      if (/^\.env(\.|$)/.test(n) && !/\.(example|sample|template)$/.test(n)) files.add(base + '/' + n)
42    }
43  } catch {
44    // an unreadable folder adds nothing
45  }
46  for (const f of files) {
47    try {
48      if (!(await $.fs.exists(f))) continue
49      for (const v of secretValuesFrom(await $.fs.read(f))) found.add(v)
50    } catch {
51      // an unreadable file is skipped
52    }
53  }
54  secrets = [...found]
55}
56
57async function refreshForeign($) {
58  if (!root) {
59    foreign = []
60    return
61  }
62  foreign = foreignChanges(statusPaths(await git($, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])), written)
63  $.ui.invalidate('ui.render')
64}
65
66function listFew(paths) {
67  const head = paths.slice(0, 10).join('\n  ')
68  return '  ' + head + (paths.length > 10 ? '\n  ...and ' + (paths.length - 10) + ' more' : '')
69}
70
71function deny($, reason) {
72  blocked += 1
73  $.ui.toast('shared-repo-guard stopped: ' + reason.split('.')[0])
74  return { deny: 'shared-repo-guard: ' + reason }
75}
76
77async function preflight($) {
78  if (!root) return 'Not inside a git repository.'
79  const out = []
80  const upstream = (await git($, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).trim()
81  if (!upstream) {
82    out.push('No upstream branch, so there is nothing to compare against.')
83  } else {
84    const log = (await git($, ['log', upstream + '..HEAD', '--format=%h %ad %an %s', '--date=short'])).trim()
85    out.push('Unpushed commits on top of ' + upstream + ': ' + (log ? log.split('\n').length : 0))
86    if (log) {
87      out.push(log)
88      const churn = lineEndingChurn(
89        await git($, ['diff', '--shortstat', upstream, 'HEAD']),
90        await git($, ['diff', '--ignore-cr-at-eol', '--shortstat', upstream, 'HEAD']),
91      )
92      out.push('Line endings: ' + (churn ? 'CHANGED (diff shows ' + churn.shown + ' lines, real content ' + churn.real + ')' : 'unchanged'))
93      const hits = secretPatternHits(await git($, ['diff', upstream, 'HEAD']))
94      out.push('Secret-looking strings: ' + (hits.length ? hits.join(', ') : 'none'))
95      const files = (await git($, ['diff', '--name-only', upstream, 'HEAD'])).trim()
96      const envs = files.split('\n').filter((f) => /(^|\/)\.env(\.|$)/.test(f) && !/\.(example|sample|template)$/.test(f))
97      if (envs.length) out.push('.env files in the commits: ' + envs.join(', '))
98    }
99  }
100  await refreshForeign($)
101  out.push('Uncommitted files this session did not write: ' + foreign.length + (foreign.length ? '\n' + listFew(foreign) : ''))
102  return out.join('\n')
103}
104
105export function register(on, options) {
106  publicRemotes = parseList(options?.publicRemotes)
107  extraEnvFiles = parseList(options?.envFiles)
108
109  on('session.start', async ($, e, next) => {
110    await findRoot($)
111    await loadSecrets($)
112    await $.command.register({ name: 'guard', description: 'shared-repo-guard: what it watches and what it stopped' })
113    await $.command.register({ name: 'preflight', description: 'Check unpushed commits: line endings, secrets, .env files, other agents\' changes' })
114    await refreshForeign($)
115    return next(e)
116  })
117
118  on('turn.complete', async ($, e, next) => {
119    await refreshForeign($)
120    return next(e)
121  })
122
123  on('command.run', { command: 'guard' }, async ($) => {
124    await loadSecrets($)
125    await refreshForeign($)
126    return {
127      text: [
128        'Secret values watched: ' + secrets.length,
129        'Public remotes: ' + (publicRemotes.length ? publicRemotes.join(', ') : 'none set'),
130        'Stopped this session: ' + blocked,
131        'Uncommitted files this session did not write (protected): ' + foreign.length + (foreign.length ? '\n' + listFew(foreign) : ''),
132      ].join('\n'),
133    }
134  })
135
136  on('command.run', { command: 'preflight' }, async ($) => ({ text: await preflight($) }))
137
138  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
139    if (e.props.hasSurvey || foreign.length === 0) return next(e)
140    const { Text } = $.ui.resolve(e)
141    return <Text dimColor>shared-repo-guard: {foreign.length} uncommitted file(s) from outside this session are protected (/guard)</Text>
142  })
143
144  on('tool.call', { tool: ['Bash', 'PowerShell'] }, async ($, e, next) => {
145    const cmd = String(e.command || '')
146    const r = pushToPublic(cmd, publicRemotes) || printsEnvFile(cmd)
147    if (r) return deny($, r)
148    if (containsSecret(cmd, secrets)) return deny($, 'The command contains a secret value from your .env. Read it from the environment instead of writing it out.')
149    if (addAll(cmd)) {
150      await refreshForeign($)
151      if (foreign.length) return deny($, 'git add -A would stage ' + foreign.length + ' file(s) this session did not write. Add your own files by name.\n' + listFew(foreign))
152    }
153    const d = destructiveGit(cmd)
154    if (d) {
155      await refreshForeign($)
156      // Refused without asking: in a desktop session in auto mode, $.ui.ask was seen to return an answer
157      // without showing any dialog (measured 2026-10-10), so a question cannot stand in for the user.
158      if (foreign.length) {
159        return deny($, d + ' was stopped because it would discard uncommitted work this session did not write (' + foreign.length + ' file(s)). Leave those files alone, or run the command yourself in your own terminal.\n' + listFew(foreign))
160      }
161    }
162    return redact(await next(e), secrets)
163  }).catch(async () => ({ deny: 'shared-repo-guard could not check this command, so it did not run.' }))
164
165  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
166    const r = readsEnvFile(e.file_path)
167    if (r) return deny($, r)
168    return redact(await next(e), secrets)
169  })
170
171  on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
172    const text = String(e.content || '') + '\n' + String(e.new_string || '')
173    if (containsSecret(text, secrets)) return deny($, 'This writes a secret value into a file. Refer to the variable name instead.')
174    const result = await next(e)
175    const rel = relativeToRoot(String(e.file_path || ''), root)
176    if (rel && !written.includes(rel)) written.push(rel)
177    return result
178  })
179
180  on('tool.call', { tool: /^(?!(Bash|PowerShell|Read|Write|Edit)$)/ }, async ($, e, next) => {
181    let text = ''
182    try { text = JSON.stringify(e) } catch { text = '' }
183    if (containsSecret(text, secrets)) return deny($, 'This passes a secret value to ' + e.tool + '.')
184    return next(e)
185  })
186}
187
hooks/rules.js 222 lines
1// Pure decision functions. No engine calls here, so the tests can call them directly.
2
3// Split a shell line on ; && || and newlines. Quotes are not parsed: rough, but it errs toward stopping.
4function splitCommands(cmd) {
5  return String(cmd || '').split(/;|&&|\|\||\n/)
6}
7
8// "word" and 'word' become word; quoted text with spaces is left as it is.
9function unquoteWords(s) {
10  return String(s || '').replace(/(["'])([^"'\s]+)\1/g, '$2')
11}
12
13// git -C <dir> add … / git -c key=value reset … / git --no-pager stash …: drop the options between git and its command.
14function withoutGitOptions(s) {
15  return String(s || '').replace(/\bgit((?:\s+(?:-C|-c|--git-dir|--work-tree|--namespace|--exec-path|--config-env)(?:=|\s+)\S+|\s+-[A-Za-z-][\w-]*(?:=\S+)?)*)(?=\s)/g, 'git')
16}
17
18// Drop commit messages, which are text and never run: the -m "..." of git commit, and the body of a
19// here-document given to git commit or written to a file. A here-document that is run (bash <<EOF) stays,
20// and so does any message holding $(...) or backticks, because the shell runs those.
21function withoutMessages(cmd) {
22  let s = String(cmd || '')
23  s = s.replace(/<<-?\s*(['"]?)(\w+)\1([^\n]*)\n([\s\S]*?)\n[ \t]*\2[ \t]*(?=\n|$)/g, (all, q, tag, rest, body, offset) => {
24    if (!q && /\$\(|`/.test(body)) return all // unquoted tag: the shell runs $(...) and backticks in the body
25    const opener = s.slice(s.lastIndexOf('\n', offset) + 1, offset) + rest
26    return /\bgit\s+commit\b/.test(opener) || />/.test(opener) ? '<<' + tag + rest + '\n' + tag : all
27  })
28  if (/\bgit\s+commit\b/.test(s)) {
29    s = s.replace(/(\s(?:-m|--message)(?:=|\s+))("(?:[^"\\]|\\.)*"|'[^']*')/g, (all, flag, msg) => (/\$\(|`/.test(msg) ? all : flag + '""'))
30  }
31  return s
32}
33
34// Comma or whitespace separated list from a userConfig string.
35export function parseList(value) {
36  return String(value || '')
37    .split(/[,\s]+/)
38    .map((s) => s.trim())
39    .filter(Boolean)
40}
41
42// git push to a remote the user marked public, or push --all / --mirror.
43export function pushToPublic(cmd, publicRemotes) {
44  for (const raw of splitCommands(withoutMessages(cmd))) {
45    // The shell drops quotes, so "public" and 'public' push to the same remote as public.
46    // Only single quoted words are unwrapped, so a message like -m "push to public" stays a message.
47    const part = unquoteWords(raw)
48    if (!/\bgit\b/.test(part) || !/\bpush\b/.test(part)) continue
49    for (const r of publicRemotes || []) {
50      const esc = r.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
51      if (new RegExp('\\bpush\\b.*(^|\\s)' + esc + '(\\s|$|:)').test(part)) {
52        return 'This pushes to "' + r + '", which is marked as a public remote. Push to your private remote instead.'
53      }
54    }
55    if (/\s--(all|mirror)\b/.test(part)) return 'git push --all / --mirror sends every branch at once. Push the current branch only.'
56  }
57  return null
58}
59
60// git add -A / --all / . / ./ / :/ / * (stages everything, including other agents' work)
61export function addAll(cmd) {
62  for (const raw of splitCommands(withoutMessages(cmd))) {
63    const part = withoutGitOptions(raw)
64    const m = part.match(/\bgit\s+add\b(.*)$/)
65    if (!m) continue
66    const args = ' ' + unquoteWords(m[1]) + ' '
67    if (/\s(-A|--all|\.\/?|:\/|\*|-[a-zA-Z]*A[a-zA-Z]*)\s/.test(args)) return 'git add -A'
68  }
69  return null
70}
71
72// git commands that throw away uncommitted work with no way back.
73export function destructiveGit(cmd) {
74  for (const raw of splitCommands(withoutMessages(cmd))) {
75    const part = withoutGitOptions(raw)
76    if (!/\bgit\b/.test(part)) continue
77    if (/\bgit\s+reset\b.*\s--hard\b/.test(part)) return 'git reset --hard'
78    if (/\bgit\s+checkout\b.*\s--(\s|$)/.test(part)) return 'git checkout -- <file>'
79    if (/\bgit\s+checkout\s+\.(\s|$)/.test(part)) return 'git checkout .'
80    if (/\bgit\s+restore\b/.test(part) && (!/\s--staged\b/.test(part) || /\s--worktree\b/.test(part))) return 'git restore'
81    if (/\bgit\s+stash\b/.test(part) && !/\bgit\s+stash\s+(list|show)\b/.test(part)) return 'git stash'
82    if (/\bgit\s+clean\b.*\s-[a-zA-Z]*f/.test(part)) return 'git clean -f'
83  }
84  return null
85}
86
87// A shell command that prints a .env file to the screen.
88export function printsEnvFile(cmd) {
89  const reader = /\b(cat|type|Get-Content|gc|more|less|head|tail|bat|nl|strings|xxd|od)\b[^|;&\n]*?[\\/\s'"]\.env(\.[\w.-]*)?\b/i
90  return reader.test(String(cmd || ''))
91    ? 'This prints a .env file. Read the value inside a script and never print it.'
92    : null
93}
94
95// The Read tool opening a .env file (.env.example is a template, so it passes).
96export function readsEnvFile(path) {
97  if (typeof path !== 'string') return null
98  const name = path.split(/[\\/]/).pop() || ''
99  if (!/^\.env(\..+)?$/.test(name)) return null
100  if (/\.(example|sample|template)$/.test(name)) return null
101  return 'Opening a .env file puts its secrets into the conversation. Use the variable names only.'
102}
103
104// Key names that hold secrets. Public build-time variables are skipped.
105const SECRET_NAME = /(SECRET|KEY|TOKEN|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|WEBHOOK|SIGNING|AUTH|DSN|DATABASE_URL)/i
106const PUBLIC_NAME = /^(NEXT_PUBLIC_|VITE_|PUBLIC_|EXPO_PUBLIC_|REACT_APP_)/
107
108// Secret values from a .env body. Short values are skipped to avoid matching ordinary words.
109export function secretValuesFrom(text) {
110  const out = []
111  for (const raw of String(text || '').split(/\r?\n/)) {
112    const line = raw.trim()
113    if (!line || line.startsWith('#')) continue
114    const m = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/)
115    if (!m) continue
116    const key = m[1]
117    let val = m[2].trim()
118    if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1)
119    if (PUBLIC_NAME.test(key) || !SECRET_NAME.test(key)) continue
120    if (val.length < 12) continue
121    out.push(val)
122  }
123  return out
124}
125
126export function containsSecret(text, secrets) {
127  if (!text || !secrets || secrets.length === 0) return false
128  for (const s of secrets) if (text.includes(s)) return true
129  return false
130}
131
132// Copy of a tool result with secret values masked (frozen input is never touched).
133export function redact(value, secrets) {
134  if (!secrets || secrets.length === 0) return value
135  if (typeof value === 'string') {
136    let v = value
137    for (const s of secrets) if (v.includes(s)) v = v.split(s).join('[shared-repo-guard: secret hidden]')
138    return v
139  }
140  if (Array.isArray(value)) return value.map((x) => redact(x, secrets))
141  if (value && typeof value === 'object') {
142    const o = {}
143    for (const k of Object.keys(value)) o[k] = redact(value[k], secrets)
144    return o
145  }
146  return value
147}
148
149// Paths from `git status --porcelain=v1 -z --untracked-files=all`. Renames give two entries; both count.
150export function statusPaths(z) {
151  const parts = String(z || '').split('\0').filter(Boolean)
152  const out = []
153  for (let i = 0; i < parts.length; i++) {
154    const entry = parts[i]
155    if (entry.length < 4) continue
156    out.push(normPath(entry.slice(3)))
157    if (entry[0] === 'R' || entry[0] === 'C') {
158      if (parts[i + 1]) out.push(normPath(parts[i + 1]))
159      i++
160    }
161  }
162  return out
163}
164
165// Forward slashes and lower case, so Windows and git spellings compare equal.
166export function normPath(p) {
167  return String(p || '').replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase()
168}
169
170// A file path from a tool call, relative to the repository root, or null when it lies outside.
171export function relativeToRoot(filePath, root) {
172  const f = normPath(filePath)
173  const r = normPath(root).replace(/\/$/, '')
174  if (!r) return null
175  if (f.startsWith(r + '/')) return f.slice(r.length + 1)
176  return null
177}
178
179// Uncommitted paths this session did not write: another agent's or a person's work.
180export function foreignChanges(currentPaths, writtenBySession) {
181  const mine = new Set((writtenBySession || []).map(normPath))
182  return [...new Set((currentPaths || []).map(normPath))].filter((p) => !mine.has(p))
183}
184
185// Known secret formats in the added lines of a diff.
186export function secretPatternHits(diffText) {
187  const pats = {
188    'Stripe live key': /sk_live_[A-Za-z0-9]{8,}/g,
189    'Stripe test key': /sk_test_[A-Za-z0-9]{8,}/g,
190    'JWT': /eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}/g,
191    'GitHub token': /gh[pousr]_[A-Za-z0-9]{20,}/g,
192    'OpenAI / Anthropic key': /sk-(ant-)?[A-Za-z0-9_-]{20,}/g,
193    'Google API key': /AIza[0-9A-Za-z_-]{30,}/g,
194    'AWS access key': /AKIA[0-9A-Z]{16}/g,
195    'Private key block': /-----BEGIN [A-Z ]*PRIVATE KEY-----/g,
196  }
197  const added = String(diffText || '')
198    .split(/\r?\n/)
199    .filter((l) => l.startsWith('+') && !l.startsWith('+++'))
200    .join('\n')
201  const out = []
202  for (const [name, re] of Object.entries(pats)) {
203    const n = (added.match(re) || []).length
204    if (n > 0) out.push(name + ' x' + n)
205  }
206  return out
207}
208
209// Inserted plus deleted lines from `git diff --shortstat`.
210export function shortstatLines(s) {
211  const ins = Number((String(s).match(/(\d+) insertion/) || [])[1] || 0)
212  const del = Number((String(s).match(/(\d+) deletion/) || [])[1] || 0)
213  return ins + del
214}
215
216// A diff that is much bigger than its content once line endings are ignored.
217export function lineEndingChurn(plain, ignoringCr) {
218  const a = shortstatLines(plain)
219  const b = shortstatLines(ignoringCr)
220  return a !== b ? { shown: a, real: b } : null
221}
222