@phyzess/kitto 0.2.1 → 0.3.1

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.
package/lib/pi_config.py CHANGED
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env python3
2
- """Structural merge helpers for pi-config sync.
2
+ """Structural helpers for the Pi adapter.
3
3
 
4
- Three responsibilities, each exposed as a subcommand so sync.sh can stay in bash:
4
+ Each responsibility is a small subcommand so sync.sh can stay in bash:
5
5
 
6
6
  merge-settings repo settings + machine settings + machine-only packages -> machine settings
7
7
  sanitize-settings machine settings -> repo settings (drops volatile keys)
8
8
  merge-mcp repo + platform + machine local + machine -> machine mcp.json
9
+ compose-agents shared rules + host addendum -> deployed AGENTS.md
10
+ extract-agents deployed AGENTS.md -> host addendum only (never shared rules)
11
+ legacy-agents deployed AGENTS.md -> whole-file export for sources without common.md
9
12
 
10
13
  Shared definitions are updated while machine overrides and runtime switches
11
14
  stay local. Preview helpers write only their explicit output path.
@@ -15,11 +18,78 @@ from __future__ import annotations
15
18
 
16
19
  import json
17
20
  import os
21
+ import re
18
22
  import sys
19
23
  import tempfile
20
24
 
21
25
  VOLATILE_KEYS = ("lastChangelogVersion", "extensionChangelogVersions")
22
26
 
27
+ # Explicit boundary between the shared layer and the host addendum. Without it,
28
+ # a truncated common.md can look like an addendum prefix of an older deployed
29
+ # file; the boundary (plus an exact shared-section comparison) makes the split
30
+ # unambiguous. Keep in sync with lib/host-config.mjs.
31
+ AGENTS_BOUNDARY = "<!-- kitto:host-addendum -->"
32
+
33
+ # Export must never turn a local secret into a repository commit. These are the
34
+ # key names and literal shapes that Kitto refuses to write into the source tree.
35
+ SECRET_KEY_NAMES = frozenset({
36
+ "apikey", "api_key", "token", "access_token", "refresh_token", "secret",
37
+ "client_secret", "password", "passwd", "private_key", "bearer_token", "authorization",
38
+ })
39
+ SECRET_VALUE_PATTERNS = (
40
+ ("openai-style key", re.compile(r"sk-[A-Za-z0-9_-]{16,}")),
41
+ ("GitHub token", re.compile(r"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}")),
42
+ ("GitHub fine-grained token", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
43
+ ("Slack token", re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
44
+ ("AWS access key", re.compile(r"AKIA[0-9A-Z]{16}")),
45
+ ("JWT", re.compile(r"eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")),
46
+ ("private key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
47
+ )
48
+
49
+
50
+ def scan_secrets(value, path=""):
51
+ """Return (cleaned, removed key paths, found literal secrets).
52
+
53
+ Dict keys named like credentials are removed. Literal token shapes remain
54
+ in place but are reported so the caller can refuse the export.
55
+ """
56
+ removed, found = [], []
57
+ if isinstance(value, dict):
58
+ out = {}
59
+ for key, item in value.items():
60
+ child = f"{path}.{key}" if path else key
61
+ if key.casefold() in SECRET_KEY_NAMES:
62
+ removed.append(child)
63
+ continue
64
+ cleaned, child_removed, child_found = scan_secrets(item, child)
65
+ out[key] = cleaned
66
+ removed.extend(child_removed)
67
+ found.extend(child_found)
68
+ return out, removed, found
69
+ if isinstance(value, list):
70
+ cleaned = []
71
+ for index, item in enumerate(value):
72
+ child = f"{path}[{index}]"
73
+ item, child_removed, child_found = scan_secrets(item, child)
74
+ cleaned.append(item)
75
+ removed.extend(child_removed)
76
+ found.extend(child_found)
77
+ return cleaned, removed, found
78
+ if isinstance(value, str):
79
+ for label, pattern in SECRET_VALUE_PATTERNS:
80
+ if pattern.search(value):
81
+ found.append((path, label))
82
+ return value, removed, found
83
+
84
+
85
+ def refuse_secrets(found):
86
+ if not found:
87
+ return False
88
+ for path, label in found:
89
+ print(f"refusing to export a literal secret ({label}) at {path}", file=sys.stderr)
90
+ print("Replace the literal with an environment-variable reference or remove it before exporting.", file=sys.stderr)
91
+ return True
92
+
23
93
 
24
94
  # ---------------------------------------------------------------- helpers
25
95
 
@@ -63,6 +133,52 @@ def dump_semantic(path: str, data) -> bool:
63
133
  return dump(path, data)
64
134
 
65
135
 
136
+ def read_text(path: str) -> str | None:
137
+ if not path or not os.path.exists(path):
138
+ return None
139
+ with open(path, encoding="utf-8") as fh:
140
+ return fh.read()
141
+
142
+
143
+ def write_text(path: str, text: str) -> bool:
144
+ """Write UTF-8 text atomically. Returns True when the file changed."""
145
+ old = read_text(path)
146
+ if old == text:
147
+ return False
148
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
149
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".kitto-")
150
+ try:
151
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
152
+ fh.write(text)
153
+ os.replace(tmp, path)
154
+ finally:
155
+ if os.path.exists(tmp):
156
+ os.unlink(tmp)
157
+ return True
158
+
159
+
160
+ def normalize_instructions(text: str) -> str:
161
+ """One canonical form for shared-layer files: no BOM, LF line endings."""
162
+ if text.startswith("\ufeff"):
163
+ text = text[1:]
164
+ return text.replace("\r\n", "\n").replace("\r", "\n")
165
+
166
+
167
+ def compose_agents(common: str | None, addendum: str | None) -> str:
168
+ """Shared rules first, a boundary line, then the host addendum.
169
+
170
+ Byte-identical to composeInstructions() in lib/host-config.mjs. Normalizing
171
+ and stripping each section keeps the result stable no matter how the files
172
+ end or which platform produced them. A single section (legacy sources with
173
+ no shared layer) keeps the historical output without a boundary.
174
+ """
175
+ sections = [normalize_instructions(text).strip() for text in (common, addendum) if text]
176
+ sections = [text for text in sections if text]
177
+ if not sections:
178
+ return ""
179
+ return ("\n\n" + AGENTS_BOUNDARY + "\n\n").join(sections) + "\n"
180
+
181
+
66
182
  def read_list(path: str) -> list[str]:
67
183
  if not os.path.exists(path):
68
184
  return []
@@ -229,13 +345,14 @@ def cmd_sanitize_settings(argv: list[str]) -> int:
229
345
  out[key] = packages if key == "packages" else machine.get(key, repo[key])
230
346
  if "packages" not in out:
231
347
  out["packages"] = packages
232
- for key, value in machine.items():
233
- if key in out or key in VOLATILE_KEYS:
234
- continue
235
- out[key] = value
236
348
 
237
349
  overrides = load(os.path.join(local_dir, "settings.json"), {}) or {}
238
350
  out = restore_overrides(out, repo, overrides)
351
+ out, removed, found = scan_secrets(out)
352
+ if refuse_secrets(found):
353
+ return 1
354
+ if removed:
355
+ print(" credential-shaped keys left out: " + ", ".join(sorted(removed)))
239
356
  changed = dump_semantic(out_path, out)
240
357
  print(f"settings: {'exported' if changed else 'unchanged'}")
241
358
  if dropped:
@@ -299,17 +416,105 @@ def cmd_export_mcp(argv: list[str]) -> int:
299
416
  else:
300
417
  dropped.append(name) # platform-only server never ships
301
418
  continue
302
- out[name] = entry
419
+ if name in repo:
420
+ out[name] = entry
421
+ else:
422
+ dropped.append(name) # unmanaged server never ships
303
423
 
424
+ out, removed, found = scan_secrets(out)
425
+ if refuse_secrets(found):
426
+ return 1
427
+ if removed:
428
+ print(" credential-shaped keys left out: " + ", ".join(sorted(removed)))
304
429
  changed = dump_semantic(out_path, {"mcpServers": out})
305
430
  print(f"mcp: {'exported' if changed else 'unchanged'} ({len(out)} servers)")
306
431
  if dropped:
307
- print(" left out (local/platform/private): " + ", ".join(sorted(dropped)))
432
+ print(" left out (unmanaged/local/platform/private): " + ", ".join(sorted(dropped)))
308
433
  if replaced:
309
434
  print(" repo entry kept instead of machine override: " + ", ".join(sorted(replaced)))
310
435
  return 0
311
436
 
312
437
 
438
+ def cmd_compose_agents(argv: list[str]) -> int:
439
+ common_path, addendum_path, out_path = argv
440
+ common, addendum = read_text(common_path), read_text(addendum_path)
441
+ if common is None:
442
+ print(f"missing shared instructions: {common_path}", file=sys.stderr)
443
+ return 1
444
+ for path, text in ((common_path, common), (addendum_path, addendum)):
445
+ if text and AGENTS_BOUNDARY in text:
446
+ print(f"reserved shared/host boundary in {path}", file=sys.stderr)
447
+ return 1
448
+ write_text(out_path, compose_agents(common, addendum))
449
+ return 0
450
+
451
+
452
+ def cmd_extract_agents(argv: list[str]) -> int:
453
+ """Export only the host addendum, so shared rules never travel upstream."""
454
+ machine_path, common_path, out_path = argv
455
+ machine, common = read_text(machine_path), read_text(common_path)
456
+ if machine is None:
457
+ print(f"missing deployed instructions: {machine_path}", file=sys.stderr)
458
+ return 1
459
+ if common is None:
460
+ print(f"missing shared instructions: {common_path}", file=sys.stderr)
461
+ return 1
462
+ prefix = normalize_instructions(common).strip()
463
+ body = normalize_instructions(machine).strip()
464
+ lines = body.split("\n")
465
+ boundaries = [index for index, line in enumerate(lines) if line.strip() == AGENTS_BOUNDARY]
466
+ if not boundaries:
467
+ print(f"{machine_path} has no {AGENTS_BOUNDARY} boundary; push only exports the host-specific "
468
+ "section of a file composed from the current shared layer. Run sync before exporting.",
469
+ file=sys.stderr)
470
+ return 1
471
+ if len(boundaries) > 1:
472
+ print(f"{machine_path} contains more than one {AGENTS_BOUNDARY} boundary; refusing to export.",
473
+ file=sys.stderr)
474
+ return 1
475
+ # Compare the whole shared section, not just a prefix: deleting the tail of
476
+ # common.md must not turn old shared rules into an addendum.
477
+ split = boundaries[0]
478
+ if "\n".join(lines[:split]).strip() != prefix:
479
+ print(f"{machine_path} shared rules differ from {common_path} (the deployed file may predate "
480
+ "the current shared layer); run sync before exporting.", file=sys.stderr)
481
+ return 1
482
+ addendum = "\n".join(lines[split + 1:]).strip()
483
+ if not addendum:
484
+ print(f"{machine_path} has no host-specific section; refusing to export an empty addendum.", file=sys.stderr)
485
+ return 1
486
+ if compose_agents(common, addendum) != body + "\n":
487
+ print(f"{machine_path} is not a canonical shared-layer composition; run sync before exporting. "
488
+ "Shared rules must be edited in the source, not in the deployed file.", file=sys.stderr)
489
+ return 1
490
+ changed = write_text(out_path, addendum + "\n")
491
+ print(f"AGENTS.md: {'exported' if changed else 'unchanged'} (host addendum only)")
492
+ return 0
493
+
494
+
495
+ def cmd_legacy_agents(argv: list[str]) -> int:
496
+ """Stage the historical whole-file export for sources without common.md.
497
+
498
+ A file composed with the shared layer (it carries the boundary) must not be
499
+ copied wholesale into a legacy addendum: the boundary and shared rules
500
+ would leak into the source and duplicate on the next shared-layer pull.
501
+ """
502
+ machine_path, out_path = argv
503
+ machine = read_text(machine_path)
504
+ if machine is None:
505
+ print(f"missing deployed instructions: {machine_path}", file=sys.stderr)
506
+ return 1
507
+ if AGENTS_BOUNDARY in normalize_instructions(machine):
508
+ print(f"{machine_path} is composed with a shared layer ({AGENTS_BOUNDARY}), but the "
509
+ "configuration source has no config/instructions/common.md; refusing the whole-file "
510
+ "export. Sync from the source that contains the shared layer, or start from a "
511
+ "legacy-only AGENTS.md.", file=sys.stderr)
512
+ return 1
513
+ write_text(out_path, machine)
514
+ print("AGENTS.md: legacy whole-file export (source has no shared layer)")
515
+ return 0
516
+
517
+
313
518
  COMMANDS = {
314
519
  "list-shared-packages": cmd_list_shared_packages,
315
520
  "record-settings": cmd_record_settings,
@@ -317,12 +522,16 @@ COMMANDS = {
317
522
  "sanitize-settings": cmd_sanitize_settings,
318
523
  "merge-mcp": cmd_merge_mcp,
319
524
  "export-mcp": cmd_export_mcp,
525
+ "compose-agents": cmd_compose_agents,
526
+ "extract-agents": cmd_extract_agents,
527
+ "legacy-agents": cmd_legacy_agents,
320
528
  }
321
529
 
322
530
 
323
531
  def main(argv: list[str]) -> int:
324
532
  if len(argv) < 2 or argv[1] not in COMMANDS:
325
- sys.exit("usage: pi_config.py {merge-settings|sanitize-settings|merge-mcp|export-mcp} ...")
533
+ sys.exit("usage: pi_config.py "
534
+ "{merge-settings|sanitize-settings|merge-mcp|export-mcp|compose-agents|extract-agents|legacy-agents} ...")
326
535
  return COMMANDS[argv[1]](argv[2:])
327
536
 
328
537
 
package/lib/scope-dsh.mjs CHANGED
@@ -1,33 +1,13 @@
1
- import { spawnSync } from 'node:child_process';
2
1
  import { randomUUID } from 'node:crypto';
3
- import { constants } from 'node:fs';
4
- import { access, lstat, mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
5
- import { delimiter, dirname, join, resolve } from 'node:path';
2
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
6
4
  import { fileURLToPath } from 'node:url';
7
- import { importFromDsh } from '../integration/scoped-dsh/native.mjs';
5
+ import { desktopScopeError, isDesktopProfile, validateDshProfile } from './dsh-profile.mjs';
6
+ import { dshExecutable, importFromDsh } from '../integration/scoped-dsh/native.mjs';
8
7
 
9
8
  const pluginId = 'phyzess-kitto-scopes';
10
9
  const defaultRuntime = fileURLToPath(new URL('../', import.meta.url));
11
10
 
12
- async function dshExecutable() {
13
- for (const dir of (process.env.PATH ?? '').split(delimiter)) {
14
- const candidate = resolve(dir, 'dsh');
15
- try {
16
- await access(candidate, constants.X_OK);
17
- if ((await lstat(candidate)).isDirectory()) continue;
18
- const entry = await realpath(candidate);
19
- if (entry.endsWith('/mise') || dir.endsWith('/shims')) {
20
- const result = spawnSync(entry.endsWith('/mise') ? entry : 'mise', ['which', 'dsh'], { encoding: 'utf8', timeout: 8000 });
21
- if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
22
- }
23
- return candidate;
24
- } catch (error) {
25
- if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) throw error;
26
- }
27
- }
28
- throw new Error('DSH must be installed and available on PATH to configure its profile.');
29
- }
30
-
31
11
  async function readPatch(path) {
32
12
  try {
33
13
  const info = await lstat(path);
@@ -40,21 +20,20 @@ async function readPatch(path) {
40
20
  }
41
21
 
42
22
  export async function installDshScope({ dryRun, home, runtime = defaultRuntime, dshProfile = 'web' }) {
43
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(dshProfile) || dshProfile === 'desktop') {
44
- throw new Error('Invalid DSH CLI profile name.');
45
- }
23
+ const profile = validateDshProfile(dshProfile);
24
+ if (isDesktopProfile(profile)) throw new Error(desktopScopeError);
46
25
  const configuredHome = process.env.DSH_HOME?.trim() || join(home, '.dsh');
47
26
  const dshHome = resolve(configuredHome === '~' ? home
48
27
  : configuredHome.startsWith('~/') ? join(home, configuredHome.slice(2)) : configuredHome);
49
- const path = join(dshHome, 'profiles', dshProfile, 'cordis.patch.yml');
28
+ const path = join(dshHome, 'profiles', profile, 'cordis.patch.yml');
50
29
  const plugin = join(runtime, 'integration', 'scoped-dsh', 'index.mjs');
51
30
  const executable = await dshExecutable();
52
31
  const [{ isSeq, parseDocument }, { PROFILE_TEMPLATES }] = await Promise.all([
53
32
  importFromDsh(executable, 'yaml'),
54
33
  importFromDsh(executable, '@deepseek-ai/dsh-official-bundles'),
55
34
  ]);
56
- if (!Object.hasOwn(PROFILE_TEMPLATES, dshProfile) && (await readPatch(join(dirname(path), 'package.json'))).content === null) {
57
- throw new Error(`Initialize the native DSH profile ${dshProfile} before setup.`);
35
+ if (!Object.hasOwn(PROFILE_TEMPLATES, profile) && (await readPatch(join(dirname(path), 'package.json'))).content === null) {
36
+ throw new Error(`Initialize the native DSH profile ${profile} before setup.`);
58
37
  }
59
38
  const before = await readPatch(path);
60
39
  const document = parseDocument(before.content ?? '[]\n', {
@@ -88,5 +67,5 @@ export async function installDshScope({ dryRun, home, runtime = defaultRuntime,
88
67
  } finally {
89
68
  await rm(temporary, { force: true });
90
69
  }
91
- console.log(`DSH scoped configuration registered for the ${dshProfile} profile. Restart running DSH servers for this profile.`);
70
+ console.log(`DSH scoped configuration registered for the ${profile} profile. Restart running DSH servers for this profile.`);
92
71
  }
@@ -1,10 +1,11 @@
1
- import { randomUUID } from 'node:crypto';
2
1
  import { spawnSync } from 'node:child_process';
3
2
  import { cp, lstat, mkdir, mkdtemp, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
4
3
  import { homedir } from 'node:os';
5
4
  import { basename, dirname, join, resolve } from 'node:path';
6
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { readScopeRegistry, scopeHome } from './scopes.mjs';
6
+ import { readScopeRegistry, scopeHome, writeScopeRegistry } from './scopes.mjs';
7
+ import { canWrite, ensureCodeGraphIndexes } from './codegraph.mjs';
8
+ import { desktopScopeError, isDesktopProfile, validateDshProfile } from './dsh-profile.mjs';
8
9
 
9
10
  const packageDir = fileURLToPath(new URL('../', import.meta.url));
10
11
  const installers = { pi: 'installPiScope', codex: 'installCodexScope', dsh: 'installDshScope' };
@@ -41,6 +42,8 @@ async function installRuntime(home) {
41
42
  if (entry.startsWith(prefix)) await cp(join(packageDir, dir, entry), join(temp, dir, entry), { recursive: true });
42
43
  }
43
44
  }
45
+ await cp(join(packageDir, 'lib', 'codegraph.mjs'), join(temp, 'lib', 'codegraph.mjs'));
46
+ await cp(join(packageDir, 'lib', 'dsh-profile.mjs'), join(temp, 'lib', 'dsh-profile.mjs'));
44
47
  if (await exists(runtime)) {
45
48
  await rm(backup, { recursive: true, force: true });
46
49
  await rename(runtime, backup);
@@ -61,7 +64,7 @@ export async function setupScope(options) {
61
64
  throw new Error('Choose exactly one of --global, --workspace PATH or --workspace-parent PATH.');
62
65
  }
63
66
  for (const key of Object.keys(options)) {
64
- if (!['global', 'workspace', 'workspace-parent', 'agents', 'dsh-profile', 'dsh-service', 'dry-run'].includes(key)) {
67
+ if (!['global', 'workspace', 'workspace-parent', 'agents', 'dsh-profile', 'dsh-service', 'dry-run', 'require-baseline'].includes(key)) {
65
68
  throw new Error('Scoped setup does not support --' + key);
66
69
  }
67
70
  }
@@ -74,17 +77,29 @@ export async function setupScope(options) {
74
77
  if (unit && (global || workspaceParent || (options.agents && !options.agents.includes('dsh')))) {
75
78
  throw new Error('--dsh-service requires --workspace PATH and the DSH host.');
76
79
  }
77
- const agents = options.agents || Object.keys(installers).filter(name =>
80
+ const dshProfile = validateDshProfile(options['dsh-profile'] || 'web', 'Invalid DSH profile.');
81
+ const requestedAgents = options.agents || Object.keys(installers).filter(name =>
78
82
  (name === 'dsh' && unit) || spawnSync(name, ['--version'], { stdio: 'ignore', timeout: 8000 }).status === 0);
83
+ if (options['dsh-profile'] && !requestedAgents.includes('dsh')) throw new Error('--dsh-profile requires DSH.');
84
+ if (unit && isDesktopProfile(dshProfile)) {
85
+ throw new Error('The DSH desktop profile cannot be configured for a system service. Use --dsh-profile web.');
86
+ }
87
+ let agents = requestedAgents;
88
+ if (agents.includes('dsh') && isDesktopProfile(dshProfile)) {
89
+ // The app owns profiles/desktop: no scoped patch or adapter may be written.
90
+ if (!agents.some(name => name !== 'dsh')) throw new Error(desktopScopeError);
91
+ agents = agents.filter(name => name !== 'dsh');
92
+ console.warn('Kitto: skipping the DSH desktop profile in scoped setup; the Desktop app manages it and Kitto v1 does not write its profile patch.');
93
+ }
79
94
  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
95
 
84
96
  const args = { global, root, home: homedir(), dshProfile, dryRun };
85
97
  const scopeLabel = global ? 'global' : workspaceParent ? 'workspace parent' : 'workspace';
86
98
  const contentRoot = workspaceParent ? join(root, '<workspace>') : root;
87
99
  console.log(`Kitto ${scopeLabel}: ${root}\nHosts: ${agents.join(', ')}\nInstructions: ${join(contentRoot, 'AGENTS.md')}\nSkills: ${join(contentRoot, '.agents/skills')}`);
100
+ if (!global && await exists(root) && !canWrite(root)) {
101
+ console.warn(`Kitto: workspace ${root} is not writable by the current user. Agents cannot create CodeGraph indexes or edit files there; grant write access (chown or setfacl) before starting a session.`);
102
+ }
88
103
  async function installHosts(directory, preview) {
89
104
  for (const name of agents) {
90
105
  if (unit && name === 'dsh') continue;
@@ -104,7 +119,10 @@ export async function setupScope(options) {
104
119
  await readScopeRegistry(home);
105
120
  await installHosts(packageDir, true);
106
121
  await configureService(true);
107
- if (dryRun) return;
122
+ if (dryRun) {
123
+ if (!global) console.log(`CodeGraph: would initialize missing indexes under ${root} when the CLI is available.`);
124
+ return;
125
+ }
108
126
 
109
127
  await mkdir(home, { recursive: true });
110
128
  const lock = join(home, '.scope-setup.lock');
@@ -130,11 +148,15 @@ export async function setupScope(options) {
130
148
  const roots = workspaceParent ? (registry.workspaceParents ??= []) : registry.workspaces;
131
149
  if (!roots.includes(root)) roots.push(root);
132
150
  }
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 }); }
151
+ await writeScopeRegistry(home, registry);
138
152
  console.log('Scope ready. Start a new agent session in your project.');
153
+ if (!global) {
154
+ const owner = await stat(root).then(info => info.uid).catch(() => null);
155
+ if (process.getuid?.() === 0 && owner !== null && owner !== 0) {
156
+ console.warn(`CodeGraph indexes: setup runs as root but ${root} belongs to uid ${owner}; run codegraph init as that user instead.`);
157
+ } else {
158
+ await ensureCodeGraphIndexes({ home, source: join(home, 'config') }, { apply: true, registeredOnly: true });
159
+ }
160
+ }
139
161
  } finally { await rm(lock, { recursive: true }); }
140
162
  }
package/lib/scopes.mjs CHANGED
@@ -1,5 +1,6 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { existsSync } from 'node:fs';
2
- import { readFile, realpath } from 'node:fs/promises';
3
+ import { chmod, mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
4
5
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
@@ -13,23 +14,57 @@ export function scopeHome() {
13
14
  return resolve(process.env.KITTO_HOME || join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'kitto'));
14
15
  }
15
16
 
17
+ const registryPath = home => join(home, 'scopes.json');
18
+
19
+ function emptyScopeRegistry() {
20
+ return { version: 1, global: false, workspaces: [], workspaceParents: [] };
21
+ }
22
+
23
+ function validateScopeRegistry(registry, file) {
24
+ const paths = value => Array.isArray(value) && value.every(path => typeof path === 'string' && isAbsolute(path));
25
+ if (!registry || typeof registry !== 'object' || Array.isArray(registry) ||
26
+ registry.version !== 1 || typeof registry.global !== 'boolean' ||
27
+ !paths(registry.workspaces) ||
28
+ (registry.workspaceParents !== undefined && !paths(registry.workspaceParents))) {
29
+ throw new Error('Invalid Kitto scope registry: ' + file);
30
+ }
31
+ }
32
+
16
33
  export async function readScopeRegistry(home = scopeHome()) {
34
+ const file = registryPath(home);
17
35
  let contents;
18
- try { contents = await readFile(join(home, 'scopes.json'), 'utf8'); }
36
+ try { contents = await readFile(file, 'utf8'); }
19
37
  catch (error) {
20
- if (error.code === 'ENOENT') return { version: 1, global: false, workspaces: [] };
38
+ if (error.code === 'ENOENT') return emptyScopeRegistry();
21
39
  throw error;
22
40
  }
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
- }
41
+ let registry;
42
+ try { registry = JSON.parse(contents); }
43
+ catch (error) { throw new Error('Invalid Kitto scope registry: ' + file, { cause: error }); }
44
+ validateScopeRegistry(registry, file);
30
45
  return registry;
31
46
  }
32
47
 
48
+ /** Write the scope registry atomically, preserving unknown top-level fields. */
49
+ export async function writeScopeRegistry(home, registry) {
50
+ const file = registryPath(home);
51
+ validateScopeRegistry(registry, file);
52
+ const next = {
53
+ ...registry,
54
+ workspaces: [...registry.workspaces],
55
+ workspaceParents: [...(registry.workspaceParents ?? [])],
56
+ };
57
+ await mkdir(home, { recursive: true });
58
+ const temporary = join(home, 'scopes.' + randomUUID() + '.tmp');
59
+ try {
60
+ await writeFile(temporary, JSON.stringify(next, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
61
+ await chmod(temporary, 0o600);
62
+ await rename(temporary, file);
63
+ } finally {
64
+ await rm(temporary, { force: true });
65
+ }
66
+ }
67
+
33
68
  function descendantPath(root, directory) {
34
69
  const path = relative(root, directory);
35
70
  if (path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path)) return path;
@@ -1,6 +1,7 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { homedir } from 'node:os';
3
3
  import { resolve } from 'node:path';
4
+ import { isDesktopProfile, normalizeDshProfile } from './dsh-profile.mjs';
4
5
  import { setupPrompts } from './setup-prompts.mjs';
5
6
  import { promisify } from 'node:util';
6
7
 
@@ -56,6 +57,8 @@ async function configure({ input, output, environment, execute, probeServicePnpm
56
57
  let selected;
57
58
  let unit;
58
59
  let installAgents;
60
+ let dshProfile = 'web';
61
+ let dshProfileAsked = false;
59
62
  while (true) {
60
63
  selected = await hosts(hostOptions, defaults);
61
64
  if (!selected?.length) return undefined;
@@ -67,7 +70,28 @@ async function configure({ input, output, environment, execute, probeServicePnpm
67
70
  if (useService) unit = serviceUnit;
68
71
  }
69
72
 
70
- const missing = selected.filter(agent => !available.includes(agent) && !(agent === 'dsh' && unit));
73
+ if (selected.includes('dsh') && !dshProfileAsked) {
74
+ dshProfile = await text('DSH 配置档名称(desktop 由 Desktop 应用管理,仅部署全局规则/skills)', {
75
+ initialValue: 'web',
76
+ validate: value => {
77
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value)) return '请输入有效的 DSH 配置档名称';
78
+ if (unit && value.toLowerCase() === 'desktop') return '系统服务不能使用 desktop 配置档';
79
+ },
80
+ });
81
+ if (dshProfile === undefined) return undefined;
82
+ dshProfile = normalizeDshProfile(dshProfile);
83
+ dshProfileAsked = true;
84
+ if (isDesktopProfile(dshProfile)) {
85
+ print('DSH Desktop 由 App 管理:Kitto 只部署全局 AGENTS.md 和 skills;不安装 bundle、不写 profile patch、不需要 pnpm。');
86
+ }
87
+ }
88
+
89
+ const desktopDsh = selected.includes('dsh') && isDesktopProfile(dshProfile);
90
+ const missing = selected.filter(agent => !available.includes(agent) &&
91
+ !(agent === 'dsh' && (unit || desktopDsh)));
92
+ if (desktopDsh && !available.includes('dsh')) {
93
+ print('DSH Desktop 不要求本机 dsh CLI:Kitto 不会用 npm 补装它。');
94
+ }
71
95
  installAgents = false;
72
96
  if (missing.length) {
73
97
  installAgents = await yesNo(`补装 ${missing.map(agent => names[agent]).join('、')}?`, true);
@@ -90,7 +114,12 @@ async function configure({ input, output, environment, execute, probeServicePnpm
90
114
  ], '1');
91
115
  if (sourceChoice === undefined || sourceChoice === '0') return;
92
116
 
93
- const needsPnpm = sourceChoice !== '3' && selected.includes('dsh') && !unit && pnpmAvailable === false;
117
+ if (sourceChoice === '3' && isDesktopProfile(dshProfile) && selected.includes('dsh')) {
118
+ print('DSH Desktop 需要配置来源才能部署全局规则与 skills,不能选择「仅配置共享规则与 skills」。请选择 1 或 2,或改用 web 配置档。');
119
+ continue;
120
+ }
121
+
122
+ const needsPnpm = sourceChoice !== '3' && selected.includes('dsh') && !unit && !isDesktopProfile(dshProfile) && pnpmAvailable === false;
94
123
  if (needsPnpm) {
95
124
  const installPnpm = await yesNo('本机 DSH 的完整配置需要 pnpm。允许补装 pnpm?', true);
96
125
  if (installPnpm === undefined) return;
@@ -101,7 +130,7 @@ async function configure({ input, output, environment, execute, probeServicePnpm
101
130
  installAgents = true;
102
131
  }
103
132
 
104
- if (unit && sourceChoice !== '3') {
133
+ if (unit && sourceChoice !== '3' && !isDesktopProfile(dshProfile)) {
105
134
  servicePnpmAvailable ??= await probeServicePnpm(unit);
106
135
  if (servicePnpmAvailable === false) {
107
136
  const installPnpm = await yesNo(`服务 ${unit} 的完整配置需要 pnpm。允许在服务账号中补装 pnpm?`, true);
@@ -129,15 +158,6 @@ async function configure({ input, output, environment, execute, probeServicePnpm
129
158
  const workspace = await text('工作区父目录(可选)。例如未来项目会放在 ~/workspaces/workspace-1 下,就填 ~/workspaces。留空使用全局配置。');
130
159
  if (workspace === undefined) return undefined;
131
160
 
132
- let dshProfile = 'web';
133
- if (selected.includes('dsh')) {
134
- dshProfile = await text('DSH 配置档名称', {
135
- initialValue: 'web',
136
- validate: value => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value) && value !== 'desktop' ? undefined : '请输入有效的 DSH 配置档名称',
137
- });
138
- if (dshProfile === undefined) return undefined;
139
- }
140
-
141
161
  const plan = {
142
162
  agents: selected, source, installAgents, deps, workspace: workspace ? expandHome(workspace) : undefined,
143
163
  unit, dshProfile,
@@ -147,8 +167,13 @@ async function configure({ input, output, environment, execute, probeServicePnpm
147
167
  print(` 宿主 ${selected.map(agent => names[agent]).join('、')}`);
148
168
  print(` 配置来源 ${source === false ? '仅配置共享规则与 skills' : source ?? '默认 Kitto 配置'}`);
149
169
  print(' 共享范围 全局' + (plan.workspace ? `,以及工作区 ${plan.workspace}` : ''));
150
- if (selected.includes('dsh')) print(` DSH ${unit ?? '当前账号'},配置档 ${dshProfile}`);
170
+ if (selected.includes('dsh')) {
171
+ print(` DSH ${unit ?? '当前账号'},配置档 ${dshProfile}${isDesktopProfile(dshProfile) ? '(由 App 管理,仅全局规则/skills)' : ''}`);
172
+ }
151
173
  print(` 补装缺少的宿主和必需工具 ${installAgents ? '是' : '否'}`);
174
+ if (selected.includes('dsh') && isDesktopProfile(dshProfile)) {
175
+ print(' DSH Desktop 不检查、也不补装本机 dsh CLI(由 App 管理)。');
176
+ }
152
177
  if (serviceInstallAgents) print(` 为 ${unit} 的账号补装 pnpm 是`);
153
178
  if (source !== false) print(` 安装配置声明的辅助依赖 ${deps ? '是' : '否'}`);
154
179