@sakanano-moe/agenthelm 6.13.1 → 6.14.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 (117) hide show
  1. package/package.json +1 -1
  2. package/runtime/index.json +6 -6
  3. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  4. package/runtime/plugins/agent-pack/plugin.json +1 -1
  5. package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
  6. package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
  7. package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
  8. package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
  9. package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
  10. package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
  11. package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
  12. package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
  13. package/runtime/plugins/agent-pack/references/nudge.md +10 -2
  14. package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
  15. package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
  16. package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
  17. package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
  18. package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
  19. package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
  20. package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
  21. package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
  22. package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
  23. package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
  24. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
  25. package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
  26. package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
  27. package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
  28. package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
  29. package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
  30. package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
  31. package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
  32. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
  33. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  34. package/runtime/plugins/agents-init/content.json +4 -2
  35. package/runtime/plugins/agents-init/plugin.json +1 -1
  36. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
  37. package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
  38. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
  39. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
  40. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
  41. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  42. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  43. package/runtime/plugins/opinion-manager/catalog/README.md +3 -1
  44. package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
  45. package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
  46. package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
  47. package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
  48. package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
  49. package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
  50. package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
  51. package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
  52. package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
  53. package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
  54. package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
  55. package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
  56. package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
  57. package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
  58. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
  59. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
  60. package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
  61. package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
  62. package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
  63. package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
  64. package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
  65. package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
  66. package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
  67. package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
  68. package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
  69. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
  70. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
  71. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
  72. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
  73. package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
  74. package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
  75. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
  76. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
  77. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
  78. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
  79. package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
  80. package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
  81. package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
  82. package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
  83. package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
  84. package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
  85. package/runtime/plugins/opinion-manager/content.json +44 -3
  86. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  87. package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
  88. package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
  89. package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
  90. package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
  91. package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
  92. package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
  93. package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
  94. package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
  95. package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
  96. package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
  97. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
  98. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
  99. package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
  100. package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
  101. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
  102. package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
  103. package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
  104. package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
  105. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
  106. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  107. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  108. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
  109. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
  110. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
  111. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
  112. package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
  113. package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
  114. package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
  115. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
  116. package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
  117. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
@@ -26,6 +26,7 @@ from pathlib import Path
26
26
  from typing import Any, Iterable
27
27
 
28
28
  import agent_pack_config as core
29
+ import agent_pack_scope as scoping
29
30
 
30
31
  OVERRIDE_CONTAINERS = ("headers", "env")
31
32
  STATE_SCHEMA = 1
@@ -203,6 +204,118 @@ def _inside(path: Path, root: Path) -> bool:
203
204
  return False
204
205
 
205
206
 
207
+ # ---------------------------------------------------------------- project-level stores
208
+
209
+ PROJECT_STORES = ("local", "file")
210
+ LOCAL_UNRECOGNIZED = "local-structure-unrecognized"
211
+ PROJECT_SKILL_ACTIONS = ("link-project-skill", "copy-project-skill", "relink-project-skill", "refresh-project-skill",
212
+ "conflict-project-skill", "keep-project-skill")
213
+ PROJECT_ACTIONS = ("add-project-mcp", "update-project-mcp", "conflict-project-mcp", "keep-project-mcp",
214
+ "keep-override-project-mcp")
215
+
216
+
217
+ def normalize_project_store(value: str | None) -> str:
218
+ store = value or "local"
219
+ if store not in PROJECT_STORES:
220
+ raise core.AgentPackError(f"unknown --project-store: {store} (choose from {', '.join(PROJECT_STORES)})")
221
+ return store
222
+
223
+
224
+ def local_section(config: dict[str, Any], root: Path) -> tuple[str | None, dict[str, Any], str | None]:
225
+ """(key, servers, problem) of ``~/.claude.json`` ``projects[<absolute path>].mcpServers`` for this project.
226
+
227
+ The documentation says only that the entry lives "under that project's path"; any shape other than
228
+ ``projects`` -> path -> ``mcpServers`` objects is a ``problem`` and nothing is written there.
229
+ """
230
+ projects = config.get("projects")
231
+ if projects is None:
232
+ return str(root), {}, None
233
+ if not isinstance(projects, dict):
234
+ return None, {}, LOCAL_UNRECOGNIZED
235
+ for key in dict.fromkeys((str(root), str(root.resolve()))):
236
+ if key in projects:
237
+ section = projects[key]
238
+ if not isinstance(section, dict):
239
+ return None, {}, LOCAL_UNRECOGNIZED
240
+ servers = section.get("mcpServers")
241
+ if servers is None:
242
+ return key, {}, None
243
+ return (key, servers, None) if isinstance(servers, dict) else (None, {}, LOCAL_UNRECOGNIZED)
244
+ return str(root.resolve()), {}, None
245
+
246
+
247
+ def _entry_strings(entry: dict[str, Any]) -> Iterable[tuple[str, str]]:
248
+ """(field path, text) of the command, arguments, working directory and environment values: field paths only,
249
+ never the text, are ever reported."""
250
+ for field in ("command", "cwd"):
251
+ if isinstance(entry.get(field), str):
252
+ yield field, entry[field]
253
+ for index, text in enumerate(entry.get("args") or []):
254
+ if isinstance(text, str):
255
+ yield f"args[{index}]", text
256
+ for container in ("env", "headers"):
257
+ values = entry.get(container)
258
+ for key, text in (values.items() if isinstance(values, dict) else ()):
259
+ if isinstance(text, str):
260
+ yield f"{container}.{key}", text
261
+
262
+
263
+ def machine_specific(entry: dict[str, Any], home: Path, root: Path) -> list[str]:
264
+ """Fields of a rendered entry that tie it to this machine (absolute or home paths, this project's path).
265
+
266
+ A project file (``.mcp.json``) travels with the repository, so such an entry is refused there.
267
+ Returns field names only.
268
+ """
269
+ anchors = [str(home), str(root), str(root.resolve())]
270
+ found: list[str] = []
271
+ for field, text in _entry_strings(entry):
272
+ if text.startswith(("/", "~")) or any(anchor and anchor != "/" and anchor in text for anchor in anchors):
273
+ found.append(field)
274
+ return found
275
+
276
+
277
+ def _sync_service(root: Path) -> dict[str, Any] | None:
278
+ """The cloud-sync folder service the project sits in (by path only), or None. A symbolic link inside a synced
279
+ folder may not survive, so project-level Skills are copied there instead."""
280
+ try:
281
+ import local_only # noqa: PLC0415 - shipped next to this file
282
+
283
+ return local_only.detect_service(root, None)
284
+ except Exception: # noqa: BLE001 - detection is advisory; never block a sync on it
285
+ return None
286
+
287
+
288
+ def _project_file(root: Path) -> Path:
289
+ return root / ".mcp.json"
290
+
291
+
292
+ def _read_project_file(path: Path) -> tuple[dict[str, Any], str | None]:
293
+ """(servers, problem) of the project's ``.mcp.json``."""
294
+ if not path.exists() and not path.is_symlink():
295
+ return {}, None
296
+ if path.is_symlink():
297
+ return {}, "mcp-json-symlink"
298
+ try:
299
+ data = core._read_json(path)
300
+ except core.AgentPackError:
301
+ return {}, "mcp-json-unreadable"
302
+ servers = data.get("mcpServers", {})
303
+ return (servers, None) if isinstance(servers, dict) else ({}, "mcp-json-unreadable")
304
+
305
+
306
+ def _writable(path: Path) -> bool:
307
+ target = path if path.exists() else path.parent
308
+ while not target.exists() and target != target.parent:
309
+ target = target.parent
310
+ return os.access(target, os.W_OK)
311
+
312
+
313
+ def _state_scopes(state: dict[str, Any], kind: str) -> dict[str, str]:
314
+ scopes = state.get("scopes")
315
+ value = scopes.get(kind) if isinstance(scopes, dict) else None
316
+ return value if isinstance(value, dict) else {}
317
+
318
+
206
319
  # ---------------------------------------------------------------- plan
207
320
 
208
321
  def _plugin_skill_links(home: Path, plugin_path: Path) -> list[Path]:
@@ -290,13 +403,22 @@ def _render_package_mcps(package: Path, home: Path, name: str) -> dict[str, dict
290
403
  def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: bool = False,
291
404
  retire_skills: Iterable[str] = (), retire_plugins: Iterable[str] = (),
292
405
  retire_only: bool = False, only: frozenset[str] = frozenset(SYNC_TYPES),
293
- package_tree: Path | None = None) -> dict[str, Any]:
406
+ package_tree: Path | None = None, scope: str = "all",
407
+ project_store: str = "local") -> dict[str, Any]:
294
408
  """Every change a Claude sync would make, without writing; conflicts are listed, not raised.
295
409
 
296
410
  ``only`` limits the sync to those types (#68): ``plugins`` is the package and its install record,
297
411
  ``skills`` the user-level Skill links, ``mcp`` the user-scope MCP entries. ``package_tree`` is the
298
412
  tree that will be installed as the package (default: ``built``). Explicit retirements are never filtered.
413
+
414
+ ``scope`` (#67) narrows the plan to the user-level entries (``user``), the entries the project declares as
415
+ project-level (``project``) or both (``all``). A project-declared entry is never written to the user level;
416
+ ``project`` MCP entries go to ``project_store``: ``local`` (``~/.claude.json`` under the project's path) or
417
+ ``file`` (the project's ``.mcp.json``, only for entries that do not depend on this machine). A target that is not
418
+ writable, or whose structure is not recognised, makes the entry ``skip-*`` with a warning: never a fallback to
419
+ the user level. Project-declared Skills are still ``skip-skill`` here (``.claude/skills`` arrives with a later change).
299
420
  """
421
+ project_store = normalize_project_store(project_store)
300
422
  package_tree = package_tree or built
301
423
  layout = core.load_project_layout(project)
302
424
  authority = core.inventory_project(layout.root)
@@ -313,9 +435,22 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
313
435
  desired_mcps = _render_package_mcps(built, home, name)
314
436
  excluded = sorted(item.name for item in authority.mcps
315
437
  if item.portable and not core._mcp_allowed(layout, item.name, "claude"))
438
+ mcp_places = _state_scopes(state, "mcps")
439
+ # Project-level entries are recorded only under ``scopes`` (never in the pre-existing ``skills`` / ``mcps`` keys,
440
+ # which an older runtime reads as user-level ownership), so those two keys are user-level ownership only.
441
+ owned_project_mcps = {server for server, place in mcp_places.items() if place != "user"}
316
442
  owned_mcps = set(state.get("mcps", {}))
317
443
  owned_mcps |= {server for server, entry in existing.items() if _references(entry, record)}
318
- owned_skills = set(state.get("skills", []))
444
+ skill_places = _state_scopes(state, "skills")
445
+ owned_project_skills = {item for item, place in skill_places.items() if place != "user"}
446
+ owned_skills = set(state.get("skills", [])) # the pre-existing key is user-level ownership only
447
+ skill_sources = {item.name: Path(item.path) for item in authority.skills}
448
+ project_skills = {item for item in desired_skills if core.declared_scope(layout, "skill", item) == "project"}
449
+ project_mcps = {item for item in desired_mcps if core.declared_scope(layout, "mcp", item) == "project"}
450
+ # Scope fields appear only once the project declares a scope (or --scope is given); older output is unchanged.
451
+ aware = bool(project_skills or project_mcps or layout.mcp_scope or layout.skill_scope
452
+ or layout.default_scope != "user" or owned_project_skills or owned_project_mcps) or scope != "all"
453
+ do_user, do_project = scope != "project", scope != "user"
319
454
 
320
455
  operations: list[dict[str, Any]] = []
321
456
  conflicts: list[str] = []
@@ -323,15 +458,28 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
323
458
  residuals: list[dict[str, str]] = []
324
459
 
325
460
  sync_skills, sync_mcps = "skills" in only, "mcp" in only
461
+ others = scoping.other_projects(home, name) if aware else []
462
+ narrowing: list[dict[str, Any]] = []
463
+ skipped: list[dict[str, str]] = []
464
+ migrations: list[dict[str, Any]] = []
465
+ shadowed: list[dict[str, Any]] = []
466
+ degraded: list[dict[str, Any]] = []
467
+ project_skill_places: dict[str, str] = {}
468
+ retired_project_skills: set[str] = set()
469
+ retired_user_skills: set[str] = set()
326
470
  if not retire_only:
327
471
  # The package is the carrier of the other two types, so a partial sync still installs it (composed
328
472
  # from what is installed plus the selected parts); the record link follows the package.
329
- if package.exists() and not package.is_symlink():
473
+ if not do_user:
474
+ pass
475
+ elif package.exists() and not package.is_symlink():
330
476
  same = core._tree_fingerprint(package) == core._tree_fingerprint(package_tree)
331
477
  operations.append({"action": "keep-package" if same else "replace-package", "name": name, "to": str(package)})
332
478
  else:
333
479
  operations.append({"action": "install-package", "name": name, "to": str(package)})
334
- if old_target is not None and package.is_dir() and old_target.resolve() == package.resolve():
480
+ if not do_user:
481
+ pass
482
+ elif old_target is not None and package.is_dir() and old_target.resolve() == package.resolve():
335
483
  operations.append({"action": "keep-record", "name": name, "to": str(record)})
336
484
  elif record.is_symlink() or record.exists():
337
485
  detail = {"from": str(old_target)} if old_target is not None else {}
@@ -340,7 +488,7 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
340
488
  operations.append({"action": "link-record", "name": name, "to": str(record)})
341
489
 
342
490
  skills_root = home / ".claude" / "skills"
343
- for skill in sorted(desired_skills if sync_skills else ()):
491
+ for skill in sorted((desired_skills - project_skills) if sync_skills and do_user else ()):
344
492
  path, target = skills_root / skill, package / "skills" / skill
345
493
  link = _link_target(path)
346
494
  ours = skill in owned_skills or (link is not None and (
@@ -355,18 +503,20 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
355
503
  action = "conflict-skill"
356
504
  conflicts.append(f"skill {skill}: {path}")
357
505
  operations.append({"action": action, "name": skill, "to": str(path)})
358
- for skill in sorted(owned_skills - desired_skills if sync_skills else ()):
506
+ for skill in sorted(owned_skills - desired_skills if sync_skills and do_user else ()):
359
507
  path = skills_root / skill
360
508
  if path.is_symlink() or path.exists():
361
509
  operations.append({"action": "remove-skill", "name": skill, "from": str(path)})
362
- if sync_skills and legacy_root is not None and skills_root.is_dir():
510
+ if sync_skills and do_user and legacy_root is not None and skills_root.is_dir():
363
511
  for path in sorted(skills_root.iterdir()):
364
512
  link = _link_target(path)
365
513
  if (path.name not in desired_skills and path.name not in owned_skills and link is not None
366
514
  and _inside(link, legacy_root)):
367
515
  operations.append({"action": "remove-skill", "name": path.name, "from": str(path)})
368
516
 
369
- for server, rendered in (desired_mcps.items() if sync_mcps else ()):
517
+ for server, rendered in (desired_mcps.items() if sync_mcps and do_user else ()):
518
+ if server in project_mcps:
519
+ continue
370
520
  state_name, entry, kept = classify_mcp(rendered, existing.get(server), reset=reset_overrides)
371
521
  if state_name == "differ":
372
522
  if server in owned_mcps:
@@ -377,11 +527,153 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
377
527
  if kept:
378
528
  overrides.append({"name": server, "keys": kept})
379
529
  operations.append({"action": f"{state_name}-mcp", "name": server, "keys": kept, "_entry": entry})
380
- for server in sorted(owned_mcps - set(desired_mcps) if sync_mcps else ()):
530
+ for server in sorted(owned_mcps - set(desired_mcps) if sync_mcps and do_user else ()):
381
531
  if server in existing:
382
532
  operations.append({"action": "remove-mcp", "name": server,
383
533
  "reason": "excluded for claude" if server in excluded else "no longer in project"})
384
534
 
535
+ if not retire_only and do_project:
536
+ skills_dir = layout.root / ".claude" / "skills"
537
+ service = _sync_service(layout.root)
538
+ mode = "copy" if service else "link"
539
+ skills_problem = None
540
+ if (layout.root / ".claude").is_symlink() or skills_dir.is_symlink():
541
+ skills_problem = "project-skills-symlink"
542
+ elif not _writable(skills_dir):
543
+ skills_problem = "target-not-writable"
544
+ for skill in sorted(project_skills if sync_skills else ()):
545
+ path, source = skills_dir / skill, skill_sources.get(skill)
546
+ base = {"name": skill, "to": str(path), "scope": "project", "store": scoping.PROJECT_SKILLS}
547
+ reason = skills_problem or (None if source is not None and _inside(source, layout.root)
548
+ else "skill-source-outside-project")
549
+ if reason:
550
+ operations.append({"action": "skip-skill", **base})
551
+ skipped.append({"kind": "skill", "name": skill, "client": "claude", "reason": reason})
552
+ continue
553
+ rel = os.path.relpath(source, skills_dir)
554
+ existing_here = path.is_symlink() or path.exists()
555
+ ours_here = skill in owned_project_skills
556
+ if mode == "link":
557
+ if not existing_here:
558
+ action = "link-project-skill"
559
+ elif path.is_symlink() and (os.readlink(path) == rel or _link_target(path) == source):
560
+ action = "keep-project-skill"
561
+ elif ours_here:
562
+ action = "relink-project-skill"
563
+ else:
564
+ action = "conflict-project-skill"
565
+ else:
566
+ if not existing_here:
567
+ action = "copy-project-skill"
568
+ elif (not path.is_symlink() and path.is_dir()
569
+ and core._tree_fingerprint(path) == core._tree_fingerprint(source)):
570
+ action = "keep-project-skill"
571
+ elif ours_here:
572
+ action = "refresh-project-skill"
573
+ else:
574
+ action = "conflict-project-skill"
575
+ if action == "conflict-project-skill":
576
+ conflicts.append(f"project-skill {skill}: {path}")
577
+ operations.append({"action": action, **base, "mode": mode, "_source": source,
578
+ **({"target": rel} if mode == "link" else {})})
579
+ project_skill_places[skill] = f"project:{mode}"
580
+ if sync_skills and service and any(item.get("mode") == "copy" for item in operations):
581
+ degraded.append({"kind": "skill", "mode": "copy", "reason": "sync-folder", "service": service.get("id")})
582
+ for skill in sorted((owned_project_skills - project_skills) if sync_skills else ()):
583
+ path = skills_dir / skill
584
+ if not (path.is_symlink() or path.exists()) or skills_problem:
585
+ continue
586
+ moved_user = skill in desired_skills and do_user # declared user-level now: the project copy is retired
587
+ if skill in desired_skills and not do_user:
588
+ continue
589
+ operations.append({"action": "archive-project-skill", "name": skill, "from": str(path),
590
+ "scope": "project", "store": scoping.PROJECT_SKILLS,
591
+ "reason": "moved to user level" if moved_user else "no longer in project"})
592
+ retired_project_skills.add(skill)
593
+ if moved_user:
594
+ migrations.append(scoping.migration_entry(
595
+ "skill", skill, "widen", scoping.PROJECT_SKILLS, scoping.USER_SKILLS,
596
+ write_new="link-skill", retire={"action": "archive-project-skill", "path": str(path)}))
597
+ # user -> project: the user-level link this package made is archived (personal Skills outrank project ones)
598
+ for skill in sorted(project_skills if sync_skills and do_user else ()):
599
+ user_path = skills_root / skill
600
+ if skill not in project_skill_places or not (user_path.is_symlink() or user_path.exists()):
601
+ continue
602
+ link = _link_target(user_path)
603
+ ours_user = link is not None and (_inside(link, package) or (legacy_root is not None and _inside(link, legacy_root)))
604
+ if not ours_user: # someone else's Skill of that name: not archived, but it outranks the project one
605
+ advisory = scoping.skill_shadow(skill)
606
+ if advisory:
607
+ shadowed.append(advisory)
608
+ continue
609
+ operations.append({"action": "archive-skill", "name": skill, "from": str(user_path),
610
+ "reason": "moved to project level", "scope": "user", "store": scoping.USER_SKILLS})
611
+ retired_user_skills.add(skill)
612
+ narrowing.append(scoping.narrowing_entry("skill", skill, scoping.USER_SKILLS, scoping.PROJECT_SKILLS, others)
613
+ | {"status": "planned"})
614
+ migrations.append(scoping.migration_entry(
615
+ "skill", skill, "narrow", scoping.USER_SKILLS, scoping.PROJECT_SKILLS,
616
+ write_new=next((item["action"] for item in operations if item["name"] == skill
617
+ and item["action"].endswith("-project-skill")), "skip-skill"),
618
+ retire={"action": "archive-skill", "path": str(user_path)}))
619
+ local_key, local_servers, local_problem = local_section(config, layout.root)
620
+ file_path = _project_file(layout.root)
621
+ file_servers, file_problem = _read_project_file(file_path)
622
+ target_store = scoping.LOCAL_MCP if project_store == "local" else scoping.FILE_MCP
623
+ target_path = (f"{core._claude_user_config(home)}#projects[{local_key or layout.root}].mcpServers"
624
+ if project_store == "local" else str(file_path))
625
+ problem = (local_problem if project_store == "local" else file_problem) or (
626
+ None if _writable(core._claude_user_config(home) if project_store == "local" else file_path)
627
+ else "target-not-writable")
628
+ place = "project:local" if project_store == "local" else "project:file"
629
+ wanted = sorted(project_mcps) if sync_mcps else []
630
+ if scope == "project" and any(_references(desired_mcps[server], record) for server in wanted) \
631
+ and not package.is_dir():
632
+ raise core.AgentPackError(
633
+ "project-level MCP entries launch through the project package, which is not installed yet: "
634
+ "sync the package first (--scope user, or --only plugins)")
635
+ if project_store == "file":
636
+ bad = {server: machine_specific(desired_mcps[server], home, layout.root) for server in wanted}
637
+ bad = {server: fields for server, fields in bad.items() if fields}
638
+ if bad:
639
+ raise core.AgentPackError(
640
+ "MCP entries that depend on this machine cannot be written to the project file .mcp.json "
641
+ "(use --project-store local or declare them user-level): "
642
+ + "; ".join(f"{server} ({', '.join(fields)})" for server, fields in sorted(bad.items())))
643
+ current_servers = local_servers if project_store == "local" else file_servers
644
+ for server in wanted:
645
+ if problem:
646
+ operations.append({"action": "skip-mcp", "name": server, "to": target_path,
647
+ "scope": "project", "store": target_store})
648
+ skipped.append({"kind": "mcp", "name": server, "client": "claude", "reason": problem})
649
+ continue
650
+ state_name, entry, kept = classify_mcp(desired_mcps[server], current_servers.get(server),
651
+ reset=reset_overrides or project_store == "file")
652
+ if state_name == "differ":
653
+ if mcp_places.get(server) == place and server in owned_project_mcps:
654
+ state_name = "update"
655
+ else:
656
+ state_name = "conflict"
657
+ conflicts.append(f"project-mcp {server}: {target_path}")
658
+ if kept:
659
+ overrides.append({"name": server, "keys": kept})
660
+ operations.append({"action": f"{state_name}-project-mcp", "name": server, "to": target_path,
661
+ "keys": kept, "scope": "project", "store": target_store, "_entry": entry})
662
+ if server in existing:
663
+ command = f"claude mcp remove --scope user {server}"
664
+ narrowing.append(scoping.narrowing_entry("mcp", server, scoping.USER_MCP, target_store, others)
665
+ | {"manual": command})
666
+ migrations.append(scoping.migration_entry(
667
+ "mcp", server, "narrow", scoping.USER_MCP, target_store, write_new=f"{state_name}-project-mcp",
668
+ retire={"action": "manual", "command": command}))
669
+ advisory = scoping.mcp_shadow(server, project_store)
670
+ if advisory:
671
+ shadowed.append(advisory)
672
+ for server in sorted(owned_project_mcps - set(desired_mcps) if sync_mcps else ()):
673
+ if mcp_places.get(server) == place and server in current_servers and not problem:
674
+ operations.append({"action": "remove-project-mcp", "name": server, "to": target_path,
675
+ "scope": "project", "store": target_store, "reason": "no longer in project"})
676
+
385
677
  client_inventory = core.inventory_client("claude", home)
386
678
  actual_skills = {item.name: Path(item.path) for item in client_inventory.skills}
387
679
  actual_plugins = {str(item.get("name")): Path(str(item.get("path")))
@@ -409,8 +701,29 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
409
701
  if retire_only and not (retire_skills or retire_plugins):
410
702
  raise core.AgentPackError("retire-only reconcile needs at least one --retire-skill or --retire-plugin")
411
703
 
704
+ if sync_mcps and do_user and do_project: # project -> user: the old project-level entry is not edited, only named
705
+ for server in sorted(owned_project_mcps & (set(desired_mcps) - project_mcps)):
706
+ place = mcp_places.get(server)
707
+ command = "claude mcp remove --scope " + ("local" if place == "project:local" else "project") + f" {server}"
708
+ migrations.append(scoping.migration_entry(
709
+ "mcp", server, "widen", scoping.LOCAL_MCP if place == "project:local" else scoping.FILE_MCP,
710
+ scoping.USER_MCP, write_new="add-mcp", retire={"action": "manual", "command": command}))
412
711
  native = sorted(server for server in existing if server not in desired_mcps and server not in owned_mcps)
413
- return {"name": name, "layout": layout, "operations": operations, "conflicts": conflicts,
712
+ # What the state records as owned: what this plan puts at the user level, plus project-declared entries that
713
+ # already sit there under this package's ownership (they stay until a later change moves them).
714
+ state_skills = sorted((desired_skills - project_skills) | ((project_skills & owned_skills) - retired_user_skills))
715
+ carried_mcps = sorted(server for server in project_mcps & owned_mcps if server in existing)
716
+ undeclared = sorted((set(layout.mcp_scope) - set(desired_mcps) - set(item.name for item in authority.mcps))
717
+ | (set(layout.skill_scope) - desired_skills - set(item.name for item in authority.skills)))
718
+ return {"name": name, "aware": aware, "scope": scope, "do_user": do_user, "do_project": do_project,
719
+ "migrations": migrations, "shadowed": shadowed, "degraded": degraded,
720
+ "project_skill_places": project_skill_places, "retired_project_skills": sorted(retired_project_skills), "skipped": skipped, "narrowing": narrowing,
721
+ "others": others, "undeclared": undeclared,
722
+ "state_skills": state_skills, "carried_mcps": carried_mcps,
723
+ "scope_counts": {"user": {"skills": len(desired_skills - project_skills) if sync_skills and do_user else 0,
724
+ "mcp": len(set(desired_mcps) - project_mcps) if sync_mcps and do_user else 0},
725
+ "project": {"skills": len(project_skills) if sync_skills and do_project else 0,
726
+ "mcp": len(project_mcps) if sync_mcps and do_project else 0}}, "layout": layout, "operations": operations, "conflicts": conflicts,
414
727
  "retire_only": retire_only, "residuals": residuals, "only": sorted(only),
415
728
  "overrides": overrides if sync_mcps else [],
416
729
  "excluded": [server for server in excluded if server in existing] if sync_mcps else [],
@@ -418,9 +731,29 @@ def plan_project(project: Path, home: Path, *, built: Path, reset_overrides: boo
418
731
  "desired_skills": sorted(desired_skills), "desired_mcps": sorted(desired_mcps)}
419
732
 
420
733
 
421
- def _public(operations: list[dict[str, Any]]) -> list[dict[str, Any]]:
422
- return [{key: value for key, value in item.items() if not key.startswith("_") and value != []}
423
- | {"client": "claude"} for item in operations]
734
+ def _public(operations: list[dict[str, Any]], aware: bool = False) -> list[dict[str, Any]]:
735
+ result = [{key: value for key, value in item.items() if not key.startswith("_") and value != []}
736
+ | {"client": "claude"} for item in operations]
737
+ if aware: # scope and store only appear once a project declares a scope (older output stays byte-identical)
738
+ for item in result:
739
+ for key, value in _scope_of_operation(item).items():
740
+ item.setdefault(key, value)
741
+ return result
742
+
743
+
744
+ def _scope_of_operation(item: dict[str, Any]) -> dict[str, str]:
745
+ action = item["action"]
746
+ if action.endswith("-project-skill") or (action.endswith("-skill") and action.startswith("skip-")):
747
+ return {"scope": "project", "store": scoping.PROJECT_SKILLS}
748
+ if action.startswith("skip-") and action.endswith("-mcp"):
749
+ return {"scope": "project", "store": scoping.LOCAL_MCP}
750
+ if action.endswith("-project-mcp"):
751
+ return {"scope": "project", "store": scoping.LOCAL_MCP}
752
+ if action.endswith("-mcp"):
753
+ return {"scope": "user", "store": scoping.USER_MCP}
754
+ if action.endswith("-skill"):
755
+ return {"scope": "user", "store": scoping.USER_SKILLS}
756
+ return {"scope": "user"} # the package and its install record are the user-level carrier
424
757
 
425
758
 
426
759
  # ---------------------------------------------------------------- apply
@@ -428,7 +761,9 @@ def _public(operations: list[dict[str, Any]]) -> list[dict[str, Any]]:
428
761
  def _conflict_summary(conflicts: list[str]) -> dict[str, int]:
429
762
  """Conflicts counted per type; a conflict string starts with ``skill`` or ``mcp``."""
430
763
  counts = {"skills": sum(1 for item in conflicts if item.startswith("skill ")),
431
- "mcp": sum(1 for item in conflicts if item.startswith("mcp "))}
764
+ "mcp": sum(1 for item in conflicts if item.startswith("mcp ")),
765
+ "project_mcp": sum(1 for item in conflicts if item.startswith("project-mcp ")),
766
+ "project_skills": sum(1 for item in conflicts if item.startswith("project-skill "))}
432
767
  return {key: number for key, number in counts.items() if number}
433
768
 
434
769
 
@@ -441,6 +776,10 @@ def _global_warnings(home: Path, summary: dict[str, int]) -> list[str]:
441
776
  if summary.get("mcp"):
442
777
  warnings.append(f"replaces {summary['mcp']} user-scope MCP entr{'y' if summary['mcp'] == 1 else 'ies'} in "
443
778
  f"{core._claude_user_config(home)}; they apply to every project (the replaced originals go to recovery)")
779
+ if summary.get("project_mcp"):
780
+ warnings.append(scoping.project_replace_warning(summary["project_mcp"]))
781
+ if summary.get("project_skills"):
782
+ warnings.append(scoping.project_skills_replace_warning(summary["project_skills"]))
444
783
  return warnings
445
784
 
446
785
 
@@ -448,8 +787,13 @@ def sync_project(project: Path, *, home: Path | None = None, apply: bool = False
448
787
  reset_overrides: bool = False, recovery_root: Path | None = None,
449
788
  retire_skills: Iterable[str] = (), retire_plugins: Iterable[str] = (),
450
789
  retire_only: bool = False, only: Iterable[str] | None = None,
451
- replace_mcp: bool = False, replace_skills: bool = False) -> dict[str, Any]:
790
+ replace_mcp: bool = False, replace_skills: bool = False, scope: str = "all",
791
+ project_store: str = "local") -> dict[str, Any]:
452
792
  home = (home or Path.home()).expanduser().resolve()
793
+ try:
794
+ scope = scoping.normalize_scope(scope)
795
+ except ValueError as exc:
796
+ raise core.AgentPackError(str(exc)) from exc
453
797
  retire_skills, retire_plugins = list(retire_skills), list(retire_plugins)
454
798
  types = normalize_only(only)
455
799
  with tempfile.TemporaryDirectory(prefix="agent-pack-claude-") as temporary:
@@ -461,17 +805,17 @@ def sync_project(project: Path, *, home: Path | None = None, apply: bool = False
461
805
  package_root(home, name), built, types, Path(temporary))
462
806
  plan = plan_project(project, home, built=built, reset_overrides=reset_overrides,
463
807
  retire_skills=retire_skills, retire_plugins=retire_plugins, retire_only=retire_only,
464
- only=types, package_tree=tree)
808
+ only=types, package_tree=tree, scope=scope, project_store=project_store)
465
809
  blocking = [item for item in plan["conflicts"]
466
- if not (replace or (replace_mcp and item.startswith("mcp ")) or
467
- (replace_skills and item.startswith("skill ")))]
810
+ if not (replace or (replace_mcp and item.startswith(("mcp ", "project-mcp "))) or
811
+ (replace_skills and item.startswith(("skill ", "project-skill "))))]
468
812
  if blocking:
469
813
  raise core.AgentPackError("Claude client already has different content not installed by this package "
470
814
  "(use --replace, or --replace-mcp / --replace-skills for one type; "
471
815
  "replaced items go to recovery): " + "; ".join(blocking))
472
816
  result: dict[str, Any] = {
473
817
  "ok": True, "applied": False, "client": "claude", "package": name,
474
- "operations": _public(plan["operations"]), "overrides": plan["overrides"],
818
+ "operations": _public(plan["operations"], plan["aware"]), "overrides": plan["overrides"],
475
819
  "excluded": plan["excluded"], "native": plan["native"],
476
820
  "notes": ["restart Claude Code to load changed Skills and MCP servers"],
477
821
  }
@@ -481,11 +825,31 @@ def sync_project(project: Path, *, home: Path | None = None, apply: bool = False
481
825
  result["warnings"] = _global_warnings(home, summary)
482
826
  if types != frozenset(SYNC_TYPES):
483
827
  result["only"] = sorted(types)
828
+ if plan["aware"]:
829
+ result["scope"] = scope
830
+ result["by_scope"] = plan["scope_counts"]
831
+ result["narrowing"] = plan["narrowing"]
832
+ result["skipped"] = plan["skipped"]
833
+ if plan["migrations"]:
834
+ result["migrations"] = plan["migrations"]
835
+ if plan["shadowed"]:
836
+ result["shadowed"] = plan["shadowed"]
837
+ if plan["degraded"]:
838
+ result["degraded"] = plan["degraded"]
839
+ notes = [scoping.narrowing_note()] if plan["narrowing"] else []
840
+ if plan["undeclared"]:
841
+ notes.append(scoping.undeclared_warning(plan["undeclared"]))
842
+ notes += [scoping.widen_warning(item["kind"], item["name"]) for item in plan["migrations"]
843
+ if item["direction"] == "widen"]
844
+ notes += [scoping.sync_folder_warning(item["service"]) for item in plan["degraded"]]
845
+ notes += [scoping.shadow_warning(item) for item in plan["shadowed"]]
846
+ if notes:
847
+ result["warnings"] = [*result.get("warnings", []), *notes]
484
848
  if plan["residuals"]:
485
849
  result["residuals"] = plan["residuals"]
486
850
  if plan["legacy_root"]:
487
851
  result["migrated_from"] = plan["legacy_root"]
488
- changes = [item for item in plan["operations"] if not item["action"].startswith("keep-")]
852
+ changes = [item for item in plan["operations"] if not item["action"].startswith(("keep-", "skip-"))]
489
853
  if not apply or not changes:
490
854
  result["applied"] = apply and not changes
491
855
  return result
@@ -494,6 +858,88 @@ def sync_project(project: Path, *, home: Path | None = None, apply: bool = False
494
858
  return result
495
859
 
496
860
 
861
+ def _project_hashes(state: dict[str, Any]) -> dict[str, str]:
862
+ scopes = state.get("scopes")
863
+ value = scopes.get("project_hashes") if isinstance(scopes, dict) else None
864
+ return value if isinstance(value, dict) else {}
865
+
866
+
867
+ def _final_mcp_state(plan: dict[str, Any], before: dict[str, Any], user: dict[str, str], project: dict[str, tuple[str, str]],
868
+ removed: set[str]) -> tuple[dict[str, str], dict[str, tuple[str, str]]]:
869
+ """Owned MCP entries after an apply: ``(user-level name -> hash, project-level name -> (hash, place))``.
870
+
871
+ The user-level part goes to the pre-existing ``mcps`` key, the project-level part only to ``scopes``. A scope the
872
+ plan did not handle (``--scope``) keeps what the previous state recorded for it.
873
+ """
874
+ old_user = before.get("mcps") if isinstance(before.get("mcps"), dict) else {}
875
+ users = dict(user) if plan["do_user"] else dict(old_user)
876
+ projects: dict[str, tuple[str, str]] = {}
877
+ old_hashes = _project_hashes(before)
878
+ for name, place in _state_scopes(before, "mcps").items():
879
+ if place != "user" and name not in removed and name not in project:
880
+ projects[name] = (old_hashes.get(name, ""), place) # the plan left it alone (skipped, other store, other scope)
881
+ if plan["do_project"]:
882
+ projects.update(project)
883
+ return users, projects
884
+
885
+
886
+ def _final_skill_state(plan: dict[str, Any], before: dict[str, Any]) -> dict[str, str]:
887
+ """Owned Skills after an apply and where each sits (name -> ``user`` | ``project:link`` | ``project:copy``).
888
+
889
+ A scope the plan did not handle (``--scope``) keeps what the previous state recorded for it.
890
+ """
891
+ old_places = _state_scopes(before, "skills")
892
+ retired = set(plan["retired_project_skills"])
893
+ places: dict[str, str] = {}
894
+ previous = dict.fromkeys(before.get("skills", []), "user") | {n: p for n, p in old_places.items() if p != "user"}
895
+ for name, place in previous.items():
896
+ handled = plan["do_user"] if place == "user" else plan["do_project"]
897
+ if not handled or (place != "user" and name not in retired and name not in plan["project_skill_places"]):
898
+ places[name] = place
899
+ if plan["do_user"]:
900
+ for name in plan["state_skills"]:
901
+ places[name] = "user"
902
+ if plan["do_project"]:
903
+ places.update(plan["project_skill_places"])
904
+ return places
905
+
906
+
907
+ def _scopes_record(plan: dict[str, Any], before: dict[str, Any], skills: dict[str, str] | None,
908
+ mcps: tuple[dict[str, str], dict[str, tuple[str, str]]] | None) -> dict[str, Any]:
909
+ """``scopes``: where each owned entry actually sits, and the hashes of the project-level MCP entries. Written
910
+ only once a project declares a scope; a state without it reads as all ``user``."""
911
+ if not plan["aware"] and "scopes" not in before:
912
+ return {}
913
+ old = before.get("scopes") if isinstance(before.get("scopes"), dict) else {}
914
+ if mcps is None:
915
+ places, hashes = dict(old.get("mcps", {})), dict(old.get("project_hashes", {}))
916
+ else:
917
+ users, projects = mcps
918
+ places = {name: "user" for name in users} | {name: place for name, (_digest, place) in projects.items()}
919
+ hashes = {name: digest for name, (digest, _place) in projects.items()}
920
+ return {"scopes": {"skills": dict(skills) if skills is not None else dict(old.get("skills", {})),
921
+ "mcps": places, "project_hashes": hashes}}
922
+
923
+
924
+ def _restore_bytes(path: Path, data: bytes | None, mode: int) -> None:
925
+ """Put a file back exactly as it was (or remove it when it did not exist)."""
926
+ if data is None:
927
+ if path.exists() or path.is_symlink():
928
+ path.unlink()
929
+ return
930
+ descriptor, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
931
+ try:
932
+ with os.fdopen(descriptor, "wb") as handle:
933
+ handle.write(data)
934
+ handle.flush()
935
+ os.fsync(handle.fileno())
936
+ os.chmod(temp_name, mode)
937
+ os.replace(temp_name, path)
938
+ finally:
939
+ if os.path.exists(temp_name):
940
+ os.unlink(temp_name)
941
+
942
+
497
943
  def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path | None) -> Path:
498
944
  name = plan["name"]
499
945
  package, record = package_root(home, name), record_path(home, name)
@@ -505,8 +951,15 @@ def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path |
505
951
  config = _read_config(home)
506
952
  original_config = json.loads(json.dumps(config))
507
953
  config_written = False
954
+ config_bytes = config_path.read_bytes() if config_path.is_file() else None
955
+ config_mode = stat.S_IMODE(config_path.stat().st_mode) if config_path.is_file() else 0o600
956
+ project_file = _project_file(plan["layout"].root)
957
+ file_bytes = project_file.read_bytes() if project_file.is_file() else None
958
+ file_mode = stat.S_IMODE(project_file.stat().st_mode) if project_file.is_file() else 0o644
959
+ file_written = False
508
960
  moved: list[tuple[Path, Path]] = [] # (archived, original)
509
961
  created: list[Path] = []
962
+ made_dirs: list[Path] = []
510
963
  actions = {(item["action"], item["name"]): item for item in plan["operations"]}
511
964
 
512
965
  def archive(path: Path, bucket: str, item_name: str) -> None:
@@ -515,6 +968,15 @@ def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path |
515
968
  os.replace(path, archived)
516
969
  moved.append((archived, path))
517
970
 
971
+ def ensure_dir(directory: Path) -> None:
972
+ missing = []
973
+ probe = directory
974
+ while not probe.exists() and probe != probe.parent:
975
+ missing.append(probe)
976
+ probe = probe.parent
977
+ directory.mkdir(parents=True, exist_ok=True)
978
+ made_dirs.extend(missing)
979
+
518
980
  def link(path: Path, target: Path) -> None:
519
981
  path.parent.mkdir(parents=True, exist_ok=True)
520
982
  os.symlink(target, path, target_is_directory=True)
@@ -548,10 +1010,28 @@ def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path |
548
1010
  archive(path, "replaced-skills" if action != "archive-skill" else "skills", item_name)
549
1011
  if action in ("link-skill", "relink-skill", "conflict-skill"):
550
1012
  link(Path(item["to"]), package / "skills" / item_name)
1013
+ if action in ("relink-project-skill", "refresh-project-skill", "conflict-project-skill"):
1014
+ path = Path(item["to"])
1015
+ if path.is_symlink() or path.exists():
1016
+ archive(path, "replaced-project-skills", item_name)
1017
+ if action == "archive-project-skill":
1018
+ archive(Path(item["from"]), "project-skills", item_name)
1019
+ if action in PROJECT_SKILL_ACTIONS and not action.startswith("keep-"):
1020
+ path = Path(item["to"])
1021
+ ensure_dir(path.parent)
1022
+ if item["mode"] == "link":
1023
+ os.symlink(item["target"], path, target_is_directory=True)
1024
+ else:
1025
+ core._copy_skill(item["_source"], path, allowed_root=plan["layout"].root)
1026
+ created.append(path)
551
1027
  if action == "archive-plugin":
552
1028
  archive(Path(item["from"]), "plugins", item_name)
553
1029
  # A sync that does not include mcp never opens ~/.claude.json for writing (#68).
554
- servers = config.setdefault("mcpServers", {}) if "mcp" in plan["only"] else {}
1030
+ user_mcp_ops = any(item["action"].endswith("-mcp") and not item["action"].endswith("-project-mcp")
1031
+ and not item["action"].startswith("skip-") for item in plan["operations"])
1032
+ # (a scope-aware plan with no user-level MCP operation leaves ~/.claude.json's user section alone)
1033
+ servers = (config.setdefault("mcpServers", {})
1034
+ if "mcp" in plan["only"] and plan["do_user"] and (user_mcp_ops or not plan["aware"]) else {})
555
1035
  replaced: dict[str, Any] = {}
556
1036
  mcp_state: dict[str, str] = {}
557
1037
  for item in plan["operations"]:
@@ -566,22 +1046,74 @@ def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path |
566
1046
  replaced[server] = servers.pop(server)
567
1047
  if replaced:
568
1048
  core._write_json_atomic(transaction / "replaced-mcp.json", {"mcpServers": replaced}, mode=0o600)
1049
+ # Project-level entries: Claude local (inside ~/.claude.json, written with the user-level change in one
1050
+ # atomic replace) and the project file .mcp.json.
1051
+ project_state: dict[str, tuple[str, str]] = {}
1052
+ removed_project: set[str] = set()
1053
+ local_set: dict[str, Any] = {}
1054
+ file_set: dict[str, Any] = {}
1055
+ local_drop: set[str] = set()
1056
+ file_drop: set[str] = set()
1057
+ for item in plan["operations"]:
1058
+ action, server = item["action"], item["name"]
1059
+ if action in PROJECT_ACTIONS:
1060
+ local = item["store"] == scoping.LOCAL_MCP
1061
+ project_state[server] = (hashlib.sha256(json.dumps(item["_entry"], sort_keys=True).encode("utf-8")).hexdigest(),
1062
+ "project:local" if local else "project:file")
1063
+ if not action.startswith("keep-"):
1064
+ (local_set if local else file_set)[server] = item["_entry"]
1065
+ elif action == "remove-project-mcp":
1066
+ removed_project.add(server)
1067
+ (local_drop if item["store"] == scoping.LOCAL_MCP else file_drop).add(server)
1068
+ if local_set or local_drop:
1069
+ key = local_section(config, plan["layout"].root)[0]
1070
+ if key is None:
1071
+ raise core.AgentPackError("claude local MCP store changed shape since the preview")
1072
+ if config_bytes is not None: # the original file, before any write (it may hold the user's own values)
1073
+ backup = transaction / "claude.json.before"
1074
+ backup.write_bytes(config_bytes)
1075
+ os.chmod(backup, 0o600)
1076
+ section = config.setdefault("projects", {}).setdefault(key, {})
1077
+ local_servers = section.setdefault("mcpServers", {})
1078
+ local_servers.update(local_set)
1079
+ for server in local_drop:
1080
+ local_servers.pop(server, None)
569
1081
  if config != original_config:
570
- mode = stat.S_IMODE(config_path.stat().st_mode) if config_path.exists() else 0o600
571
- core._write_json_atomic(config_path, config, mode=mode)
1082
+ core._write_json_atomic(config_path, config, mode=config_mode)
572
1083
  config_written = True
1084
+ if file_set or file_drop:
1085
+ if file_bytes is not None:
1086
+ backup = transaction / "project-mcp.json.before"
1087
+ backup.write_bytes(file_bytes)
1088
+ os.chmod(backup, 0o600)
1089
+ data = core._read_json(project_file) if file_bytes is not None else {}
1090
+ file_servers = data.setdefault("mcpServers", {})
1091
+ file_servers.update(file_set)
1092
+ for server in file_drop:
1093
+ file_servers.pop(server, None)
1094
+ core._write_json_atomic(project_file, data, mode=file_mode)
1095
+ file_written = True
1096
+ for server in plan["carried_mcps"]: # project-declared, already owned at the user level: keep owning it
1097
+ if "mcp" in plan["only"]:
1098
+ mcp_state.setdefault(server, (_read_state(home, name).get("mcps") or {}).get(server)
1099
+ or hashlib.sha256(json.dumps(servers.get(server), sort_keys=True).encode("utf-8")).hexdigest())
573
1100
  if not plan["retire_only"]:
574
1101
  # A partial sync records only the types it handled; the others keep their recorded ownership.
575
1102
  before = _read_state(home, name)
576
1103
  only = set(plan["only"])
1104
+ final = _final_mcp_state(plan, before, mcp_state, project_state, removed_project) if "mcp" in only else None
1105
+ skill_places_final = _final_skill_state(plan, before) if "skills" in only else None
1106
+ skills_final = (sorted(name for name, place in skill_places_final.items() if place == "user")
1107
+ if skill_places_final is not None else before.get("skills", []))
577
1108
  core._write_json_atomic(state_path(home, name), {
578
1109
  "schema_version": STATE_SCHEMA, "package": name,
579
- "skills": plan["desired_skills"] if "skills" in only else before.get("skills", []),
580
- "mcps": mcp_state if "mcp" in only else before.get("mcps", {}),
581
- "updated_at": stamp}, mode=0o600)
1110
+ "skills": skills_final, "mcps": final[0] if final else before.get("mcps", {}),
1111
+ "updated_at": stamp} | _scopes_record(plan, before, skill_places_final, final), mode=0o600)
582
1112
  except Exception as exc:
583
1113
  if config_written:
584
- core._write_json_atomic(config_path, original_config, mode=0o600)
1114
+ _restore_bytes(config_path, config_bytes, config_mode)
1115
+ if file_written:
1116
+ _restore_bytes(project_file, file_bytes, file_mode)
585
1117
  for path in reversed(created):
586
1118
  if path.is_symlink():
587
1119
  path.unlink()
@@ -591,6 +1123,11 @@ def _apply(plan: dict[str, Any], built: Path, home: Path, recovery_root: Path |
591
1123
  if (archived.exists() or archived.is_symlink()) and not (original.exists() or original.is_symlink()):
592
1124
  original.parent.mkdir(parents=True, exist_ok=True)
593
1125
  os.replace(archived, original)
1126
+ for directory in made_dirs: # deepest first: the list was built from the leaf upwards
1127
+ try:
1128
+ directory.rmdir()
1129
+ except OSError:
1130
+ pass
594
1131
  raise core.AgentPackError(f"claude sync rolled back: {exc}") from exc
595
1132
  return transaction
596
1133
 
@@ -609,11 +1146,14 @@ def drift(project: Path, home: Path | None = None) -> dict[str, Any]:
609
1146
  "excluded": plan["excluded"], "dangling": [], "coupled": plan["legacy_root"]}
610
1147
  for item in plan["operations"]:
611
1148
  action, item_name = item["action"], item["name"]
612
- if action in ("install-package", "link-record", "link-skill", "add-mcp"):
1149
+ if action in ("install-package", "link-record", "link-skill", "add-mcp", "add-project-mcp",
1150
+ "link-project-skill", "copy-project-skill"):
613
1151
  report["missing"].append(f"{action.split('-')[1]} {item_name}")
614
- elif action in ("replace-package", "relink-skill", "conflict-skill", "update-mcp", "conflict-mcp"):
1152
+ elif action in ("replace-package", "relink-skill", "conflict-skill", "update-mcp", "conflict-mcp",
1153
+ "update-project-mcp", "conflict-project-mcp", "relink-project-skill",
1154
+ "refresh-project-skill", "conflict-project-skill"):
615
1155
  report["different"].append(f"{action.split('-')[-1]} {item_name}")
616
- elif action in ("remove-skill", "remove-mcp"):
1156
+ elif action in ("remove-skill", "remove-mcp", "remove-project-mcp", "archive-project-skill"):
617
1157
  report["stale"].append(f"{action.split('-')[1]} {item_name}")
618
1158
  skills_root = home / ".claude" / "skills"
619
1159
  if skills_root.is_dir():
@@ -626,6 +1166,8 @@ def drift(project: Path, home: Path | None = None) -> dict[str, Any]:
626
1166
  if text.startswith(str(record) + os.sep) and not Path(text).exists():
627
1167
  report["dangling"].append(f"mcp {server}: {text}")
628
1168
  break
1169
+ if plan["shadowed"]: # advisory only: never part of in_sync
1170
+ report["advisories"] = plan["shadowed"]
629
1171
  report["in_sync"] = not (report["missing"] or report["different"] or report["stale"]
630
1172
  or report["dangling"] or report["coupled"])
631
1173
  return report