claude: a caller's folder Claude Code would ask about is known before the run, and the session kept (sleepy_shibe)

sleepy_shibe on Discord (magpie 0.1.2996, Claude Code 2.1.318, own
account, interactive mode): message counts 36, 65, 85, 108, 128 for one
conversation. Confirmed at origin/main 74d1cda42: a caller's folder Claude
Code asked about was passed over for untrustedFor (10 min) only. Past
that, the next run went in the caller's folder again, claudeSessions
pointed at another project folder than the conversation's session in
magpie's folder, so `from` went nil and the run was told the whole
conversation; Claude Code asked about trust, startTrusted dropped
req.branch and started from nil in magpie's folder (the deferred
from.discard() had already removed the session), told it all again.

Now, for the own account in the interactive mode, each run first decides
as Claude Code does (untrustedHere -> claudeTrusts), from
hasTrustDialogAccepted in claudeProfilePath()'s .claude.json
(provider.ClaudeTrustedProjects; a missing file is nothing trusted, an
unreadable one unknown, which goes on as before). The rules are Claude
Code 2.1.316's, read from its bundled JS (UI/zh/jh/Y0/lr): the key of the
repository's main checkout (a worktree's is the checkout it was added
from), or any folder from the run's up to the git root and never past it
(a nested repository isn't trusted by its parent), every folder above
outside a repository; NFC keys, forward slashes on Windows
(claudeTrustKey, shared with claudeTrustKeys). An untrusted folder stays
in magpie's folder with its session; a folder trusted since is run in on
the next run. When Claude Code asks all the same, startRun keeps `from`
and startTrusted goes on from it in magpie's folder with the branch.

Run (mote, at this tree on 74d1cda42):
- go test ./internal/gateway -run TestClaude: ok (118s);
  go test ./internal/provider -run Claude: ok
- GOOS=windows and GOOS=linux go vet ./internal/gateway ./internal/provider: ok
- win-run go test ./internal/gateway -run TestClaudeTrust: ok
- real Claude Code 2.1.316 in a sandbox HOME + CLAUDE_CONFIG_DIR (dummy
  key, no account), tmux, 10 cases: repo/subfolder/parent-in-repo/
  worktree-of-trusted/worktree-itself trusted -> no question; worktree
  under a trusted parent, nested repo in a trusted repo, repo under a
  trusted parent, unrelated folder -> asked; outside a repo a trusted
  parent -> no question. All ten match claudeTrustedBy.
Broken by hand:
- untrustedHere returning passedOver only (the old choice):
  TestClaudeTUIUntrustedFolderKeepsItsSession/untrusted red (helper
  started twice) and TestClaudeTUIFolderTrustedLaterRunInAtOnce red (ran
  in magpie's folder).
- startTrusted dropping req.branch and starting from nil (the old
  fallback): .../unknown red (resumed a new transcript, not the
  conversation's session).
Not tried: the owner's real account or a real turn through the gateway
(no sign-in in the sandbox); Claude Code 2.1.318 itself (2.1.316 is
installed here); a Windows or Linux real Claude Code; the full suite
before the push (it runs after, through the suite lock).
This commit is contained in:
yetone
2026-11-06 04:35:12 +08:00
parent 74d1cda421
commit 60fe6645a9
7 changed files with 505 additions and 15 deletions
+29 -5
View File
@@ -271,12 +271,36 @@ both magpie's. In the caller's folder under the account Claude Code is
signed in to, the question is the user's: the helper ends there, saying
so (`claudetui.Untrusted`), and the turn goes in magpie's own folder,
told the caller's as any run whose folder isn't here is (`envElsewhere`;
`startTrusted`). That folder is passed over for 10 minutes
(`passedOver`, `untrustedFor`), then tried again, the user having maybe
trusted it since. Until 11-01 such a run became `-p`; from then until
this change it was a 502, which a Claude Code client (paseo) asked again
`startTrusted`). Until 11-01 such a run became `-p`; from then until
the fallback it was a 502, which a Claude Code client (paseo) asked again
with backoff, so the chat hung (lwjef on X).
`TestClaudeTUIUntrustedFolderAnswered` holds it. The question opens on "No, exit", and a key
`TestClaudeTUIUntrustedFolderAnswered` holds it.
Before each such run the bridge decides as Claude Code does whether it
would ask (`untrustedHere`, `claudeTrusts` in `claude_trusted.go`), from
the user's own answers in the profile `provider.ClaudeTrustedProjects`
reads (`CLAUDE_CONFIG_DIR/.claude.json` or `~/.claude.json`), so a folder
the user never trusted is never run in and a folder they trust is run in
from the next run on. The rules are Claude Code 2.1.316's, read from its
code (`claudeTrustedBy`): a `projects` key, the path in NFC (forward
slashes on Windows), with `hasTrustDialogAccepted` true for the
repository's main checkout (its root; for a worktree the checkout it was
added from, `claudeMainCheckout`), or for any folder from the run's up
to the repository's root and never past it, so a repository inside a
trusted one is asked about; outside a repository every folder above
counts. The run's folder as written and with links followed both count.
A profile that can't be read is unknown, and the run goes in the
caller's folder as before. A folder Claude Code asked about all the same
is passed over for 10 minutes (`passedOver`, `untrustedFor`). The run
that goes in magpie's folder after the question goes on from the
conversation's saved session (`startRun` keeps it for `startTrusted`).
Before, only the 10 minutes decided: past them, a conversation whose
session was in magpie's folder ran in the caller's again, was told the
whole conversation there, was asked, and was told it all once more in
magpie's folder with its branch dropped, every 10 minutes (sleepy_shibe
on Discord). `TestClaudeTUIUntrustedFolderKeepsItsSession`,
`TestClaudeTUIFolderTrustedLaterRunInAtOnce` and
`TestClaudeTrustedFolders` hold it. The question opens on "No, exit", and a key
sent as it is first drawn can be lost to its being drawn again, so the
helper presses ↓ until "Yes" is the last choice drawn and Enter only once
it has stayed so for 300ms (`ready`, `trustSettle`). Pressing Enter blind
+46 -5
View File
@@ -911,11 +911,44 @@ func (b *subscriptionBridge) startTrusted(ctx context.Context, req *Request, mod
return run, events, err
}
// passed over from now on (passedOver): this run, and the next,
// aren't in the caller's folder
// aren't in the caller's folder. The conversation's session, kept
// (startRun), is gone on with there when it is magpie's folder's: a
// run started anew replayed the whole conversation once in each
// folder (sleepy_shibe on Discord)
b.untrusted.Store(untrusted.key, time.Now())
log.Printf("claude: Claude Code asks whether to trust %s, which its user hasn't; the run goes in magpie's own folder, told the caller's", untrusted.dir)
req.branch = nil
return b.startRun(ctx, req, model, configDir, owner, nil)
return b.startRun(ctx, req, model, configDir, owner, from)
}
// untrustedHere is whether a run in the caller's folder work goes in
// magpie's own instead: in the interactive mode under the account Claude
// Code is signed in to, Claude Code would ask whether to trust it, which
// only the user answers. It is decided for each run as Claude Code
// decides it (claudeTrusts), before the run, so a conversation whose
// session is in magpie's folder goes on with it there instead of being
// replayed in the caller's, asked about and replayed again in magpie's
// every time passedOver's 10 minutes were up (sleepy_shibe on Discord),
// and a folder the user trusts since is run in from the next turn on.
// A folder Claude Code asked about lately all the same stays passed
// over, as one is while the user's answers can't be read.
func (b *subscriptionBridge) untrustedHere(req *Request, binary claudeCLI, configDir, work string) bool {
if b.passedOver(configDir, work) {
return true
}
if configDir != "" || claudePrintWhy(req, binary) != "" {
// a saved account's folder is magpie's, which answers yes, and
// claude -p asks nothing
return false
}
trusted, err := claudeTrusts(work)
if err != nil {
log.Printf("claude: whether Claude Code trusts the caller's folder is unknown (%v); the run goes there", logSafe(err.Error()))
return false
}
if !trusted {
log.Printf("claude: Claude Code hasn't been told to trust %s; the run goes in magpie's own folder, told the caller's", logSafe(work))
}
return !trusted
}
// startRun is start's Claude Code, from the saved session from when set.
@@ -993,7 +1026,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
work := ""
if binary.wsl == nil {
work = clientWorkDir(req)
if work != "" && b.passedOver(configDir, work) {
if work != "" && b.untrustedHere(req, binary, configDir, work) {
work = ""
}
}
@@ -1041,8 +1074,15 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
b.sweepSessions(sessions)
}
}
// kept is the session from was, for startTrusted to go on with in
// magpie's folder when Claude Code asks about the caller's
kept := false
if from != nil {
defer from.discard() // unless the run took it
defer func(from *savedSession) {
if !kept {
from.discard() // unless the run took it
}
}(from)
if sessions == nil || !slices.Equal(from.sessions, sessions) || !from.saved() {
from = nil
}
@@ -1291,6 +1331,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if err := run.cliControlWithin(ctx, map[string]any{"subtype": "initialize"}, wait); err != nil {
run.abort()
if tui && client && configDir == "" && run.saidOnEnd(claudetui.Untrusted) {
kept = true
return nil, nil, &tuiUntrusted{key: configDir + "\x00" + work, dir: work, err: err}
}
var unanswered *controlUnanswered
+127
View File
@@ -0,0 +1,127 @@
package gateway
import (
"os"
"path/filepath"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// claudeTrusts is whether Claude Code, under the account it is signed in
// to, runs in folder work without asking whether to trust it, by the
// answers the user gave it (provider.ClaudeTrustedProjects); err when
// those can't be read, which is unknown. Either path of work counts, as
// written and with its links followed: Claude Code keys a folder by the
// one its working directory has, and a Mac's getcwd says /private/var/…
// for /var/… (claudeTrustKeys).
func claudeTrusts(work string) (bool, error) {
projects, err := provider.ClaudeTrustedProjects()
if err != nil {
return false, err
}
for _, w := range []string{work, evalSymlinks(work)} {
if claudeTrustedBy(projects, filepath.Clean(w)) {
return true, nil
}
}
return false, nil
}
// claudeTrustedBy is Claude Code's own trust check (2.1.316, read from its
// code), for a run in dir: the folder is trusted when the user trusted
// the main checkout of the repository dir is in (its own root, or for a
// worktree the checkout it was added from), dir itself when it is in
// none, or dir or a folder above it up to the root of the repository
// it is in, never past it: a trusted repository doesn't trust a
// repository inside it. Outside a repository every folder above counts.
// Accepting the question records the first of these (claudeTrustKeys'
// form), which is why a worktree of a trusted checkout isn't asked about.
func claudeTrustedBy(projects map[string]bool, dir string) bool {
root := claudeGitRoot(dir)
key := dir
if root != "" {
key = claudeMainCheckout(root)
}
if projects[claudeTrustKey(key)] {
return true
}
for d := dir; ; {
if projects[claudeTrustKey(d)] {
return true
}
if d == root {
return false
}
up := filepath.Dir(d)
if up == d {
return false
}
d = up
}
}
// claudeGitRoot is the folder nearest dir, dir itself first, that holds a
// .git, a folder or a file (a worktree's, a submodule's) or a link to
// one, as Claude Code's findGitRoot takes it; "" when none does.
func claudeGitRoot(dir string) string {
for d := dir; ; {
if fi, err := os.Stat(filepath.Join(d, ".git")); err == nil && (fi.IsDir() || fi.Mode().IsRegular()) {
return d
}
up := filepath.Dir(d)
if up == d {
return ""
}
d = up
}
}
// claudeMainCheckout is the checkout a worktree at root was added from,
// as Claude Code finds it: root's .git file names the worktree's git
// folder (<common>/worktrees/<name>), whose commondir names the
// repository's own and whose gitdir names root's .git back; the checkout
// is the folder holding that common .git, or the common folder itself
// for a bare repository. Anything else, a repository's own root and a
// submodule's included, is root.
func claudeMainCheckout(root string) string {
b, err := os.ReadFile(filepath.Join(root, ".git"))
if err != nil {
return root // a folder, or unreadable
}
line := strings.TrimSpace(string(b))
if !strings.HasPrefix(line, "gitdir:") {
return root
}
gitDir := resolveFrom(root, strings.TrimSpace(strings.TrimPrefix(line, "gitdir:")))
common, err := os.ReadFile(filepath.Join(gitDir, "commondir"))
if err != nil {
return root
}
commonDir := resolveFrom(gitDir, strings.TrimSpace(string(common)))
if filepath.Dir(gitDir) != filepath.Join(commonDir, "worktrees") {
return root
}
back, err := os.ReadFile(filepath.Join(gitDir, "gitdir"))
if err != nil {
return root
}
if evalSymlinks(resolveFrom(gitDir, strings.TrimSpace(string(back)))) != filepath.Join(evalSymlinks(root), ".git") {
return root
}
if filepath.Base(commonDir) != ".git" {
if _, err := os.Lstat(filepath.Join(commonDir, ".git")); err == nil {
return root
}
return commonDir
}
return filepath.Dir(commonDir)
}
// resolveFrom is path p read from base, as Node's path.resolve(base, p).
func resolveFrom(base, p string) string {
if filepath.IsAbs(p) {
return filepath.Clean(p)
}
return filepath.Join(base, p)
}
+250
View File
@@ -0,0 +1,250 @@
package gateway
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/claudetui"
)
// writeProfile writes the account's Claude Code profile (CLAUDE_CONFIG_DIR's
// .claude.json) with folders trusted, as Claude Code records an accepted
// trust question.
func writeProfile(t *testing.T, config string, folders ...string) {
t.Helper()
projects := map[string]any{}
for _, f := range folders {
projects[claudeTrustKey(f)] = map[string]any{"hasTrustDialogAccepted": true, "allowedTools": []any{}}
}
b, _ := json.Marshal(map[string]any{"projects": projects})
if err := os.MkdirAll(config, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(config, ".claude.json"), b, 0o600); err != nil {
t.Fatal(err)
}
}
// trustInProfile records the user trusting folder in h's Claude Code.
func trustInProfile(t *testing.T, h *resumeHarness, folder string) {
t.Helper()
writeProfile(t, h.config, evalSymlinks(folder))
}
// askingClaude is a tuiHelperHarness hold for a Claude Code that asks
// whether to trust its folder, which only its user answers, unless
// magpie's own folder answered yes for it or its profile says the user
// trusted one; each run's folder goes to cwds.
func askingClaude(cwds string) string {
return `if [ "$` + claudetui.TrustEnv + `" != 1 ] && ! grep -q hasTrustDialogAccepted "$CLAUDE_CONFIG_DIR/.claude.json" 2>/dev/null; then
echo "claude-tui: ` + claudetui.Untrusted + `, which only its user answers" >&2
exit 1
fi
pwd >> '` + cwds + `'`
}
// sleepy_shibe on Discord (Claude Code 2.1.318, its own account): a
// conversation in a folder the user never trusted was run in magpie's
// folder, and its session kept there. Once passedOver's 10 minutes were
// up, its next run went in the caller's folder again: no session of the
// conversation's there, so Claude Code was told the whole conversation,
// asked about the folder, and the run went in magpie's folder started
// anew, told the whole conversation once more, the conversation's branch
// dropped. The folder is known untrusted from the user's own answers now,
// and the conversation goes on from its session in magpie's folder.
//
// When the user's answers can't be read, the run goes in the caller's
// folder as before, and once Claude Code asks, in magpie's folder from the
// conversation's session there: once, not from the transcript again.
func TestClaudeTUIUntrustedFolderKeepsItsSession(t *testing.T) {
for _, c := range []struct {
name string
profile string
starts int
}{
{"untrusted", `{"projects":{}}`, 1},
{"unknown", `{"projects":`, 2},
} {
t.Run(c.name, func(t *testing.T) { untrustedKeepsSession(t, c.profile, c.starts) })
}
}
func untrustedKeepsSession(t *testing.T, profile string, starts int) {
caller := t.TempDir()
cwds := filepath.Join(t.TempDir(), "cwds")
h, started := tuiHelperHarness(t, askingClaude(cwds))
if err := os.MkdirAll(h.config, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(h.config, ".claude.json"), []byte(profile), 0o600); err != nil {
t.Fatal(err)
}
system := "Primary working directory: " + caller
h.ask(system, "a1")
first := h.runs()
if len(first) != 1 {
t.Fatalf("runs: %v", first)
}
var sid string
for pid := range first {
sid = "s" + pid
}
// past untrustedFor
h.s.subscription.untrusted.Range(func(k, _ any) bool {
h.s.subscription.untrusted.Store(k, time.Now().Add(-untrustedFor-time.Minute))
return true
})
for i := range idleMost {
h.ask(fmt.Sprintf("rules %d", i), "x")
}
eventually(t, "the conversation's run still going", func() bool { return len(h.s.subscription.idle) == idleMost })
before, was := h.runs(), helperStarts(started)
h.ask(system, "a1", "a2")
var resumed []string
for pid, log := range h.runs() {
if _, ok := before[pid]; !ok {
resumed = append(resumed, log)
}
}
if n := helperStarts(started) - was; n != starts {
t.Fatalf("the turn started the helper %d times, want %d", n, starts)
}
if len(resumed) != 1 || !strings.Contains(resumed[0], "--resume "+sid+" ") {
// a transcript of the conversation is resumed too (replaySession),
// written anew under an id of its own
t.Fatalf("the turn did not resume the conversation's session %s:\n%s", sid, strings.Join(resumed, "\n---\n"))
}
told := resumed[0][strings.Index(resumed[0], "\ntold "):]
if !strings.Contains(told, "a2") || strings.Contains(told, "a1") {
t.Fatalf("the resumed run was told more than the turn:\n%s", told)
}
b, _ := os.ReadFile(cwds)
for _, d := range strings.Fields(string(b)) {
if evalSymlinks(d) == evalSymlinks(caller) {
t.Fatalf("a run went in the caller's folder %s, which the user never trusted", caller)
}
}
}
// A folder the user trusts in Claude Code after magpie went around it is
// run in from the next run on, not after untrustedFor.
func TestClaudeTUIFolderTrustedLaterRunInAtOnce(t *testing.T) {
caller := t.TempDir()
cwds := filepath.Join(t.TempDir(), "cwds")
h, started := tuiHelperHarness(t, askingClaude(cwds))
h.ask("Primary working directory: "+caller, "hi")
trustInProfile(t, h, caller)
starts := helperStarts(started)
h.ask("Primary working directory: "+caller+`\nanother conversation`, "hello")
if n := helperStarts(started) - starts; n != 1 {
t.Fatalf("the run started the helper %d times, want once", n)
}
b, _ := os.ReadFile(cwds)
ran := strings.Fields(string(b))
if len(ran) == 0 || evalSymlinks(ran[len(ran)-1]) != evalSymlinks(caller) {
t.Fatalf("the run after the user trusted %s ran in %q", caller, ran)
}
}
// A profile that can't be read says nothing about the folder: the run goes
// in the caller's folder as it did before, and passedOver alone decides.
func TestClaudeTrustsUnreadableProfileIsUnknown(t *testing.T) {
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
if err := os.WriteFile(filepath.Join(config, ".claude.json"), []byte(`{"projects":`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := claudeTrusts(t.TempDir()); err == nil {
t.Fatal("a half-written profile read as known")
}
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(t.TempDir(), "none"))
if ok, err := claudeTrusts(t.TempDir()); ok || err != nil {
t.Fatalf("no profile at all: %v %v, want untrusted", ok, err)
}
}
// claudeTrustedBy follows Claude Code 2.1.316's own check (UI, zh, jh, Y0/lr):
// the key of the repository's main checkout, or any folder from the run's
// up to the repository's root, never past it.
func TestClaudeTrustedFolders(t *testing.T) {
top := evalSymlinks(t.TempDir())
mk := func(p ...string) string {
d := filepath.Join(append([]string{top}, p...)...)
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
return d
}
write := func(path, s string) {
if err := os.WriteFile(path, []byte(s), 0o644); err != nil {
t.Fatal(err)
}
}
repo := mk("repo")
mk("repo", ".git", "worktrees", "wt")
sub := mk("repo", "src", "pkg")
nested := mk("repo", "vendor", "lib")
mk("repo", "vendor", "lib", ".git")
wt := mk("wts", "wt")
write(filepath.Join(wt, ".git"), "gitdir: "+filepath.Join(repo, ".git", "worktrees", "wt")+"\n")
write(filepath.Join(repo, ".git", "worktrees", "wt", "commondir"), "../..\n")
write(filepath.Join(repo, ".git", "worktrees", "wt", "gitdir"), filepath.Join(wt, ".git")+"\n")
plain := mk("plain", "a", "b")
sm := mk("repo", "mods", "m")
mk("repo", ".git", "modules", "m")
write(filepath.Join(sm, ".git"), "gitdir: ../../.git/modules/m\n")
link := filepath.Join(t.TempDir(), "link")
linked := os.Symlink(repo, link) == nil // Windows wants a privilege for it
trusted := func(folders ...string) map[string]bool {
m := map[string]bool{}
for _, f := range folders {
m[claudeTrustKey(f)] = true
}
return m
}
for _, c := range []struct {
name string
trusted []string
dir string
want bool
}{
{"the repository's root", []string{repo}, repo, true},
{"a folder in the repository", []string{repo}, sub, true},
{"a folder between the run's and the root", []string{filepath.Join(repo, "src")}, sub, true},
{"a worktree of a trusted checkout", []string{repo}, wt, true},
{"the worktree itself", []string{wt}, wt, true},
{"a folder above the worktree", []string{filepath.Join(top, "wts")}, wt, false},
{"a repository in a trusted one", []string{repo}, nested, false},
{"a submodule of a trusted repository", []string{repo}, sm, false},
{"a folder above the repository", []string{top}, repo, false},
{"outside a repository, a folder above", []string{filepath.Join(top, "plain")}, plain, true},
{"outside a repository, nothing trusted", nil, plain, false},
{"another folder", []string{repo}, filepath.Join(top, "wts"), false},
} {
if got := claudeTrustedBy(trusted(c.trusted...), c.dir); got != c.want {
t.Errorf("%s: claudeTrustedBy = %v, want %v", c.name, got, c.want)
}
}
// a link to the repository is trusted by its real path, as Claude Code
// sees it from its working directory
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
writeProfile(t, config, repo)
if ok, err := claudeTrusts(link); linked && (!ok || err != nil) {
t.Fatalf("a link to a trusted repository: %v %v", ok, err)
}
// keys are NFC: a folder named in NFD is trusted by its NFC key
nfd := mk("café")
writeProfile(t, config, filepath.Join(top, "café"))
if ok, err := claudeTrusts(nfd); !ok || err != nil {
t.Fatalf("a folder named in NFD: %v %v", ok, err)
}
}
@@ -85,6 +85,10 @@ func TestClaudeTUIHungHelperNeverPrint(t *testing.T) {
// and again, so the turn hung (lwjef on X). The turn goes in magpie's own
// folder, told the caller's, and that folder is passed over for the
// conversation's next turns rather than asked about again.
//
// The user's answers say the folder is trusted here, so the run goes
// there first (untrustedHere); Claude Code asking all the same is the case
// this test is about.
func TestClaudeTUIUntrustedFolderAnswered(t *testing.T) {
caller := t.TempDir()
cwds := filepath.Join(t.TempDir(), "cwds")
@@ -93,6 +97,7 @@ func TestClaudeTUIUntrustedFolderAnswered(t *testing.T) {
exit 1
fi
pwd >> '`+cwds+`'`)
trustInProfile(t, h, caller)
h.ask("Primary working directory: "+caller, "hi") // fails the test on anything but 200
b, _ := os.ReadFile(cwds)
ran := strings.Fields(string(b))
+11 -5
View File
@@ -350,17 +350,23 @@ func claudeTrustKeys(binary claudeCLI, work string) []string {
}
var keys []string
for _, w := range []string{work, evalSymlinks(work)} {
k := norm.NFC.String(filepath.Clean(w))
if trustGOOS == "windows" {
k = strings.ReplaceAll(k, `\`, "/")
}
if !slices.Contains(keys, k) {
if k := claudeTrustKey(w); !slices.Contains(keys, k) {
keys = append(keys, k)
}
}
return keys
}
// claudeTrustKey is the projects key Claude Code (2.1.316) gives folder
// dir: its path in NFC, on Windows with forward slashes.
func claudeTrustKey(dir string) string {
k := norm.NFC.String(filepath.Clean(dir))
if trustGOOS == "windows" {
k = strings.ReplaceAll(k, `\`, "/")
}
return k
}
// dropOneOff removes the session a one-off interactive run left in
// magpie's folder, by its id (sid, "" when it told none): a test's "hi"
// keeps its transcript there. A folder of the run's own goes whole.
+37
View File
@@ -620,6 +620,43 @@ func claudeProfileAccount() (map[string]any, bool) {
return acct, err == nil && acct != nil
}
// ClaudeTrustedProjects are the projects keys of the folders the user
// told Claude Code to trust (hasTrustDialogAccepted), in the state file of
// the account it is signed in to (claudeProfilePath, so CLAUDE_CONFIG_DIR's
// when set), read again only when the file changes. Only read, never
// written: the answers are the user's. A file that isn't there trusts
// nothing; one that can't be read or parsed, which Claude Code may be
// writing, or account discovery turned off, is an error: unknown. What it
// returns is shared and must not be changed.
func ClaudeTrustedProjects() (map[string]bool, error) {
if settings.AccountDiscoveryOff() {
return nil, errAccountDiscoveryOff
}
trusted, err := filememo.Read("claude trusted projects", claudeProfilePath(), func(b []byte) (map[string]bool, error) {
var m struct {
Projects map[string]struct {
Trusted any `json:"hasTrustDialogAccepted"`
} `json:"projects"`
}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
out := map[string]bool{}
for k, p := range m.Projects {
// Claude Code counts only true (=== true, or truthy: a
// bool either way in what it writes)
if t, _ := p.Trusted.(bool); t {
out[k] = true
}
}
return out, nil
})
if errors.Is(err, fs.ErrNotExist) {
return map[string]bool{}, nil
}
return trusted, err
}
// claudeSignedInUser names the account Claude Code is signed in to, by the
// one name both the account (claudeAccount) and its saved login (liveLogin)
// go by: ~/.claude.json's, or status, what `claude auth status` said, when