@phyzess/kitto 0.0.0-stage → 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.
@@ -0,0 +1,261 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { constants } from 'node:fs';
3
+ import { access, chmod, lstat, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const defaultPackageDir = fileURLToPath(new URL('../', import.meta.url));
8
+ const systemEnv = { PATH: '/usr/sbin:/usr/bin:/sbin:/bin', LC_ALL: 'C' };
9
+ const properties = ['Id', 'LoadState', 'ActiveState', 'MainPID', 'User', 'DynamicUser', 'RootDirectory', 'RootImage'];
10
+
11
+ function execute(program, args, { cwd = '/', capture = true, timeout = 8_000 } = {}) {
12
+ const result = spawnSync(program, args, {
13
+ cwd, env: systemEnv, encoding: 'utf8', timeout, stdio: capture ? 'pipe' : 'inherit',
14
+ });
15
+ if (result.error || result.status !== 0) {
16
+ throw new Error(`${program} failed: ${result.error?.message || result.stderr?.trim() || result.signal || result.status}`);
17
+ }
18
+ return result.stdout ?? '';
19
+ }
20
+
21
+ export function readServiceProperties(unit, output) {
22
+ const details = Object.fromEntries(output.trimEnd().split('\n').map(line => {
23
+ const equals = line.indexOf('=');
24
+ return [line.slice(0, equals), line.slice(equals + 1)];
25
+ }));
26
+ if (details.Id !== unit || details.LoadState !== 'loaded' || details.ActiveState !== 'active' ||
27
+ !/^[1-9][0-9]*$/.test(details.MainPID ?? '')) {
28
+ throw new Error(`Expected a loaded and active systemd service with a main process: ${unit}`);
29
+ }
30
+ if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*[$]?$/.test(details.User ?? '') ||
31
+ details.User === 'root' || /^0+$/.test(details.User) ||
32
+ details.DynamicUser !== 'no' || details.RootDirectory !== '' || details.RootImage !== '') {
33
+ throw new Error(`Service must use a fixed non-root account and the host filesystem: ${unit}`);
34
+ }
35
+ return { pid: details.MainPID, user: details.User };
36
+ }
37
+
38
+ function serviceDetails(unit) {
39
+ return readServiceProperties(unit, execute('/usr/bin/systemctl', [
40
+ '--system', 'show', '--no-pager', '--property=' + properties.join(','), '--', unit,
41
+ ]));
42
+ }
43
+
44
+ export function readServiceEnvironment(data) {
45
+ const env = {};
46
+ for (const item of data.split('\0')) {
47
+ const equals = item.indexOf('=');
48
+ if (equals === -1) continue;
49
+ const key = item.slice(0, equals);
50
+ if (!['HOME', 'DSH_HOME', 'DSH_AGENTS_HOME', 'KITTO_HOME', 'XDG_DATA_HOME', 'PATH'].includes(key)) continue;
51
+ if (Object.hasOwn(env, key)) throw new Error(`Duplicate service environment variable: ${key}`);
52
+ const value = item.slice(equals + 1);
53
+ const paths = key === 'PATH' ? value.split(':') : [value];
54
+ if (paths.some(path => !isAbsolute(path) || /[\u0000-\u001f\u007f]/.test(path))) {
55
+ throw new Error(`Service environment ${key} must contain absolute paths.`);
56
+ }
57
+ env[key] = value;
58
+ }
59
+ if (!env.HOME || !env.PATH) throw new Error('Service environment must provide HOME and PATH.');
60
+ return env;
61
+ }
62
+
63
+ async function accountForService(unit) {
64
+ const { pid, user } = serviceDetails(unit);
65
+ const [name, , uid] = execute('/usr/bin/getent', ['passwd', user]).trimEnd().split(':');
66
+ if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*[$]?$/.test(name) || !/^[1-9][0-9]*$/.test(uid ?? '')) {
67
+ throw new Error(`Service must use a fixed non-root account: ${unit}`);
68
+ }
69
+ const proc = `/proc/${pid}`;
70
+ const before = await readFile(join(proc, 'stat'), 'utf8');
71
+ const status = await readFile(join(proc, 'status'), 'utf8');
72
+ const processUids = status.match(/^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$/m)?.slice(1);
73
+ if (!processUids || !processUids.every(value => value === uid)) {
74
+ throw new Error(`Service process does not match the configured account: ${unit}`);
75
+ }
76
+ const environment = readServiceEnvironment(await readFile(join(proc, 'environ'), 'utf8'));
77
+ const after = await readFile(join(proc, 'stat'), 'utf8');
78
+ const startTime = value => value.slice(value.lastIndexOf(')') + 2).split(' ')[19];
79
+ const current = serviceDetails(unit);
80
+ if (!startTime(before) || startTime(before) !== startTime(after) || current.pid !== pid || current.user !== user) {
81
+ throw new Error(`Service changed while reading its account settings: ${unit}`);
82
+ }
83
+ return { name, uid, environment };
84
+ }
85
+
86
+ async function requireWorkspaceAccess(workspace, includeAssets) {
87
+ async function requireDirectory(path) {
88
+ let info;
89
+ try {
90
+ info = await stat(path);
91
+ } catch (error) {
92
+ if (error.code !== 'ENOENT') throw error;
93
+ const parent = dirname(path);
94
+ if (parent === path) throw error;
95
+ await requireDirectory(parent);
96
+ try {
97
+ await access(parent, constants.W_OK | constants.X_OK);
98
+ } catch (accessError) {
99
+ // A missing parent can also be created after its existing ancestor was checked.
100
+ if (accessError.code !== 'ENOENT') throw accessError;
101
+ }
102
+ return;
103
+ }
104
+ if (!info.isDirectory()) throw new Error(`Expected a directory: ${path}`);
105
+ await access(path, constants.R_OK | constants.X_OK);
106
+ }
107
+
108
+ await requireDirectory(workspace);
109
+ if (!includeAssets) return;
110
+ await requireDirectory(join(workspace, '.agents', 'skills'));
111
+ try {
112
+ await access(join(workspace, 'AGENTS.md'), constants.R_OK);
113
+ } catch (error) {
114
+ if (error.code !== 'ENOENT') throw error;
115
+ try { await access(workspace, constants.W_OK | constants.X_OK); }
116
+ catch (accessError) { if (accessError.code !== 'ENOENT') throw accessError; }
117
+ }
118
+ }
119
+
120
+ async function checkLocalSource(source) {
121
+ if (!source || !isAbsolute(source)) return;
122
+ try {
123
+ await access(source, constants.R_OK | constants.X_OK);
124
+ } catch (error) {
125
+ throw new Error(`The DSH service account cannot read the local source checkout ${source}. Use a checkout accessible to that account or a Git URL.`, { cause: error });
126
+ }
127
+ const git = spawnSync('git', ['-C', source, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 8_000 });
128
+ if (git.status !== 0) {
129
+ throw new Error(`The DSH service account cannot use the local Git checkout ${source}. Use a checkout trusted by that account or a Git URL.`);
130
+ }
131
+ }
132
+
133
+ // This function runs from the temporary package under the service identity.
134
+ async function runServiceSetup() {
135
+ const [, , uid, request] = process.argv;
136
+ if (!/^[1-9][0-9]*$/.test(uid ?? '') || String(process.getuid?.()) !== uid || String(process.geteuid?.()) !== uid) {
137
+ throw new Error('DSH setup must run under the selected non-root service account.');
138
+ }
139
+ const { source, dryRun, dshProfile, deps, workspace, global, installAgents, workspaceParent } = JSON.parse(request);
140
+ await checkLocalSource(source);
141
+ if (workspace) await requireWorkspaceAccess(workspace, !workspaceParent);
142
+ const { setup, maintain, kittoHome } = await import('./kitto.mjs');
143
+ const options = { agents: ['dsh'], 'dry-run': dryRun };
144
+ if (dshProfile) options['dsh-profile'] = dshProfile;
145
+ if (source !== false) {
146
+ await setup({ ...options, keepExistingSkills: true, ...(source ? { source } : {}), ...(installAgents ? { 'install-agents': true } : {}) });
147
+ }
148
+ const plans = [global && { global: true }, workspace && { [workspaceParent ? 'workspace-parent' : 'workspace']: workspace }].filter(Boolean);
149
+ if (plans.length && dryRun && source !== false && installAgents &&
150
+ spawnSync('dsh', ['--version'], { stdio: 'ignore', timeout: 8_000 }).status !== 0) {
151
+ console.log('DSH scope registration will run after the DSH CLI is installed.');
152
+ } else {
153
+ for (const plan of plans) await setup({ ...options, ...plan });
154
+ }
155
+ if (deps) {
156
+ const hasState = await stat(join(kittoHome(), 'state.json')).then(() => true, error => {
157
+ if (error.code === 'ENOENT') return false;
158
+ throw error;
159
+ });
160
+ if (!dryRun || source === false || hasState) {
161
+ await maintain(['deps', ...(!dryRun ? ['--apply'] : [])]);
162
+ } else if (source && isAbsolute(source)) {
163
+ const { installDependencies } = await import('./dependencies.mjs');
164
+ await installDependencies({ agents: ['dsh'], source }, false);
165
+ } else {
166
+ console.log('DSH dependency checks will run after the configuration checkout is available.');
167
+ }
168
+ }
169
+ }
170
+
171
+ export async function stageServicePackage(packageDir, stage, legacy = false) {
172
+ async function copy(relative, include = () => true) {
173
+ const source = join(packageDir, relative);
174
+ const target = join(stage, relative);
175
+ const info = await lstat(source);
176
+ if (info.isSymbolicLink()) throw new Error(`Expected an ordinary Kitto package path: ${source}`);
177
+ if (info.isDirectory()) {
178
+ await mkdir(target);
179
+ await chmod(target, 0o755);
180
+ for (const entry of await readdir(source)) {
181
+ if (!entry.startsWith('.') && !['__pycache__', 'node_modules'].includes(entry) && include(entry)) {
182
+ await copy(join(relative, entry));
183
+ }
184
+ }
185
+ } else {
186
+ if (!legacy && !relative.endsWith('.mjs')) return;
187
+ if (!info.isFile()) throw new Error(`Expected a regular Kitto package file: ${source}`);
188
+ await writeFile(target, await readFile(source), { flag: 'wx' });
189
+ await chmod(target, 0o644);
190
+ }
191
+ }
192
+
193
+ await copy('bin', name => name.endsWith('.mjs'));
194
+ await copy('lib', name => name.endsWith('.mjs') || (legacy && name.endsWith('.py')));
195
+ await copy('integration', name => legacy || name.startsWith('scoped-'));
196
+ if (legacy) for (const name of ['package.json', 'sync.sh', 'CHANGELOG.md']) await copy(name);
197
+ }
198
+
199
+ function validateServiceHost(unit) {
200
+ if (typeof unit !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.@-]*\.service$/.test(unit)) {
201
+ throw new Error('Expected a systemd service unit name ending in .service.');
202
+ }
203
+ if (process.platform !== 'linux' || process.getuid?.() !== 0 || process.geteuid?.() !== 0) {
204
+ throw new Error('DSH service setup requires root on a Linux systemd host.');
205
+ }
206
+ }
207
+
208
+ function serviceInvocation({ name, environment }, command) {
209
+ const assignments = Object.entries({ ...environment, USER: name, LOGNAME: name }).map(([key, value]) => key + '=' + value);
210
+ return ['-u', name, '--', '/usr/bin/env', '-i', ...assignments, ...command];
211
+ }
212
+
213
+ export async function servicePnpmAvailable(unit) {
214
+ validateServiceHost(unit);
215
+ const account = await accountForService(unit);
216
+ const result = spawnSync('/usr/sbin/runuser', serviceInvocation(account, ['pnpm', '--version']), {
217
+ cwd: '/', env: systemEnv, stdio: 'ignore', timeout: 3_000,
218
+ });
219
+ if (result.error) throw result.error;
220
+ return result.status === 0;
221
+ }
222
+
223
+ async function delegateServiceSetup(unit, packageDir, request) {
224
+ validateServiceHost(unit);
225
+ if (request.workspace !== undefined && (typeof request.workspace !== 'string' || !isAbsolute(request.workspace))) {
226
+ throw new Error('Service workspace must be an absolute path.');
227
+ }
228
+ const account = await accountForService(unit);
229
+ const stage = await mkdtemp('/tmp/kitto-service-');
230
+ try {
231
+ // Copy only executable assets from the initiating package. The service user can
232
+ // traverse and read this directory, and its contents stay owned by root.
233
+ await stageServicePackage(packageDir, stage, request.source !== false || request.deps);
234
+ await chmod(stage, 0o755);
235
+ console.log(`Delegating DSH setup for ${unit} to ${account.name}.`);
236
+ const runner = join(stage, 'lib', 'scope-service.mjs');
237
+ execute('/usr/sbin/runuser', serviceInvocation(account, ['node', runner, account.uid, JSON.stringify(request)]),
238
+ { cwd: stage, capture: false, timeout: request.dryRun ? 60_000 : 1_800_000 });
239
+ } finally {
240
+ await rm(stage, { recursive: true, force: true });
241
+ }
242
+ }
243
+
244
+ export async function configureServiceScope({ unit, root, dryRun = false, packageDir = defaultPackageDir, dshProfile }) {
245
+ if (typeof root !== 'string' || !isAbsolute(root)) throw new Error('Service workspace must be an absolute path.');
246
+ return delegateServiceSetup(unit, packageDir, { source: false, workspace: root, dryRun, dshProfile });
247
+ }
248
+
249
+ export async function configureServiceEnvironment({
250
+ unit, source, dryRun = false, dshProfile, deps = false, workspace, global = false, installAgents = false,
251
+ }) {
252
+ if (typeof source === 'string' && source && !/^(https:\/\/|ssh:\/\/|git@)/.test(source)) source = resolve(source);
253
+ return delegateServiceSetup(unit, defaultPackageDir, { source, dryRun, dshProfile, deps, workspace, global, installAgents, workspaceParent: true });
254
+ }
255
+
256
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
257
+ void runServiceSetup().catch(error => {
258
+ console.error('Kitto service setup: ' + error.message);
259
+ process.exitCode = 1;
260
+ });
261
+ }
@@ -0,0 +1,140 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { cp, lstat, mkdir, mkdtemp, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { basename, dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { readScopeRegistry, scopeHome } from './scopes.mjs';
8
+
9
+ const packageDir = fileURLToPath(new URL('../', import.meta.url));
10
+ const installers = { pi: 'installPiScope', codex: 'installCodexScope', dsh: 'installDshScope' };
11
+
12
+ async function exists(path) {
13
+ try { await lstat(path); return true; }
14
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
15
+ }
16
+
17
+ async function workspacePath(path) {
18
+ try { return await realpath(path); }
19
+ catch (error) {
20
+ if (error.code !== 'ENOENT' || await exists(path)) throw error;
21
+ return join(await workspacePath(dirname(path)), basename(path));
22
+ }
23
+ }
24
+
25
+ async function installRuntime(home) {
26
+ const runtime = join(home, 'scope-runtime');
27
+ const backup = join(home, 'scope-runtime.previous');
28
+ if (resolve(packageDir) === runtime) return runtime;
29
+ for (const dir of [runtime, backup]) {
30
+ if (await exists(dir) && !await exists(join(dir, '.kitto-scope-runtime'))) {
31
+ throw new Error('Existing directory is not a Kitto scope runtime: ' + dir);
32
+ }
33
+ }
34
+ if (await exists(backup) && !await exists(runtime)) await rename(backup, runtime);
35
+ const temp = await mkdtemp(join(home, '.scope-runtime-'));
36
+ try {
37
+ await writeFile(join(temp, '.kitto-scope-runtime'), '1\n');
38
+ for (const [dir, prefix] of [['lib', 'scope'], ['integration', 'scoped-']]) {
39
+ await mkdir(join(temp, dir));
40
+ for (const entry of await readdir(join(packageDir, dir))) {
41
+ if (entry.startsWith(prefix)) await cp(join(packageDir, dir, entry), join(temp, dir, entry), { recursive: true });
42
+ }
43
+ }
44
+ if (await exists(runtime)) {
45
+ await rm(backup, { recursive: true, force: true });
46
+ await rename(runtime, backup);
47
+ }
48
+ try { await rename(temp, runtime); }
49
+ catch (error) {
50
+ if (await exists(backup)) await rename(backup, runtime);
51
+ throw error;
52
+ }
53
+ await rm(backup, { recursive: true, force: true });
54
+ return runtime;
55
+ } finally { await rm(temp, { recursive: true, force: true }); }
56
+ }
57
+
58
+ export async function setupScope(options) {
59
+ const workspaceParent = options['workspace-parent'];
60
+ if ([options.global, options.workspace, workspaceParent].filter(Boolean).length !== 1) {
61
+ throw new Error('Choose exactly one of --global, --workspace PATH or --workspace-parent PATH.');
62
+ }
63
+ for (const key of Object.keys(options)) {
64
+ if (!['global', 'workspace', 'workspace-parent', 'agents', 'dsh-profile', 'dsh-service', 'dry-run'].includes(key)) {
65
+ throw new Error('Scoped setup does not support --' + key);
66
+ }
67
+ }
68
+ const dryRun = Boolean(options['dry-run']);
69
+ const home = scopeHome();
70
+ const global = Boolean(options.global);
71
+ const root = global ? join(home, 'global') : await workspacePath(resolve(workspaceParent || options.workspace));
72
+ if (!global && await exists(root) && !(await stat(root)).isDirectory()) throw new Error('Workspace must be a directory.');
73
+ const unit = options['dsh-service'];
74
+ if (unit && (global || workspaceParent || (options.agents && !options.agents.includes('dsh')))) {
75
+ throw new Error('--dsh-service requires --workspace PATH and the DSH host.');
76
+ }
77
+ const agents = options.agents || Object.keys(installers).filter(name =>
78
+ (name === 'dsh' && unit) || spawnSync(name, ['--version'], { stdio: 'ignore', timeout: 8000 }).status === 0);
79
+ if (!agents.length) throw new Error('No supported host CLI found in this account. Use --agents to select a host.');
80
+ const dshProfile = options['dsh-profile'] || 'web';
81
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(dshProfile) || dshProfile === 'desktop') throw new Error('Invalid DSH profile.');
82
+ if (options['dsh-profile'] && !agents.includes('dsh')) throw new Error('--dsh-profile requires DSH.');
83
+
84
+ const args = { global, root, home: homedir(), dshProfile, dryRun };
85
+ const scopeLabel = global ? 'global' : workspaceParent ? 'workspace parent' : 'workspace';
86
+ const contentRoot = workspaceParent ? join(root, '<workspace>') : root;
87
+ console.log(`Kitto ${scopeLabel}: ${root}\nHosts: ${agents.join(', ')}\nInstructions: ${join(contentRoot, 'AGENTS.md')}\nSkills: ${join(contentRoot, '.agents/skills')}`);
88
+ async function installHosts(directory, preview) {
89
+ for (const name of agents) {
90
+ if (unit && name === 'dsh') continue;
91
+ const module = await import(pathToFileURL(join(directory, 'lib', 'scope-' + name + '.mjs')));
92
+ await module[installers[name]]({ ...args, runtime: join(home, 'scope-runtime'), dryRun: preview });
93
+ }
94
+ }
95
+ async function configureService(preview) {
96
+ if (!unit) return;
97
+ const { configureServiceScope } = await import('./scope-service.mjs');
98
+ await configureServiceScope({ unit, root, dryRun: preview, packageDir, dshProfile });
99
+ }
100
+ const instructions = join(root, 'AGENTS.md');
101
+ if (!workspaceParent && await exists(instructions) && !(await stat(instructions)).isFile()) throw new Error('Expected an instructions file at ' + instructions);
102
+ const skills = join(root, '.agents/skills');
103
+ if (!workspaceParent && await exists(skills) && !(await stat(skills)).isDirectory()) throw new Error('Expected a skills directory at ' + skills);
104
+ await readScopeRegistry(home);
105
+ await installHosts(packageDir, true);
106
+ await configureService(true);
107
+ if (dryRun) return;
108
+
109
+ await mkdir(home, { recursive: true });
110
+ const lock = join(home, '.scope-setup.lock');
111
+ try { await mkdir(lock); }
112
+ catch (error) {
113
+ if (error.code === 'EEXIST') throw new Error('Scope setup is locked: ' + lock);
114
+ throw error;
115
+ }
116
+ try {
117
+ const registry = await readScopeRegistry(home);
118
+ const runtime = await installRuntime(home);
119
+ if (unit) {
120
+ // Create shared files under the account that works in this directory.
121
+ await configureService(false);
122
+ } else if (!workspaceParent) {
123
+ await mkdir(skills, { recursive: true });
124
+ try { await writeFile(instructions, '', { flag: 'wx' }); }
125
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
126
+ }
127
+ await installHosts(runtime, false);
128
+ if (global) registry.global = true;
129
+ else {
130
+ const roots = workspaceParent ? (registry.workspaceParents ??= []) : registry.workspaces;
131
+ if (!roots.includes(root)) roots.push(root);
132
+ }
133
+ const next = join(home, 'scopes.' + randomUUID() + '.tmp');
134
+ try {
135
+ await writeFile(next, JSON.stringify(registry, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
136
+ await rename(next, join(home, 'scopes.json'));
137
+ } finally { await rm(next, { force: true }); }
138
+ console.log('Scope ready. Start a new agent session in your project.');
139
+ } finally { await rm(lock, { recursive: true }); }
140
+ }
package/lib/scopes.mjs ADDED
@@ -0,0 +1,51 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const packageDir = fileURLToPath(new URL('../', import.meta.url));
8
+ const runtimeDir = resolve(packageDir);
9
+
10
+ export function scopeHome() {
11
+ // Native agents may run without the environment used by the setup command.
12
+ if (runtimeDir.endsWith(sep + 'scope-runtime') && existsSync(join(runtimeDir, '.kitto-scope-runtime'))) return dirname(runtimeDir);
13
+ return resolve(process.env.KITTO_HOME || join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'kitto'));
14
+ }
15
+
16
+ export async function readScopeRegistry(home = scopeHome()) {
17
+ let contents;
18
+ try { contents = await readFile(join(home, 'scopes.json'), 'utf8'); }
19
+ catch (error) {
20
+ if (error.code === 'ENOENT') return { version: 1, global: false, workspaces: [] };
21
+ throw error;
22
+ }
23
+ const registry = JSON.parse(contents);
24
+ const { workspaceParents, workspaces } = registry;
25
+ const paths = value => Array.isArray(value) && value.every(path => typeof path === 'string' && isAbsolute(path));
26
+ if (registry.version !== 1 || typeof registry.global !== 'boolean' ||
27
+ !paths(workspaces) || (workspaceParents !== undefined && !paths(workspaceParents))) {
28
+ throw new Error('Invalid Kitto scope registry: ' + join(home, 'scopes.json'));
29
+ }
30
+ return registry;
31
+ }
32
+
33
+ function descendantPath(root, directory) {
34
+ const path = relative(root, directory);
35
+ if (path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path)) return path;
36
+ }
37
+
38
+ export async function resolveScopes(cwd, home = scopeHome()) {
39
+ const registry = await readScopeRegistry(home);
40
+ const directory = await realpath(cwd);
41
+ const roots = registry.workspaces.filter(root => descendantPath(root, directory) !== undefined);
42
+ for (const parent of registry.workspaceParents ?? []) {
43
+ const path = descendantPath(parent, directory);
44
+ if (path) roots.push(join(parent, path.split(sep, 1)[0]));
45
+ }
46
+ roots.sort((left, right) => left.length - right.length);
47
+ if (registry.global) roots.unshift(join(home, 'global'));
48
+ return [...new Set(roots)].map(root => ({
49
+ root, instructions: join(root, 'AGENTS.md'), skills: join(root, '.agents', 'skills'),
50
+ }));
51
+ }