llm-orchestrator 1.5.0 → 1.6.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 (63) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +231 -44
  3. package/SKILL.md +22 -2
  4. package/adapters/agents.mjs +8 -5
  5. package/adapters/codex/index.mjs +0 -2
  6. package/adapters/commands.mjs +13 -1
  7. package/adapters/hooks.mjs +18 -6
  8. package/agents/advisor.md +53 -0
  9. package/agents/orchestrator.md +1 -1
  10. package/bin/budget.mjs +94 -0
  11. package/bin/cli-options.mjs +31 -10
  12. package/bin/discover-models.mjs +428 -13
  13. package/bin/doctor.mjs +48 -22
  14. package/bin/gate.mjs +1 -1
  15. package/bin/install.mjs +15 -8
  16. package/bin/llm-orchestrator.mjs +14 -3
  17. package/bin/model-thinking-report.mjs +1 -0
  18. package/bin/route.mjs +57 -18
  19. package/bin/strategy.mjs +234 -0
  20. package/bin/uninstall.mjs +3 -1
  21. package/commands/task.md +13 -1
  22. package/hooks/hooks.json +11 -0
  23. package/lib/adapter-renderer.mjs +131 -10
  24. package/lib/budget.mjs +269 -0
  25. package/lib/dispatch-contract.mjs +87 -24
  26. package/lib/file-lock.mjs +121 -0
  27. package/lib/first-run.mjs +11 -9
  28. package/lib/flow-gate.mjs +377 -71
  29. package/lib/installation.mjs +313 -75
  30. package/lib/learning.mjs +233 -0
  31. package/lib/project-root.mjs +52 -0
  32. package/lib/router.mjs +473 -65
  33. package/lib/strategy-store.mjs +481 -0
  34. package/models/example-model-inventory.json +21 -10
  35. package/models/model-thinking-data.json +134 -2
  36. package/models/model-thinking-matrix.md +32 -0
  37. package/models/top-models.json +794 -44
  38. package/package.json +1 -1
  39. package/policies/capabilities.md +37 -0
  40. package/policies/dispatch.md +6 -1
  41. package/policies/learning.md +336 -0
  42. package/policies/routing.md +240 -63
  43. package/protocol.md +21 -0
  44. package/registries/agent-roles.json +35 -1
  45. package/registries/capabilities.json +1 -0
  46. package/registries/learning.json +219 -0
  47. package/registries/preferred-tools.json +64 -0
  48. package/registries/routing-matrix.json +61 -37
  49. package/registries/task-mappings.json +42 -0
  50. package/schemas/flow-ledger.schema.json +8 -2
  51. package/schemas/installation-manifest.schema.json +56 -5
  52. package/schemas/learning.schema.json +139 -0
  53. package/schemas/routing-matrix.schema.json +23 -3
  54. package/schemas/top-models.schema.json +32 -6
  55. package/workflows/bug-fix.md +8 -0
  56. package/workflows/config.md +8 -0
  57. package/workflows/deploy.md +8 -0
  58. package/workflows/feature.md +8 -0
  59. package/workflows/incident.md +8 -0
  60. package/workflows/investigation.md +8 -0
  61. package/workflows/refactor.md +8 -0
  62. package/workflows/research.md +8 -0
  63. package/workflows/review.md +8 -0
@@ -5,7 +5,7 @@ import {createHash, randomUUID} from 'node:crypto';
5
5
  import {access, lstat, mkdir, open, readdir, readFile, realpath, rename, rmdir, unlink} from 'node:fs/promises';
6
6
  import {basename, dirname, isAbsolute, join, relative, resolve, sep} from 'node:path';
7
7
 
8
- import {renderAdapter, FLOW_HOOK_TARGETS} from './adapter-renderer.mjs';
8
+ import {renderAdapter, renderGlobalAdapter, FLOW_HOOK_TARGETS, globalTargets} from './adapter-renderer.mjs';
9
9
  import {extractFlowGroups, removeFlowHooks} from '../adapters/hooks.mjs';
10
10
 
11
11
  const MANIFEST_VERSION = 1;
@@ -103,6 +103,38 @@ async function readTextIfFile(path) {
103
103
  return readFile(path, 'utf8');
104
104
  }
105
105
 
106
+ /**
107
+ * Where a write to `relativePath` under `root` really lands. A symbolic link on the
108
+ * way (a dotfile manager's `~/.claude`, or a linked `CLAUDE.md`) is followed when it
109
+ * resolves to a regular file or directory that is still inside `root`; the write then
110
+ * goes to that target and the link itself is never replaced. Anything else is refused
111
+ * with the reason. Returns {path} or {refused}.
112
+ */
113
+ async function resolveThrough(root, relativePath) {
114
+ targetPath(root, relativePath);
115
+ const pieces = relativePath.split(/[\\/]+/).filter(Boolean);
116
+ let current = root;
117
+ for (let index = 0; index < pieces.length; index += 1) {
118
+ current = join(current, pieces[index]);
119
+ const stat = await lstatOrNull(current);
120
+ if (!stat) return {path: join(current, ...pieces.slice(index + 1))};
121
+ if (!stat.isSymbolicLink()) continue;
122
+ const shown = pieces.slice(0, index + 1).join('/');
123
+ let real;
124
+ try {
125
+ real = await realpath(current);
126
+ } catch {
127
+ return {refused: `${shown} is a symbolic link whose target does not exist`};
128
+ }
129
+ if (!inside(root, real)) return {refused: `${shown} is a symbolic link that resolves outside ${root} (to ${real}); only links that stay inside it are followed`};
130
+ const target = await lstat(real);
131
+ const last = index === pieces.length - 1;
132
+ if (last ? !target.isFile() : !target.isDirectory()) return {refused: `${shown} is a symbolic link to something that is not a regular ${last ? 'file' : 'directory'}`};
133
+ current = real;
134
+ }
135
+ return {path: current};
136
+ }
137
+
106
138
  async function listRuntimeFiles(root, current = root, output = []) {
107
139
  await assertSafeTarget(current, root);
108
140
  for (const entry of await readdir(current, {withFileTypes: true})) {
@@ -121,12 +153,118 @@ function projectId(project) {
121
153
  return sha256(`portable-orchestrator:${project}`);
122
154
  }
123
155
 
124
- export function manifestPathFor({project, stateRoot, skillsRoot}) {
156
+ /**
157
+ * A global install (`global: true`) is the same machinery rooted at the user's home
158
+ * instead of a project: `project` is then the home directory, every recorded path is
159
+ * relative to it, and the manifest lives under `global/` so it can never be mistaken
160
+ * for — or merged with — a project install that happens to target the same directory.
161
+ *
162
+ * A global manifest is keyed on the home directory alone. The default skills root
163
+ * depends on the harness list, so keying on it gave every harness list its own
164
+ * manifest: a second install could not see what the first one owned. The skills root
165
+ * is recorded inside the manifest instead (`skills_root`).
166
+ */
167
+ export function manifestPathFor({project, stateRoot, skillsRoot, global = false}) {
125
168
  const safeProject = safeRoot(project, 'project');
169
+ if (global) return join(safeRoot(stateRoot, 'stateRoot'), 'global', projectId(safeProject), 'installation-manifest.json');
126
170
  const skillNamespace = skillsRoot ? safeRoot(skillsRoot, 'skillsRoot') : 'unspecified-skills-root';
127
171
  return join(safeRoot(stateRoot, 'stateRoot'), 'projects', projectId(safeProject), sha256(skillNamespace), 'installation-manifest.json');
128
172
  }
129
173
 
174
+ /** The directory an install is rooted at: the project, or the home directory for a global one. */
175
+ function installRoot(input) {
176
+ return input.global ? canonicalRoot(input.home, 'home') : canonicalRoot(input.project, 'project');
177
+ }
178
+
179
+ const PLUGIN_KEY = /^llm-orchestrator@.+/;
180
+
181
+ /** This package's `enabledPlugins` verdict in one Claude Code settings file: true, false, or undefined when it says nothing. */
182
+ async function pluginSetting(path) {
183
+ let settings;
184
+ try {
185
+ settings = JSON.parse(await readFile(path, 'utf8'));
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ const entries = settings?.enabledPlugins;
190
+ if (!entries || typeof entries !== 'object' || Array.isArray(entries)) return undefined;
191
+ const values = Object.entries(entries).filter(([name]) => PLUGIN_KEY.test(name)).map(([, value]) => value === true);
192
+ return values.length === 0 ? undefined : values.some(Boolean);
193
+ }
194
+
195
+ /**
196
+ * Whether the llm-orchestrator Claude Code plugin is enabled: an `enabledPlugins`
197
+ * entry for this package set to true in the user's `~/.claude/settings.json`. Claude
198
+ * Code writes that entry when a plugin is installed at user scope; being listed in
199
+ * `installed_plugins.json` proves nothing, since that file also lists plugins
200
+ * installed for one other project. The plugin ships the flow hooks itself.
201
+ * With `project`, that project's own settings (`.claude/settings.json`, then
202
+ * `.claude/settings.local.json`) override the user's, the way Claude Code layers them.
203
+ */
204
+ export async function claudePluginEnabled(home, {project = null} = {}) {
205
+ const user = await pluginSetting(join(home, '.claude', 'settings.json'));
206
+ if (!project) return user === true;
207
+ const shared = await pluginSetting(join(project, '.claude', 'settings.json'));
208
+ const local = await pluginSetting(join(project, '.claude', 'settings.local.json'));
209
+ return (local ?? shared ?? user) === true;
210
+ }
211
+
212
+ /**
213
+ * The user-scope targets for this home and environment (see `globalTargets`). Both
214
+ * are canonicalised first: on macOS a temp or home path is often a link, and the
215
+ * targets are paths relative to the canonical home.
216
+ */
217
+ export async function resolveGlobalTargets({home, env = {}}) {
218
+ const canonicalHome = await canonicalRoot(home, 'home');
219
+ const canonicalEnv = {};
220
+ for (const name of ['CODEX_HOME', 'XDG_CONFIG_HOME']) {
221
+ if (env?.[name] && isAbsolute(env[name]) && !env[name].split(/[\\/]+/).includes('..')) canonicalEnv[name] = await canonicalRoot(env[name], name);
222
+ }
223
+ return globalTargets({home: canonicalHome, env: canonicalEnv});
224
+ }
225
+
226
+ /**
227
+ * A skills root whose `orchestrate-core` is a symbolic link. `install --link-claude`
228
+ * creates exactly that in `~/.claude/skills`, pointing at the runtime in a shared
229
+ * root; a later install into `~/.claude/skills` must use that runtime, not refuse the
230
+ * link. The link is ours when the directory it points into has a runtime manifest.
231
+ */
232
+ async function effectiveSkillsRoot(skillsRoot, stateRoot, {strict = true} = {}) {
233
+ const link = join(skillsRoot, 'orchestrate-core');
234
+ if (!(await lstatOrNull(link))?.isSymbolicLink()) return skillsRoot;
235
+ let real = null;
236
+ try {
237
+ real = await realpath(link);
238
+ } catch { /* dangling */ }
239
+ if (real && basename(real) === 'orchestrate-core' && await readRuntimeManifest(runtimeManifestPathFor({stateRoot, skillsRoot: dirname(real)}))) return dirname(real);
240
+ if (!strict) return skillsRoot;
241
+ throw new Error(`Refusing symlink target: ${link} ${real ? `resolves to ${real}, which is not a runtime this package installed` : 'is a symbolic link whose target does not exist'}; remove the link or pass another --skills-root`);
242
+ }
243
+
244
+ /**
245
+ * The roots every entry point works from, resolved once and before any lock is taken.
246
+ * A global install whose skills root was only defaulted reuses the root its manifest
247
+ * recorded, so a different harness list does not move the runtime.
248
+ */
249
+ async function effectiveRoots(input, {strict = true} = {}) {
250
+ const global = Boolean(input.global);
251
+ const project = await installRoot(input);
252
+ const stateRoot = await canonicalRoot(input.stateRoot, 'stateRoot');
253
+ let requested = input.skillsRoot;
254
+ if (global) {
255
+ const recorded = (await readManifest(manifestPathFor({project, stateRoot, global})))?.skills_root;
256
+ if (recorded && (input.skillsRootDefaulted || !requested)) requested = recorded;
257
+ }
258
+ const skillsRoot = await effectiveSkillsRoot(await canonicalRoot(requested, 'skillsRoot'), stateRoot, {strict});
259
+ return {global, project, stateRoot, skillsRoot, manifestPath: manifestPathFor({project, stateRoot, skillsRoot, global})};
260
+ }
261
+
262
+ /** `~/…` when the path is inside the home directory: how the instruction span spells the skill. */
263
+ function homeRelative(home, path) {
264
+ const rel = relative(home, path);
265
+ return rel && !rel.startsWith('..') && !isAbsolute(rel) ? `~/${rel.split(sep).join('/')}` : path;
266
+ }
267
+
130
268
  export function runtimeManifestPathFor({stateRoot, skillsRoot}) {
131
269
  const skillNamespace = safeRoot(skillsRoot, 'skillsRoot');
132
270
  return join(safeRoot(stateRoot, 'stateRoot'), 'runtime', sha256(skillNamespace), 'runtime-manifest.json');
@@ -185,21 +323,35 @@ function normalizeHarnesses(harnesses) {
185
323
 
186
324
  const NATIVE_COMMAND_NAMES = ['orchestrate', 'task', 'task-plan', 'task-status', 'task-cancel', 'task-verify', 'incident-start', 'incident-evidence', 'incident-fix', 'incident-verify', 'incident-close'];
187
325
 
326
+ /**
327
+ * Read the files a plan may touch. `resolved` maps each path to where a write really
328
+ * lands (links followed, see `resolveThrough`); `refused` maps a path that cannot be
329
+ * used to the reason.
330
+ */
188
331
  async function scanExistingFiles(root, paths) {
189
332
  const values = {};
190
- const conflicts = [];
333
+ const refused = {};
334
+ const resolved = {};
191
335
  for (const path of paths) {
192
- const absolute = targetPath(root, path);
193
- try {
194
- await assertSafeTarget(absolute, root);
195
- const content = await readTextIfFile(absolute);
196
- if (content !== undefined) values[path] = content;
197
- } catch (error) {
198
- if (/Refusing symlink target/.test(error.message)) conflicts.push(path);
199
- else throw error;
336
+ const target = await resolveThrough(root, path);
337
+ if (target.refused) {
338
+ refused[path] = target.refused;
339
+ continue;
200
340
  }
341
+ resolved[path] = target.path;
342
+ const stat = await lstatOrNull(target.path);
343
+ if (stat && !stat.isFile()) refused[path] = `${path} exists but is not a regular file`;
344
+ else if (stat) values[path] = await readFile(target.path, 'utf8');
345
+ }
346
+ // Two targets linked to one file would be planned from the same text and written in
347
+ // turn, the second write dropping the first; neither is touched.
348
+ const byTarget = new Map();
349
+ for (const [path, real] of Object.entries(resolved)) byTarget.set(real, [...(byTarget.get(real) ?? []), path]);
350
+ for (const paths of byTarget.values()) {
351
+ if (paths.length < 2) continue;
352
+ for (const path of paths) refused[path] = `${path} is the same file as ${paths.filter((other) => other !== path).join(' and ')} (linked together); this installer writes each of them separately, so link neither or install them apart`;
201
353
  }
202
- return {values, conflicts};
354
+ return {values, refused, resolved};
203
355
  }
204
356
 
205
357
  /** Hash of the flow-hook groups this package owns inside a hooks JSON file. */
@@ -208,6 +360,17 @@ function flowGroupsHash(groups) {
208
360
  return hashText(JSON.stringify(Object.keys(groups).sort().map((event) => [event, groups[event]])));
209
361
  }
210
362
 
363
+ async function readGlobalExisting(home, harnesses, targets) {
364
+ const paths = new Set();
365
+ for (const harness of harnesses) {
366
+ const target = targets[harness];
367
+ if (!target || target.outside) continue;
368
+ paths.add(target.instructions);
369
+ if (target.hooks) paths.add(target.hooks.path);
370
+ }
371
+ return scanExistingFiles(home, paths);
372
+ }
373
+
211
374
  async function readGeneratedExisting(project, harnesses, {withAgents = false} = {}) {
212
375
  const paths = new Set(['AGENTS.md', '.agents/skills/orchestrate/SKILL.md']);
213
376
  for (const harness of harnesses) if (FLOW_HOOK_TARGETS[harness]) paths.add(FLOW_HOOK_TARGETS[harness].path);
@@ -239,26 +402,35 @@ function appendConflict(conflicts, value) {
239
402
 
240
403
  /** Return a conflict-aware, non-mutating installation plan. */
241
404
  export async function planInstallation(input) {
242
- const project = await canonicalRoot(input.project, 'project');
405
+ const {global, project, stateRoot, skillsRoot, manifestPath} = await effectiveRoots(input);
243
406
  const packageRoot = await canonicalRoot(input.packageRoot, 'packageRoot');
244
- const stateRoot = await canonicalRoot(input.stateRoot, 'stateRoot');
245
- const skillsRoot = await canonicalRoot(input.skillsRoot, 'skillsRoot');
246
407
  const requestedHarnesses = normalizeHarnesses(input.harnesses);
247
408
  await Promise.all([assertSafeTarget(project), assertSafeTarget(packageRoot), assertSafeTarget(stateRoot), assertSafeTarget(skillsRoot)]);
248
- const manifestPath = manifestPathFor({project, stateRoot, skillsRoot});
249
409
  const runtimeManifestPath = runtimeManifestPathFor({stateRoot, skillsRoot});
250
410
  await assertSafeTarget(manifestPath, stateRoot);
251
411
  const manifest = await readManifest(manifestPath);
252
412
  const runtimeManifest = await readRuntimeManifest(runtimeManifestPath);
253
413
  const harnesses = [...new Set([...(manifest?.harnesses ?? []), ...requestedHarnesses])];
254
- const withAgents = Boolean(input.withAgents);
255
- const codexPromptsRoot = input.codexPromptsRoot && harnesses.includes('codex')
414
+ // Agents, native commands and Codex prompts are per-project footprints; a global
415
+ // install carries the instruction and the hooks only.
416
+ const withAgents = !global && Boolean(input.withAgents);
417
+ const advisorModel = withAgents && input.advisorModel ? String(input.advisorModel) : null;
418
+ const codexPromptsRoot = !global && input.codexPromptsRoot && harnesses.includes('codex')
256
419
  ? await canonicalRoot(input.codexPromptsRoot, 'codexPromptsRoot')
257
420
  : null;
258
421
  if (codexPromptsRoot) await assertSafeTarget(codexPromptsRoot);
259
422
  const prior = previousByLocation(manifest);
260
423
  const runtimePrior = new Map([...(runtimeManifest?.files ?? []), ...(manifest?.files ?? []).filter(({scope}) => scope === 'skills')].map((file) => [file.path, file]));
424
+ // Conflicts that leave nothing to apply (the shared runtime), each with its reason.
261
425
  const conflicts = [];
426
+ const reasons = [];
427
+ const fatal = (path, reason) => {
428
+ if (conflicts.includes(path)) return;
429
+ conflicts.push(path);
430
+ reasons.push({harness: null, path, reason});
431
+ };
432
+ const RUNTIME_FOREIGN = 'is in the runtime directory but is not part of this package and was not installed by it';
433
+ const RUNTIME_EDITED = 'differs from what this installer wrote there (edited, or installed by something else)';
262
434
  let files = [];
263
435
  const spans = [];
264
436
 
@@ -268,7 +440,7 @@ export async function planInstallation(input) {
268
440
  const sourcePaths = new Set(sourceFiles.map(({path}) => path));
269
441
  const existingRuntime = await walkExistingFiles(runtimeRoot);
270
442
  for (const unexpected of existingRuntime.filter((path) => !sourcePaths.has(path) && !runtimePrior.has(path))) {
271
- appendConflict(conflicts, `skills/orchestrate-core/${unexpected}`);
443
+ fatal(`skills/orchestrate-core/${unexpected}`, RUNTIME_FOREIGN);
272
444
  }
273
445
  for (const source of sourceFiles) {
274
446
  const target = targetPath(runtimeRoot, source.path);
@@ -277,8 +449,8 @@ export async function planInstallation(input) {
277
449
  const old = runtimePrior.get(source.path);
278
450
  const hash = hashText(source.content);
279
451
  if (existing === undefined) files.push({scope: 'skills', path: source.path, absolutePath: target, content: source.content, hash, kind: 'runtime', action: 'create'});
280
- else if (old && hashText(existing) !== old.hash) appendConflict(conflicts, `skills/orchestrate-core/${source.path}`);
281
- else if (!old && existing !== source.content) appendConflict(conflicts, `skills/orchestrate-core/${source.path}`);
452
+ else if (old && hashText(existing) !== old.hash) fatal(`skills/orchestrate-core/${source.path}`, RUNTIME_EDITED);
453
+ else if (!old && existing !== source.content) fatal(`skills/orchestrate-core/${source.path}`, RUNTIME_EDITED);
282
454
  else if (existing !== source.content) files.push({scope: 'skills', path: source.path, absolutePath: target, content: source.content, hash, kind: 'runtime', action: 'update'});
283
455
  }
284
456
 
@@ -288,12 +460,18 @@ export async function planInstallation(input) {
288
460
  await assertSafeTarget(target, runtimeRoot);
289
461
  const existing = await readTextIfFile(target);
290
462
  if (existing === undefined) continue;
291
- if (hashText(existing) !== old.hash) appendConflict(conflicts, `skills/orchestrate-core/${path}`);
463
+ if (hashText(existing) !== old.hash) fatal(`skills/orchestrate-core/${path}`, RUNTIME_EDITED);
292
464
  else files.push({scope: 'skills', path, absolutePath: target, hash: old.hash, kind: 'runtime', action: 'remove'});
293
465
  }
294
466
 
295
- const generated = await readGeneratedExisting(project, harnesses, {withAgents});
296
- const promptsExisting = codexPromptsRoot ? await readCodexPromptsExisting(codexPromptsRoot) : {values: {}, conflicts: []};
467
+ const targets = global ? await resolveGlobalTargets({home: project, env: input.env ?? {}}) : null;
468
+ const generated = global ? await readGlobalExisting(project, harnesses, targets) : await readGeneratedExisting(project, harnesses, {withAgents});
469
+ // Only an explicitly given home is ever read: a library caller that names none is not
470
+ // answered from the real one.
471
+ const pluginEnabled = harnesses.includes('claude') && Boolean(input.home)
472
+ && await claudePluginEnabled(global ? project : await canonicalRoot(input.home, 'home'), global ? {} : {project});
473
+ const skipped = [];
474
+ const promptsExisting = codexPromptsRoot ? await readCodexPromptsExisting(codexPromptsRoot) : {values: {}, refused: {}, resolved: {}};
297
475
  const existingGenerated = {...generated.values, ...promptsExisting.values};
298
476
  const ownedGeneratedPaths = (manifest?.files ?? [])
299
477
  .filter((file) => file.scope === 'project' && existingGenerated[file.path] !== undefined && hashText(existingGenerated[file.path]) === file.hash)
@@ -304,8 +482,6 @@ export async function planInstallation(input) {
304
482
  const end = content?.indexOf(span.end) ?? -1;
305
483
  return start >= 0 && end >= start && hashText(content.slice(start, end + span.end.length)) === span.hash;
306
484
  }).map(({path}) => path);
307
- for (const conflict of generated.conflicts) appendConflict(conflicts, conflict);
308
- for (const conflict of promptsExisting.conflicts) appendConflict(conflicts, conflict);
309
485
  const flowHooksEnabled = input.flowHooks ?? manifest?.flow_hooks ?? true;
310
486
  const priorJsonEntries = manifest?.json_entries ?? [];
311
487
  const flowHooks = {
@@ -315,26 +491,51 @@ export async function planInstallation(input) {
315
491
  ownedJsonHashes: Object.fromEntries(priorJsonEntries.map(({path, hash}) => [path, hash])),
316
492
  };
317
493
  const jsonEntries = [];
494
+ // Hook groups this run took back out; every other recorded entry stays recorded,
495
+ // whether its harness was skipped this time or its location is no longer a target
496
+ // (CODEX_HOME changed), so uninstall still finds it.
497
+ const withdrawnPaths = new Set();
498
+ // A harness in conflict is left out whole; the others are applied.
499
+ const blocked = new Set();
500
+ // Recorded on a global install only, where no two harnesses share a file: it is what
501
+ // lets `uninstall --global --harness X` find X's entries in any environment.
502
+ const owner = (harness) => (global ? {harness} : {});
318
503
  for (const harness of harnesses) {
319
504
  const includeCodexPrompts = harness === 'codex' && Boolean(codexPromptsRoot);
320
- const adapter = renderAdapter({harness, capabilities: [], installMode: 'external', existingFiles: existingGenerated, ownedPaths: ownedGeneratedPaths, ownedSpanPaths, withAgents, codexPrompts: includeCodexPrompts, flowHooks});
321
- for (const conflict of adapter.conflicts) appendConflict(conflicts, conflict);
505
+ const adapter = global
506
+ ? renderGlobalAdapter({harness, targets, existingFiles: existingGenerated, ownedPaths: ownedGeneratedPaths, ownedSpanPaths, flowHooks, skillPath: homeRelative(project, join(runtimeRoot, 'SKILL.md')), claudePluginEnabled: pluginEnabled})
507
+ // An explicit --flow-hooks on this run forces the project copy even with the plugin on.
508
+ : renderAdapter({harness, capabilities: [], installMode: 'external', existingFiles: existingGenerated, ownedPaths: ownedGeneratedPaths, ownedSpanPaths, withAgents, advisorModel, codexPrompts: includeCodexPrompts, flowHooks, claudePluginEnabled: pluginEnabled && input.flowHooks !== true});
509
+ const refusedIn = (file) => (file.kind === 'codex-prompt' ? promptsExisting : generated).refused[file.path];
510
+ const harnessReasons = new Map(adapter.conflicts.map((path) => [path, adapter.conflictReasons?.[path] ?? 'conflicts with a file this installer does not own']));
511
+ for (const file of adapter.files) if (refusedIn(file)) harnessReasons.set(file.path, refusedIn(file));
512
+ if (harnessReasons.size > 0) {
513
+ blocked.add(harness);
514
+ for (const [path, reason] of harnessReasons) {
515
+ appendConflict(conflicts, path);
516
+ reasons.push({harness, path, reason});
517
+ }
518
+ skipped.push({harness, target: 'harness', reason: `not applied — ${[...harnessReasons].map(([path, reason]) => `${path}: ${reason}`).join('; ')}`});
519
+ continue;
520
+ }
521
+ skipped.push(...(adapter.skipped ?? []));
322
522
  for (const file of adapter.files) {
323
523
  const scope = file.kind === 'codex-prompt' ? 'prompts' : 'project';
324
524
  const root = scope === 'prompts' ? codexPromptsRoot : project;
325
- const absolutePath = targetPath(root, file.path);
525
+ const absolutePath = (scope === 'prompts' ? promptsExisting : generated).resolved[file.path] ?? targetPath(root, file.path);
326
526
  const old = prior.get(locationKey(scope, file.path));
327
527
  if (file.kind === 'json-hooks') {
328
528
  // The file belongs to the user; only our marked hook groups are tracked, in json_entries.
329
529
  const previous = priorJsonEntries.find((entry) => entry.path === file.path);
330
530
  const createdFile = previous?.created_file ?? existingGenerated[file.path] === undefined;
331
531
  if (file.action === 'withdraw') {
532
+ withdrawnPaths.add(file.path);
332
533
  if (file.empty && createdFile) files.push({scope: 'project', path: file.path, absolutePath, hash: hashText(existingGenerated[file.path]), kind: 'json-hooks', action: 'remove'});
333
534
  else files.push({scope: 'project', path: file.path, absolutePath, content: file.content, hash: hashText(file.content), kind: 'json-hooks', action: 'update'});
334
535
  continue;
335
536
  }
336
537
  if (file.action !== 'reuse') files.push({scope: 'project', path: file.path, absolutePath, content: file.content, hash: hashText(file.content), kind: 'json-hooks', action: file.action});
337
- jsonEntries.push({scope: 'project', path: file.path, hash: file.entryHash, created_file: createdFile});
538
+ jsonEntries.push({scope: 'project', path: file.path, hash: file.entryHash, created_file: createdFile, ...owner(harness)});
338
539
  continue;
339
540
  }
340
541
  if (file.kind === 'flow-plugin' && file.action === 'remove') {
@@ -346,10 +547,10 @@ export async function planInstallation(input) {
346
547
  if (file.action !== 'reuse' || (manifest?.spans ?? []).some((span) => span.scope === 'project' && span.path === file.path && span.hash === hashText(file.span))) {
347
548
  const previous = (manifest?.spans ?? []).find((span) => span.scope === 'project' && span.path === file.path);
348
549
  const preserveSeparators = Boolean(previous) && (file.action === 'update' || file.action === 'reuse');
349
- spans.push({scope: 'project', path: file.path, span: file.span, hash: hashText(file.span), begin: file.begin, end: file.end, before: preserveSeparators ? previous?.before ?? '' : file.before, after: preserveSeparators ? previous?.after ?? '' : file.after, created_file: preserveSeparators ? previous?.created_file ?? false : existingGenerated[file.path] === undefined});
550
+ spans.push({scope: 'project', path: file.path, span: file.span, hash: hashText(file.span), begin: file.begin, end: file.end, before: preserveSeparators ? previous?.before ?? '' : file.before, after: preserveSeparators ? previous?.after ?? '' : file.after, created_file: preserveSeparators ? previous?.created_file ?? false : existingGenerated[file.path] === undefined, ...owner(harness)});
350
551
  }
351
552
  } else if (file.action === 'create' || file.action === 'update') {
352
- files.push({scope, path: file.path, absolutePath, content: file.content, hash: hashText(file.content), kind: file.kind, action: file.action});
553
+ files.push({scope, path: file.path, absolutePath, content: file.content, hash: hashText(file.content), kind: file.kind, action: file.action, ...owner(harness)});
353
554
  } else if (file.action === 'reuse' && old) {
354
555
  // Retain ownership from an earlier successful install without rewriting it.
355
556
  }
@@ -361,9 +562,13 @@ export async function planInstallation(input) {
361
562
  const key = locationKey(file.scope, file.path);
362
563
  const existing = uniqueFiles.get(key);
363
564
  if (!existing) uniqueFiles.set(key, file);
364
- else if (existing.action !== file.action || existing.content !== file.content || existing.kind !== file.kind) appendConflict(conflicts, file.scope === 'skills' ? `skills/orchestrate-core/${file.path}` : file.scope === 'prompts' ? `prompts/${file.path}` : file.path);
565
+ else if (existing.action !== file.action || existing.content !== file.content || existing.kind !== file.kind) fatal(file.scope === 'skills' ? `skills/orchestrate-core/${file.path}` : file.scope === 'prompts' ? `prompts/${file.path}` : file.path, 'two harnesses in this install would write different content to it');
365
566
  }
366
567
  files = [...uniqueFiles.values()];
568
+ const appliedHarnesses = harnesses.filter((harness) => !blocked.has(harness));
569
+ // Nothing is written when the shared runtime is in conflict, or when every harness
570
+ // this run asked for was skipped.
571
+ const applicable = reasons.every(({harness}) => harness !== null) && requestedHarnesses.some((harness) => !blocked.has(harness));
367
572
  const changedKeys = new Set(files.filter(({action}) => action !== 'remove').map((file) => locationKey(file.scope, file.path)));
368
573
  const retainedFiles = (manifest?.files ?? []).filter((file) => file.scope !== 'skills' && !changedKeys.has(locationKey(file.scope, file.path)) && !files.some((candidate) => candidate.scope === file.scope && candidate.path === file.path && candidate.action === 'remove'));
369
574
  const nextFiles = [...retainedFiles, ...files.filter(({scope, action, kind}) => scope !== 'skills' && action !== 'remove' && kind !== 'managed-span' && kind !== 'json-hooks').map(({absolutePath, action, content, ...file}) => file)];
@@ -373,15 +578,16 @@ export async function planInstallation(input) {
373
578
  const nextManifest = {
374
579
  version: MANIFEST_VERSION,
375
580
  project_id: projectId(project),
376
- harnesses,
377
- skill_resolution: {skills_root_source: input.skillsRoot ? 'operator_provided' : 'default', native_discovery: 'unverified'},
581
+ ...(global ? {install_scope: 'global', skills_root: skillsRoot} : {}),
582
+ harnesses: [...new Set([...(manifest?.harnesses ?? []), ...requestedHarnesses.filter((harness) => !blocked.has(harness))])],
583
+ skill_resolution: {skills_root_source: input.skillsRoot && !input.skillsRootDefaulted ? 'operator_provided' : 'default', native_discovery: 'unverified'},
378
584
  files: nextFiles,
379
585
  spans: uniqueSpans,
380
586
  flow_hooks: flowHooksEnabled,
381
- json_entries: [...new Map(jsonEntries.map((entry) => [entry.path, entry])).values()],
587
+ json_entries: [...new Map([...priorJsonEntries.filter(({path}) => !withdrawnPaths.has(path)), ...jsonEntries].map((entry) => [entry.path, entry])).values()],
382
588
  };
383
- const changes = conflicts.length === 0 ? files.filter(({action}) => action !== 'reuse').map(({scope, path, action}) => ({scope, path, action})) : [];
384
- return {project, packageRoot, stateRoot, skillsRoot, codexPromptsRoot, withAgents, harnesses, runtimeRoot, manifestPath, manifest: nextManifest, runtimeManifestPath, runtimeManifest: nextRuntimeManifest, conflicts, files, changes, genericAgentsReferences: 1};
589
+ const changes = applicable ? files.filter(({action}) => action !== 'reuse').map(({scope, path, action}) => ({scope, path, action})) : [];
590
+ return {project, ...(global ? {global: true} : {}), skipped, packageRoot, stateRoot, skillsRoot, codexPromptsRoot, withAgents, harnesses, applied_harnesses: applicable ? appliedHarnesses : [], applicable, runtimeRoot, manifestPath, manifest: nextManifest, runtimeManifestPath, runtimeManifest: nextRuntimeManifest, conflicts, conflict_reasons: reasons, files, changes, genericAgentsReferences: global ? 0 : 1};
385
591
  }
386
592
 
387
593
  async function ensureSafeDirectory(path) {
@@ -434,15 +640,17 @@ async function restore(captures) {
434
640
  }
435
641
 
436
642
  export async function applyInstallation(input) {
437
- input = {...input, project: await canonicalRoot(input.project, 'project'), stateRoot: await canonicalRoot(input.stateRoot, 'stateRoot'), skillsRoot: await canonicalRoot(input.skillsRoot, 'skillsRoot')};
438
- const lockPath = manifestPathFor(input);
643
+ // Resolved before the locks: a reused or redirected skills root decides which locks they are.
644
+ const roots = await effectiveRoots(input);
645
+ input = {...input, project: roots.project, ...(input.global ? {home: roots.project} : {}), stateRoot: roots.stateRoot, skillsRoot: roots.skillsRoot};
646
+ const lockPath = roots.manifestPath;
439
647
  const runtimeLockPath = runtimeManifestPathFor(input);
440
648
  const runtimeLock = await acquireLock(runtimeLockPath);
441
649
  let lock;
442
650
  try {
443
651
  lock = await acquireLock(lockPath);
444
652
  const plan = await planInstallation(input);
445
- if (plan.conflicts.length > 0) return plan;
653
+ if (!plan.applicable) return plan;
446
654
  const mutable = plan.files.filter(({action}) => action !== 'remove');
447
655
  const captures = await Promise.all([...plan.files.map(({absolutePath}) => capture(absolutePath)), capture(plan.manifestPath), capture(plan.runtimeManifestPath)]);
448
656
  try {
@@ -484,11 +692,23 @@ async function promptsRootFor(input) {
484
692
  return input.codexPromptsRoot ? canonicalRoot(input.codexPromptsRoot, 'codexPromptsRoot') : null;
485
693
  }
486
694
 
695
+ /** Where an owned path really is (links followed like the install did), or null when it can no longer be used. */
696
+ async function ownedTarget(root, path) {
697
+ return (await resolveThrough(root, path)).path ?? null;
698
+ }
699
+
700
+ async function readOwned(root, path) {
701
+ const target = await ownedTarget(root, path);
702
+ const stat = target ? await lstatOrNull(target) : null;
703
+ // A path that turned into a refused link or a directory is the user's now: preserved.
704
+ if (!target || (stat && !stat.isFile())) return {target: null, current: undefined, unusable: true};
705
+ return {target, current: stat ? await readFile(target, 'utf8') : undefined};
706
+ }
707
+
487
708
  /** Whether the flow-hook groups recorded for a user JSON file are still exactly ours. */
488
709
  async function jsonEntryVerdict(project, entry) {
489
- const target = targetPath(project, entry.path);
490
- await assertSafeTarget(target, project);
491
- const current = await readTextIfFile(target);
710
+ const {target, current, unusable} = await readOwned(project, entry.path);
711
+ if (unusable) return {present: true, owned: false, target, current};
492
712
  if (current === undefined) return {present: false, owned: false, target, current};
493
713
  let groups;
494
714
  try {
@@ -500,46 +720,55 @@ async function jsonEntryVerdict(project, entry) {
500
720
  return {present: true, owned: flowGroupsHash(groups) === entry.hash, target, current};
501
721
  }
502
722
 
723
+ /**
724
+ * Which manifest entries an uninstall takes. A global uninstall that names only some
725
+ * of the installed harnesses takes theirs and leaves the rest installed; anything
726
+ * else — a project, no harness list, or a list covering every installed harness —
727
+ * takes everything the manifest records.
728
+ */
729
+ function uninstallSelection(input, manifest) {
730
+ const named = input.global && input.harnesses && input.harnesses.length > 0 ? new Set(normalizeHarnesses(input.harnesses)) : null;
731
+ const partial = named !== null && manifest.harnesses.some((harness) => !named.has(harness));
732
+ return {
733
+ selects: (entry) => !partial || named.has(entry.harness),
734
+ remainingHarnesses: partial ? manifest.harnesses.filter((harness) => !named.has(harness)) : manifest.harnesses,
735
+ };
736
+ }
737
+
503
738
  /** Return the exact project-owned removals an uninstall would attempt. */
504
739
  export async function planUninstall(input) {
505
- const project = await canonicalRoot(input.project, 'project');
506
- const stateRoot = await canonicalRoot(input.stateRoot, 'stateRoot');
507
- const skillsRoot = await canonicalRoot(input.skillsRoot, 'skillsRoot');
508
- const manifestPath = manifestPathFor({project, stateRoot, skillsRoot});
740
+ const {project, stateRoot, skillsRoot, manifestPath} = await effectiveRoots(input, {strict: false});
509
741
  const runtimeManifestPath = runtimeManifestPathFor({stateRoot, skillsRoot});
510
742
  const manifest = await readManifest(manifestPath);
511
743
  const runtimeManifest = await readRuntimeManifest(runtimeManifestPath);
512
744
  if (!manifest) return {conflicts: [], changes: [], preserved: [], retained_shared_runtime: (runtimeManifest?.files ?? []).map(({path}) => path), manifestPath};
745
+ const {selects} = uninstallSelection(input, manifest);
513
746
  const changes = [];
514
747
  const preserved = [];
515
- for (const span of manifest.spans) {
516
- const target = targetPath(project, span.path);
517
- await assertSafeTarget(target, project);
518
- const current = await readTextIfFile(target);
748
+ for (const span of manifest.spans.filter(selects)) {
749
+ const {current} = await readOwned(project, span.path);
519
750
  const start = current?.indexOf(span.begin) ?? -1;
520
751
  const end = current?.indexOf(span.end) ?? -1;
521
752
  const actual = start >= 0 && end >= start ? current.slice(start, end + span.end.length) : null;
522
753
  if (actual && hashText(actual) === span.hash) changes.push({scope: 'project', path: span.path, action: 'remove-span'});
523
754
  else preserved.push(span.path);
524
755
  }
525
- for (const entry of manifest.json_entries ?? []) {
756
+ for (const entry of (manifest.json_entries ?? []).filter(selects)) {
526
757
  const verdict = await jsonEntryVerdict(project, entry);
527
758
  if (verdict.owned) changes.push({scope: 'project', path: entry.path, action: 'remove-hooks'});
528
759
  else if (verdict.present) preserved.push(entry.path);
529
760
  }
530
761
  const promptsRoot = await promptsRootFor(input);
531
- for (const file of manifest.files) {
762
+ for (const file of manifest.files.filter(selects)) {
532
763
  if (file.scope === 'skills') continue;
533
764
  const root = file.scope === 'prompts' ? promptsRoot : project;
534
765
  if (!root) {
535
766
  preserved.push(`prompts/${file.path}`);
536
767
  continue;
537
768
  }
538
- const target = targetPath(root, file.path);
539
- await assertSafeTarget(target, root);
540
- const current = await readTextIfFile(target);
769
+ const {current, unusable} = await readOwned(root, file.path);
541
770
  if (current !== undefined && hashText(current) === file.hash) changes.push({scope: file.scope, path: file.path, action: 'remove'});
542
- else if (current !== undefined) preserved.push(file.path);
771
+ else if (current !== undefined || unusable) preserved.push(file.path);
543
772
  }
544
773
  return {
545
774
  conflicts: [],
@@ -551,14 +780,12 @@ export async function planUninstall(input) {
551
780
  }
552
781
 
553
782
  export async function uninstallInstallation(input) {
554
- const project = await canonicalRoot(input.project, 'project');
555
- const stateRoot = await canonicalRoot(input.stateRoot, 'stateRoot');
556
- const skillsRoot = await canonicalRoot(input.skillsRoot, 'skillsRoot');
557
- const manifestPath = manifestPathFor({project, stateRoot, skillsRoot});
783
+ const {project, skillsRoot, manifestPath} = await effectiveRoots(input, {strict: false});
558
784
  const lock = await acquireLock(manifestPath);
559
785
  try {
560
786
  const manifest = await readManifest(manifestPath);
561
787
  if (!manifest) return {conflicts: [], changes: [], preserved: [], manifestPath};
788
+ const {selects, remainingHarnesses} = uninstallSelection(input, manifest);
562
789
  const preserved = [];
563
790
  const remainingFiles = [];
564
791
  const remainingSpans = [];
@@ -568,15 +795,20 @@ export async function uninstallInstallation(input) {
568
795
  const promptsRoot = await promptsRootFor(input);
569
796
  const rootFor = (scope) => (scope === 'skills' ? targetPath(skillsRoot, 'orchestrate-core') : scope === 'prompts' ? promptsRoot : project);
570
797
  const remainingJsonEntries = [];
571
- for (const span of manifest.spans) captureTargets.push(targetPath(project, span.path));
572
- for (const entry of manifest.json_entries ?? []) captureTargets.push(targetPath(project, entry.path));
573
- for (const file of manifest.files) if (rootFor(file.scope)) captureTargets.push(targetPath(rootFor(file.scope), file.path));
574
- const captures = await Promise.all([...new Set(captureTargets)].map((path) => capture(path)));
798
+ // Captured where they really are, so a failed uninstall is restored through the same links.
799
+ const real = async (root, path) => (root ? await ownedTarget(root, path) : null);
800
+ for (const span of manifest.spans) captureTargets.push(await real(project, span.path));
801
+ for (const entry of manifest.json_entries ?? []) captureTargets.push(await real(project, entry.path));
802
+ for (const file of manifest.files) captureTargets.push(await real(rootFor(file.scope), file.path));
803
+ const captures = [];
804
+ for (const path of new Set(captureTargets.filter(Boolean))) if (!(await lstatOrNull(path))?.isDirectory()) captures.push(await capture(path));
575
805
  try {
576
806
  for (const span of manifest.spans) {
577
- const target = targetPath(project, span.path);
578
- await assertSafeTarget(target, project);
579
- const current = await readTextIfFile(target);
807
+ if (!selects(span)) {
808
+ remainingSpans.push(span);
809
+ continue;
810
+ }
811
+ const {target, current} = await readOwned(project, span.path);
580
812
  const start = current?.indexOf(span.begin) ?? -1;
581
813
  const end = current?.indexOf(span.end) ?? -1;
582
814
  const actual = start >= 0 && end >= start ? current.slice(start, end + span.end.length) : null;
@@ -595,6 +827,10 @@ export async function uninstallInstallation(input) {
595
827
  changes.push({scope: 'project', path: span.path, action: 'remove-span'});
596
828
  }
597
829
  for (const entry of manifest.json_entries ?? []) {
830
+ if (!selects(entry)) {
831
+ remainingJsonEntries.push(entry);
832
+ continue;
833
+ }
598
834
  const verdict = await jsonEntryVerdict(project, entry);
599
835
  if (!verdict.present) continue;
600
836
  if (!verdict.owned) {
@@ -612,17 +848,19 @@ export async function uninstallInstallation(input) {
612
848
  retainedSharedRuntime.push(file.path);
613
849
  continue;
614
850
  }
851
+ if (!selects(file)) {
852
+ remainingFiles.push(file);
853
+ continue;
854
+ }
615
855
  const root = rootFor(file.scope);
616
856
  if (!root) {
617
857
  preserved.push(`prompts/${file.path}`);
618
858
  remainingFiles.push(file);
619
859
  continue;
620
860
  }
621
- const target = targetPath(root, file.path);
622
- await assertSafeTarget(target, root);
623
- const current = await readTextIfFile(target);
624
- if (current === undefined) continue;
625
- if (hashText(current) !== file.hash) {
861
+ const {target, current, unusable} = await readOwned(root, file.path);
862
+ if (current === undefined && !unusable) continue;
863
+ if (unusable || hashText(current) !== file.hash) {
626
864
  preserved.push(file.scope === 'project' ? file.path : `skills/orchestrate-core/${file.path}`);
627
865
  remainingFiles.push(file);
628
866
  continue;
@@ -631,7 +869,7 @@ export async function uninstallInstallation(input) {
631
869
  await removeIfEmpty(target, root);
632
870
  changes.push({scope: file.scope, path: file.path, action: 'remove'});
633
871
  }
634
- const next = {...manifest, files: remainingFiles, spans: remainingSpans, json_entries: remainingJsonEntries};
872
+ const next = {...manifest, harnesses: remainingHarnesses, files: remainingFiles, spans: remainingSpans, json_entries: remainingJsonEntries};
635
873
  if (remainingFiles.length === 0 && remainingSpans.length === 0 && remainingJsonEntries.length === 0) await unlink(manifestPath);
636
874
  else await atomicWrite(manifestPath, `${JSON.stringify(next, null, 2)}\n`);
637
875
  return {conflicts: [], changes, preserved: [...new Set(preserved)], retained_shared_runtime: retainedSharedRuntime, manifestPath};