turno-cli 0.1.1 → 0.2.0

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/CHANGELOG.md +284 -0
  2. package/README.md +120 -53
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/demo/server.js +34 -0
  74. package/dist/mcpd/cache.js +18 -4
  75. package/dist/mcpd/calllog.js +253 -0
  76. package/dist/mcpd/client-names.js +51 -0
  77. package/dist/mcpd/connectors.js +148 -17
  78. package/dist/mcpd/daemon.js +452 -116
  79. package/dist/mcpd/folder-sets.js +39 -0
  80. package/dist/mcpd/gateway.js +441 -47
  81. package/dist/mcpd/health.js +269 -0
  82. package/dist/mcpd/importer.js +356 -36
  83. package/dist/mcpd/instances.js +425 -65
  84. package/dist/mcpd/jsonrpc.js +8 -0
  85. package/dist/mcpd/launchd.js +65 -48
  86. package/dist/mcpd/modern.js +648 -0
  87. package/dist/mcpd/oauth.js +791 -0
  88. package/dist/mcpd/peerpid.js +122 -6
  89. package/dist/mcpd/pressure.js +85 -0
  90. package/dist/mcpd/rss.js +151 -0
  91. package/dist/mcpd/service.js +167 -0
  92. package/dist/mcpd/state.js +183 -0
  93. package/dist/mcpd/sync.js +55 -80
  94. package/dist/mcpd/systemd.js +80 -0
  95. package/dist/mcpd/tokens.js +89 -0
  96. package/dist/mcpd/upstream.js +154 -44
  97. package/dist/statusline/cost.js +154 -44
  98. package/dist/statusline/input.js +66 -0
  99. package/dist/statusline/render.js +9 -3
  100. package/dist/ui/fonts.js +8 -3
  101. package/dist/ui/settings.js +27 -15
  102. package/npm-shrinkwrap.json +1093 -0
  103. package/package.json +6 -6
  104. package/dist/cli/commands/available.js +0 -18
@@ -1,6 +1,7 @@
1
+ import { accessSync, chmodSync, closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync, statSync, writeSync } from "node:fs";
1
2
  import { homedir } from "node:os";
2
- import { join } from "node:path";
3
- export function paths(env = process.env) {
3
+ import { delimiter, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
4
+ export function paths(env) {
4
5
  const home = env.HOME || homedir();
5
6
  const config = env.TURNO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(home, ".config"), "turno");
6
7
  const state = env.TURNO_STATE_DIR || join(env.XDG_STATE_HOME || join(home, ".local", "state"), "turno");
@@ -34,16 +35,18 @@ export function paths(env = process.env) {
34
35
  };
35
36
  }
36
37
  /** Config dir of a profile: ~/.claude-<name>. */
37
- export function profileDir(name, env = process.env) {
38
+ export function profileDir(name, env) {
38
39
  return join(paths(env).home, `.claude-${name}`);
39
40
  }
40
41
  /** Replace the home prefix with ~ for display. */
41
- export function tildify(p, env = process.env) {
42
- const home = paths(env).home;
43
- return p === home ? "~" : p.startsWith(home + "/") ? "~" + p.slice(home.length) : p;
42
+ export function tildify(p, env) {
43
+ // HOME may come with a trailing slash or doubled slashes (HOME=/Users/a/): compare normalized.
44
+ const home = normalize(paths(env).home).replace(/(.)\/+$/, "$1");
45
+ const q = isAbsolute(p) ? normalize(p) : p;
46
+ return q === home ? "~" : home !== "/" && q.startsWith(`${home}/`) ? `~${q.slice(home.length)}` : p;
44
47
  }
45
48
  /** Expand a leading ~ to the home directory. */
46
- export function expandHome(p, env = process.env) {
49
+ export function expandHome(p, env) {
47
50
  const home = paths(env).home;
48
51
  if (p === "~")
49
52
  return home;
@@ -51,4 +54,108 @@ export function expandHome(p, env = process.env) {
51
54
  return join(home, p.slice(2));
52
55
  return p;
53
56
  }
57
+ /** Mode of every directory turno creates under its own config, state and data roots. */
58
+ export const PRIVATE_DIR_MODE = 0o700;
59
+ /** Mode of every file turno writes under those roots (logs, accounts.toml, audit log, mcpd.port). */
60
+ export const PRIVATE_FILE_MODE = 0o600;
61
+ /** turno's own roots (config, state, data): what `ensurePrivateDir` locks down. */
62
+ export function privateRoots(env) {
63
+ const p = paths(env);
64
+ return [p.config, p.state, p.data];
65
+ }
66
+ function within(file, root) {
67
+ const rel = relative(root, file);
68
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
69
+ }
70
+ /** The turno root (config, state or data) that holds `file`, if any. */
71
+ function rootOf(file, env) {
72
+ return privateRoots(env).find((root) => within(file, root));
73
+ }
74
+ /** True when `file` is one of turno's roots or lies inside one. */
75
+ export function isPrivatePath(file, env) {
76
+ return rootOf(file, env) !== undefined;
77
+ }
78
+ /** Roots already checked by this process (tests switch HOME, so the key is the path). */
79
+ const lockedRoots = new Set();
80
+ function lockRoot(root) {
81
+ if (lockedRoots.has(root))
82
+ return;
83
+ // Parents such as ~/.config keep the default mode; only turno's own folder is private.
84
+ mkdirSync(dirname(root), { recursive: true });
85
+ try {
86
+ mkdirSync(root, { mode: PRIVATE_DIR_MODE });
87
+ }
88
+ catch (err) {
89
+ if (err.code !== "EEXIST")
90
+ throw err;
91
+ }
92
+ const st = statSync(root);
93
+ if ((st.mode & 0o777) !== PRIVATE_DIR_MODE && st.uid === process.getuid?.())
94
+ chmodSync(root, PRIVATE_DIR_MODE);
95
+ lockedRoots.add(root);
96
+ }
97
+ /**
98
+ * Create `dir` (and its parents) for turno's own state. Inside turno's config, state and data
99
+ * roots every folder is created 0700, and an existing root with a wider mode is narrowed to
100
+ * 0700 the first time a process uses it. Other folders are created with the default mode.
101
+ * Returns `dir`.
102
+ */
103
+ export function ensurePrivateDir(dir, env) {
104
+ const root = rootOf(dir, env);
105
+ if (!root) {
106
+ mkdirSync(dir, { recursive: true });
107
+ return dir;
108
+ }
109
+ lockRoot(root);
110
+ // Recursive mkdir applies the mode to every folder it creates, the root included if it vanished.
111
+ mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE });
112
+ return dir;
113
+ }
114
+ /**
115
+ * Write a small file turno keeps for itself (a mark, a cache, a state file): its folder through
116
+ * `ensurePrivateDir`, the file created 0600, and narrowed to 0600 when an older turno left it
117
+ * wider. Not atomic; use the journal's `atomicWrite` for files a reader must never see half written.
118
+ */
119
+ export function writePrivateFile(file, data, env) {
120
+ ensurePrivateDir(dirname(file), env);
121
+ const fd = openSync(file, "w", PRIVATE_FILE_MODE);
122
+ try {
123
+ if (fstatSync(fd).mode & 0o077)
124
+ fchmodSync(fd, PRIVATE_FILE_MODE);
125
+ writeSync(fd, data);
126
+ }
127
+ finally {
128
+ closeSync(fd);
129
+ }
130
+ }
131
+ /** Forget which roots were checked (tests). */
132
+ export function resetPrivateDirCache() {
133
+ lockedRoots.clear();
134
+ }
135
+ /** The first executable called `name` on the PATH of `env`, or undefined. */
136
+ export function findOnPath(name, env) {
137
+ if (name.includes("/")) {
138
+ try {
139
+ accessSync(name, constants.X_OK);
140
+ return name;
141
+ }
142
+ catch {
143
+ return undefined;
144
+ }
145
+ }
146
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
147
+ if (!dir)
148
+ continue;
149
+ const file = join(dir, name);
150
+ try {
151
+ accessSync(file, constants.X_OK);
152
+ if (statSync(file).isFile())
153
+ return file;
154
+ }
155
+ catch {
156
+ /* next */
157
+ }
158
+ }
159
+ return undefined;
160
+ }
54
161
  //# sourceMappingURL=paths.js.map
@@ -1,10 +1,12 @@
1
- import { existsSync, readdirSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { isValidProfileName } from "./config.js";
4
- import { paths, profileDir } from "./paths.js";
3
+ import { DEFAULT_AGENT, adapter } from "../agents/index.js";
4
+ import { isValidProfileName, suggestKey } from "./config.js";
5
+ import { loadManifest } from "./manifest.js";
6
+ import { paths, tildify } from "./paths.js";
5
7
  /** The agent a profile runs: from config.toml, else Claude Code. */
6
8
  export function agentOf(name, config) {
7
- return config.profiles[name]?.agent ?? "claude";
9
+ return config.profiles[name]?.agent ?? DEFAULT_AGENT;
8
10
  }
9
11
  /**
10
12
  * A profile is a ~/.claude-<name> directory that has its claude-<name> launcher, or a
@@ -12,7 +14,7 @@ export function agentOf(name, config) {
12
14
  * folders matching the pattern (for example a place to keep shared skills) are not accounts.
13
15
  * With `agent`, only that agent's profiles.
14
16
  */
15
- export function listProfiles(config, env = process.env, agent) {
17
+ export function listProfiles(config, env, agent) {
16
18
  const p = paths(env);
17
19
  const found = new Set(Object.keys(config.profiles));
18
20
  let entries = [];
@@ -41,11 +43,140 @@ export function listProfiles(config, env = process.env, agent) {
41
43
  }
42
44
  return [...found].filter((n) => !agent || agentOf(n, config) === agent).sort();
43
45
  }
44
- export function profileExists(name, config, env = process.env) {
45
- return listProfiles(config, env).includes(name);
46
+ /**
47
+ * What is wrong in a config.toml that parses: unknown keys (likely typos) and names of
48
+ * profiles that do not exist in system, default, fallback, [agents.*] and [[projects]].
49
+ * Warnings, not errors, so an older or hand-edited file keeps working. Each one says how to
50
+ * fix it: `turno profile add <name>` for a missing profile, else the line to edit.
51
+ */
52
+ export function configFindings(config, env) {
53
+ const lines = configLines(env);
54
+ const file = tildify(paths(env).configFile, env);
55
+ /** "edit ~/.config/turno/config.toml line 3: <what>", or `turno config edit` without a line. */
56
+ const edit = (key, what) => {
57
+ const line = lines ? keyLine(lines, key) : undefined;
58
+ return line ? { manual: `edit ${file} line ${line}${what ? `: ${what}` : ""}` } : { hint: "turno config edit" };
59
+ };
60
+ const out = (config.warnings ?? []).map((text) => {
61
+ const m = /^unknown key ([^\s;]+)(?: \(did you mean ([^\s?]+)\?\))?/.exec(text);
62
+ return { text, ...(m ? edit(m[1], m[2] ? `rename it to ${m[2].slice(m[2].lastIndexOf(".") + 1)}` : "remove it") : { hint: "turno config edit" }) };
63
+ });
64
+ const known = new Set(listProfiles(config, env));
65
+ const missing = (where, name) => {
66
+ if (name && !known.has(name))
67
+ out.push({ text: `${where} = "${name}", but there is no profile ${name}`, hint: `turno profile add ${name}` });
68
+ };
69
+ missing("system", config.system);
70
+ missing("default", config.default);
71
+ missing("fallback", config.fallback);
72
+ for (const [id, roles] of Object.entries(config.agents)) {
73
+ missing(`agents.${id}.default`, roles?.default);
74
+ missing(`agents.${id}.fallback`, roles?.fallback);
75
+ for (const role of ["default", "fallback"]) {
76
+ const name = roles?.[role];
77
+ if (name && known.has(name) && agentOf(name, config) !== id) {
78
+ const label = adapter(id).label;
79
+ out.push({ text: `agents.${id}.${role} = "${name}", but ${name} is a ${adapter(agentOf(name, config)).label} profile`, ...edit(`agents.${id}.${role}`, `name a ${label} profile`) });
80
+ }
81
+ }
82
+ }
83
+ for (const role of ["default", "fallback"]) {
84
+ const name = config[role];
85
+ if (name && known.has(name) && agentOf(name, config) !== DEFAULT_AGENT) {
86
+ const other = agentOf(name, config);
87
+ out.push({ text: `${role} = "${name}" is for ${adapter(DEFAULT_AGENT).label}, but ${name} is a ${adapter(other).label} profile`, ...edit(role, `move it to [agents.${other}]`) });
88
+ }
89
+ }
90
+ for (const [i, rule] of config.projects.entries()) {
91
+ if (rule.profile && !known.has(rule.profile))
92
+ out.push({ text: `the rule for ${tildify(rule.path, env)} uses profile ${rule.profile}, which does not exist`, hint: `turno profile add ${rule.profile}` });
93
+ out.push(...folderSetFindings(rule, i, env, edit));
94
+ }
95
+ return out;
96
+ }
97
+ /** The findings as `config check` prints them: the command in parentheses, or the line to edit after it. */
98
+ export function configProblems(config, env) {
99
+ return configFindings(config, env).map((f) => (f.manual ? `${f.text}; ${f.manual}` : `${f.text} (${f.hint})`));
100
+ }
101
+ /** The lines of config.toml, or undefined when it cannot be read. */
102
+ function configLines(env) {
103
+ try {
104
+ return readFileSync(paths(env).configFile, "utf8").split("\n");
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
110
+ /**
111
+ * The 1-based line of a dotted key in config.toml text: `default`, `profiles.work.colour`,
112
+ * `agents.codex.default`, `projects[0].profile` (the first [[projects]] table). Tables and
113
+ * array tables are followed; inline tables and dotted keys inside a table are not.
114
+ */
115
+ function keyLine(lines, key) {
116
+ let table = "";
117
+ const arrays = new Map();
118
+ const bare = (k) => k.trim().replace(/^"(.*)"$/, "$1");
119
+ for (const [i, raw] of lines.entries()) {
120
+ const line = raw.trim();
121
+ const arr = /^\[\[\s*([^\]]+?)\s*\]\]/.exec(line);
122
+ if (arr) {
123
+ const name = arr[1].split(".").map(bare).join(".");
124
+ const n = (arrays.get(name) ?? -1) + 1;
125
+ arrays.set(name, n);
126
+ table = `${name}[${n}]`;
127
+ continue;
128
+ }
129
+ const tab = /^\[\s*([^\]]+?)\s*\]/.exec(line);
130
+ if (tab) {
131
+ table = tab[1].split(".").map(bare).join(".");
132
+ continue;
133
+ }
134
+ const kv = /^("[^"]*"|[A-Za-z0-9_-]+)\s*=/.exec(line);
135
+ if (kv && (table ? `${table}.${bare(kv[1])}` : bare(kv[1])) === key)
136
+ return i + 1;
137
+ }
138
+ return undefined;
139
+ }
140
+ /**
141
+ * Folder server sets (ADR 0031) checked against mcp.toml: names it does not declare, and
142
+ * remote servers that skip mcpd, which a set cannot hide. Nothing when mcp.toml is missing or
143
+ * broken (its own check reports that).
144
+ */
145
+ function folderSetFindings(rule, index, env, edit) {
146
+ if ((!rule.mcp && !rule.mcpDeny) || !existsSync(paths(env).mcpFile))
147
+ return [];
148
+ let servers;
149
+ try {
150
+ servers = loadManifest(env).servers;
151
+ }
152
+ catch {
153
+ return [];
154
+ }
155
+ const declared = Object.keys(servers);
156
+ const out = [];
157
+ const where = `the rule for ${tildify(rule.path, env)}`;
158
+ for (const [key, list] of [["mcp", rule.mcp], ["mcp_deny", rule.mcpDeny]]) {
159
+ for (const name of list ?? []) {
160
+ if (servers[name])
161
+ continue;
162
+ const near = suggestKey(name, declared);
163
+ out.push({
164
+ text: `${where} lists "${name}" in ${key}, which is not in mcp.toml${near ? ` (did you mean ${near}?)` : ""}`,
165
+ ...edit(`projects[${index}].${key}`, near ? `write ${near}` : `remove "${name}", or declare it in mcp.toml`),
166
+ });
167
+ }
168
+ }
169
+ for (const [name, def] of Object.entries(servers)) {
170
+ const hidden = (rule.mcp && !rule.mcp.includes(name)) || rule.mcpDeny?.includes(name);
171
+ if (hidden && def.kind === "remote" && !def.proxy) {
172
+ const fix = rule.mcpDeny?.includes(name) ? edit(`projects[${index}].mcp_deny`, `remove ${name}`) : edit(`projects[${index}].mcp`, `add ${name}`);
173
+ out.push({ text: `${where} cannot hide ${name}: it is a remote server that does not pass through mcpd`, ...fix });
174
+ }
175
+ }
176
+ return out;
46
177
  }
47
178
  /** The profile a CLAUDE_CONFIG_DIR value belongs to, or the system profile for the hub. */
48
- export function profileFromConfigDir(configDir, config, env = process.env) {
179
+ export function profileFromConfigDir(configDir, config, env) {
49
180
  const p = paths(env);
50
181
  const dir = (configDir ?? "").replace(/\/+$/, "");
51
182
  if (dir) {
@@ -57,5 +188,4 @@ export function profileFromConfigDir(configDir, config, env = process.env) {
57
188
  }
58
189
  return config.system;
59
190
  }
60
- export { profileDir };
61
191
  //# sourceMappingURL=profiles.js.map
@@ -1,36 +1,109 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { sep } from "node:path";
2
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { dirname, join, resolve, sep } from "node:path";
4
+ import { DEFAULT_AGENT } from "../agents/index.js";
4
5
  import { exhaustedUntil } from "./exhausted.js";
5
6
  import { tildify } from "./paths.js";
6
7
  import { agentOf } from "./profiles.js";
7
- function real(p) {
8
- try {
9
- return realpathSync(p);
10
- }
11
- catch {
12
- return p;
8
+ import { realOr } from "./fsutil.js";
9
+ /** The directory itself plus, for a git worktree, the main repository it belongs to. */
10
+ export function candidateRoots(cwd, spawnGit = gitCommonDirBySpawn) {
11
+ const cands = [realOr(cwd)];
12
+ const found = gitCommonDirOnDisk(cwd);
13
+ const common = found === UNSURE ? spawnGit(cwd) : found;
14
+ if (common?.endsWith("/.git")) {
15
+ const main = realOr(common.slice(0, -5));
16
+ if (!cands.includes(main))
17
+ cands.push(main);
13
18
  }
19
+ return cands;
14
20
  }
15
- /** The directory itself plus, for a git worktree, the main repository it belongs to. */
16
- export function candidateRoots(cwd) {
17
- const cands = [real(cwd)];
21
+ /** What `git rev-parse --git-common-dir` prints in `cwd`, or undefined outside a repository. */
22
+ function gitCommonDirBySpawn(cwd) {
18
23
  try {
19
- const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
24
+ return execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
20
25
  encoding: "utf8",
21
26
  stdio: ["ignore", "pipe", "ignore"],
22
27
  timeout: 3000,
23
28
  }).trim();
24
- if (common.endsWith("/.git")) {
25
- const main = real(common.slice(0, -5));
26
- if (!cands.includes(main))
27
- cands.push(main);
29
+ }
30
+ catch {
31
+ return undefined; // not a git repository
32
+ }
33
+ }
34
+ const UNSURE = Symbol("unsure");
35
+ /** Variables that change how git finds a repository: with any of them set, git itself decides. */
36
+ const GIT_DISCOVERY_VARS = ["GIT_DIR", "GIT_COMMON_DIR", "GIT_WORK_TREE", "GIT_CEILING_DIRECTORIES", "GIT_DISCOVERY_ACROSS_FILESYSTEM"];
37
+ function stat(p) {
38
+ try {
39
+ return statSync(p);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ /**
46
+ * The git common dir of `cwd` (real path), found the way git finds it but with the file system
47
+ * only: walk up to the first `.git`, follow a `gitdir:` file (worktrees, submodules), then the
48
+ * `commondir` file of a linked worktree. The status line and `turno auto` resolve a folder on
49
+ * every run, and a `git` process costs more than the rest of the resolve. Undefined outside a
50
+ * repository; UNSURE for anything unusual (git variables, another owner, a broken `.git`, a
51
+ * missing HEAD), which `git rev-parse` then answers as before.
52
+ */
53
+ function gitCommonDirOnDisk(cwd, env = process.env) {
54
+ if (GIT_DISCOVERY_VARS.some((k) => env[k] !== undefined))
55
+ return UNSURE;
56
+ let dir = realOr(cwd);
57
+ const start = stat(dir);
58
+ if (!start?.isDirectory())
59
+ return UNSURE;
60
+ for (;;) {
61
+ const here = stat(dir);
62
+ // git stops at a file system boundary.
63
+ if (!here || here.dev !== start.dev)
64
+ return undefined;
65
+ const dotgit = join(dir, ".git");
66
+ let st;
67
+ try {
68
+ st = lstatSync(dotgit);
69
+ }
70
+ catch {
71
+ st = undefined;
72
+ }
73
+ if (st)
74
+ return commonDirOf(dir, dotgit, st.isFile());
75
+ const parent = dirname(dir);
76
+ if (parent === dir)
77
+ return undefined;
78
+ dir = parent;
79
+ }
80
+ }
81
+ function commonDirOf(dir, dotgit, isFile) {
82
+ // git refuses a repository another user owns, unless safe.directory says otherwise.
83
+ const uid = process.getuid?.();
84
+ if (uid !== undefined && stat(dir)?.uid !== uid)
85
+ return UNSURE;
86
+ let gitdir = dotgit;
87
+ try {
88
+ if (isFile) {
89
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"));
90
+ if (!m)
91
+ return UNSURE;
92
+ gitdir = resolve(dir, m[1]);
28
93
  }
94
+ if (!stat(join(gitdir, "HEAD"))?.isFile())
95
+ return UNSURE;
96
+ let common = gitdir;
97
+ const pointer = join(gitdir, "commondir");
98
+ if (existsSync(pointer))
99
+ common = resolve(gitdir, readFileSync(pointer, "utf8").trim());
100
+ if (!stat(join(common, "objects"))?.isDirectory())
101
+ return UNSURE;
102
+ return realpathSync(common);
29
103
  }
30
104
  catch {
31
- // not a git repository
105
+ return UNSURE;
32
106
  }
33
- return cands;
34
107
  }
35
108
  export function formatUntil(epochSeconds) {
36
109
  return new Date(epochSeconds * 1000).toLocaleString("en-US", {
@@ -42,18 +115,51 @@ export function formatUntil(epochSeconds) {
42
115
  hour12: false,
43
116
  });
44
117
  }
118
+ /** True when `folder` is `root` or inside it (both real paths). */
119
+ function covers(root, folder) {
120
+ return folder === root || folder.startsWith(root + sep);
121
+ }
122
+ /**
123
+ * The MCP server set of a folder (ADR 0031): among the rules that have `mcp` or `mcp_deny` and
124
+ * cover one of `roots` (the folder, and the main repository of a worktree), the one with the
125
+ * longest path. On a tie, the rule of `profile`, else the first one in the file. A rule without
126
+ * a set says nothing about servers, so a nested profile rule does not clear a parent's set.
127
+ */
128
+ export function folderMcpSet(roots, rules, profile) {
129
+ let best;
130
+ for (const rule of rules) {
131
+ if (!rule.mcp && !rule.mcpDeny)
132
+ continue;
133
+ const root = realOr(rule.path);
134
+ if (!roots.some((c) => covers(root, c)))
135
+ continue;
136
+ const longer = !best || root.length > best.root.length;
137
+ const preferred = best && root.length === best.root.length && profile !== undefined && rule.profile === profile && best.rule.profile !== profile;
138
+ if (longer || preferred)
139
+ best = { rule, root };
140
+ }
141
+ return best?.rule;
142
+ }
143
+ /** Whether a folder's set lets a session see `server` (no set: every server). */
144
+ export function mcpSetAllows(set, server) {
145
+ if (!set)
146
+ return true;
147
+ if (set.mcp && !set.mcp.includes(server))
148
+ return false;
149
+ return !set.mcpDeny?.includes(server);
150
+ }
45
151
  /**
46
152
  * Which profile of `agent` a folder uses: the longest matching project rule among that agent's
47
153
  * profiles, else the agent's default; its fallback when the assigned profile is exhausted.
48
154
  */
49
- export function resolveProfile(cwd, config, env = process.env, roots = candidateRoots(cwd), agent = "claude") {
50
- const roles = agent === "claude" ? { default: config.default, fallback: config.fallback } : (config.agents[agent] ?? {});
155
+ export function resolveProfile(cwd, config, env, roots = candidateRoots(cwd), agent = DEFAULT_AGENT) {
156
+ const roles = agent === DEFAULT_AGENT ? { default: config.default, fallback: config.fallback } : (config.agents[agent] ?? {});
51
157
  let best;
52
158
  for (const rule of config.projects) {
53
- if (agentOf(rule.profile, config) !== agent)
159
+ if (!rule.profile || agentOf(rule.profile, config) !== agent)
54
160
  continue;
55
- const root = real(rule.path);
56
- const hit = roots.some((c) => c === root || c.startsWith(root + sep));
161
+ const root = realOr(rule.path);
162
+ const hit = roots.some((c) => covers(root, c));
57
163
  if (hit && (!best || root.length > best.root.length))
58
164
  best = { profile: rule.profile, root };
59
165
  }