Compound Engineering Setup Interaction Method Ask each question below using the host's blocking question tool already in the current tool list (match by capability, not by a host-specific name). Presence in the current tool list is proof the tool exists; never call a user-facing question tool to discover whether it exists. If a matching tool is listed but unloaded, use the host's tool-discovery primitive to load that capability — do not search for another host's tool name. Fall back to a numbered list on the host's user-visible chat surface only when no such tool is in the list or a real ques…

\\t' read -r preference_kind preference_harness preference_model; do\n case \"$preference_kind\" in\n ITEM)\n work_engine_preferences_count=$((work_engine_preferences_count + 1))\n case \"$preference_harness\" in\n codex|claude|grok|cursor|opencode) ;;\n antigravity) antigravity_configured=\"yes\" ;;\n *)\n [ -z \"$work_engine_preferences_error\" ] && work_engine_preferences_error=\"invalid harness '$preference_harness' in work_engine_preferences\"\n ;;\n esac\n if [ \"$preference_model\" != \"default\" ]; then\n case \"$preference_model\" in\n [A-Za-z0-9]*)\n case \"$preference_model\" in\n *[!A-Za-z0-9._:/-]*)\n [ -z \"$work_engine_preferences_error\" ] && work_engine_preferences_error=\"invalid model '$preference_model' in work_engine_preferences\"\n ;;\n esac\n ;;\n *)\n [ -z \"$work_engine_preferences_error\" ] && work_engine_preferences_error=\"invalid model '$preference_model' in work_engine_preferences\"\n ;;\n esac\n fi\n preference_display=\"${preference_harness}@${preference_model}\"\n if [ -n \"$work_engine_preferences_detail\" ]; then\n work_engine_preferences_detail=\"${work_engine_preferences_detail}, ${preference_display}\"\n else\n work_engine_preferences_detail=\"$preference_display\"\n fi\n ;;\n ERROR)\n [ -z \"$work_engine_preferences_error\" ] && work_engine_preferences_error=\"$preference_harness\"\n ;;\n esac\n done \u003c \u003c(read_work_engine_preferences \"$structured_file\")\n fi\n\n work_engine_effort_notes=()\n resolve_structured_layer \"$local_config_path\" \"$tracked_config_path\" \"work_engine_effort\"\n if [ -n \"$structured_file\" ]; then\n while IFS=

Compound Engineering Setup Interaction Method Ask each question below using the host's blocking question tool already in the current tool list (match by capability, not by a host-specific name). Presence in the current tool list is proof the tool exists; never call a user-facing question tool to discover whether it exists. If a matching tool is listed but unloaded, use the host's tool-discovery primitive to load that capability — do not search for another host's tool name. Fall back to a numbered list on the host's user-visible chat surface only when no such tool is in the list or a real ques…

\\t' read -r effort_kind effort_harness effort_value; do\n case \"$effort_kind:$effort_harness\" in\n ERROR:*) effort_problem=\"is not a map of harness to effort; ce-work ignores the value and keeps each harness default\" ;;\n KEY:cursor) effort_problem=\"names 'cursor', which takes no effort; ce-work treats Cursor entries as unavailable while it is set\" ;;\n KEY:codex|KEY:claude|KEY:grok|KEY:opencode) continue ;;\n KEY:antigravity)\n case \"$effort_value\" in low|medium|high) continue ;; esac\n effort_problem=\"sets antigravity to '${effort_value}'; Antigravity takes low, medium, or high, so ce-work treats Antigravity entries as unavailable while it is set\" ;;\n KEY:*) effort_problem=\"names unknown harness '${effort_harness}'; ce-work ignores that entry\" ;;\n *) continue ;;\n esac\n work_engine_effort_notes+=(\"work_engine_effort in $(basename \"$structured_file\") ${effort_problem}\")\n done \u003c \u003c(read_work_engine_effort_keys \"$structured_file\")\n fi\n\n case \"$work_engine_mode\" in\n \"\"|off)\n work_engine_cfg=\"native\"\n if [ -n \"$work_engine_mode\" ]; then\n work_engine_detail=\"standing preference is off\"\n else\n work_engine_detail=\"setting is commented or missing\"\n fi\n if [ -n \"$work_engine_preferences_error\" ]; then\n work_engine_preferences_note=\"invalid dormant work_engine_preferences: ${work_engine_preferences_error}\"\n work_engine_preferences_note_level=\"warn\"\n project_issues=$((project_issues + 1))\n elif [ \"$work_engine_preferences_count\" -gt 0 ]; then\n work_engine_preferences_note=\"ordered preferences ignored while standing mode is off\"\n fi\n ;;\n prefer|require)\n if [ -n \"$work_engine_preferences_error\" ]; then\n work_engine_cfg=\"unavailable\"\n work_engine_detail=\"$work_engine_preferences_error\"\n project_issues=$((project_issues + 1))\n elif [ \"$work_engine_preferences_count\" -eq 0 ] && [ -n \"$retired_work_engine_keys\" ]; then\n work_engine_cfg=\"unavailable\"\n work_engine_detail=\"$work_engine_mode cannot use retired scalar routing; migrate ${retired_work_engine_keys} to work_engine_preferences\"\n elif [ \"$work_engine_preferences_count\" -eq 0 ]; then\n work_engine_cfg=\"unavailable\"\n work_engine_detail=\"$work_engine_mode requires work_engine_preferences\"\n project_issues=$((project_issues + 1))\n else\n work_engine_cfg=\"$work_engine_mode\"\n work_engine_detail=\"$work_engine_preferences_detail\"\n fi\n ;;\n *)\n work_engine_cfg=\"invalid\"\n work_engine_detail=\"invalid mode '$work_engine_mode' ignored; native is the default\"\n project_issues=$((project_issues + 1))\n ;;\n esac\n\n script_dir=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n template=\"$script_dir/../references/config-template.yaml\"\n example=\"$repo_root/.compound-engineering/config.example.yaml\"\n if [ ! -f \"$example\" ]; then\n example_cfg=\"missing\"\n elif [ -f \"$template\" ] && ! diff -q \"$template\" \"$example\" >/dev/null 2>&1; then\n example_cfg=\"outdated\"\n else\n example_cfg=\"ok\"\n fi\n\n # Retired keys set as ACTIVE (non-commented) in either layer. A\n # commented `# plan_use_fable:` line does not match `^[[:space:]]*\u003ckey>:`.\n for cfg_file in \"$local_config_path\" \"$tracked_config_path\"; do\n [ -f \"$cfg_file\" ] || continue\n for key in plan_use_fable brainstorm_use_fable fable_nudge; do\n if grep -Eq \"^[[:space:]]*${key}[[:space:]]*:\" \"$cfg_file\" 2>/dev/null; then\n already=\"\"\n for seen in \"${retired_keys[@]}\"; do\n [ \"$seen\" = \"$key\" ] && already=1\n done\n [ -z \"$already\" ] && retired_keys+=(\"$key\")\n fi\n done\n done\nfi\n\n# Same runtime and helper the peer workers resolve before launching the\n# antigravity route. Reported only when the user configured it or installed it.\nantigravity_row=\"skip\"\nantigravity_problem=\"\"\nantigravity_runtime=\"$(command -v agy_acp_server.par 2>/dev/null)\"\nif [ \"$antigravity_configured\" = \"yes\" ] || [ -n \"$antigravity_runtime\" ]; then\n capability_total=$((capability_total + 1))\n antigravity_helper=\"${ANTIGRAVITY_HARNESS_PATH:-$(dirname \"${antigravity_runtime:-.}\")/localharness_external}\"\n if [ -z \"$antigravity_runtime\" ]; then\n antigravity_problem=\"agy_acp_server.par not found on PATH; install Antigravity's ACP runtime\"\n elif [ ! -x \"$antigravity_helper\" ]; then\n antigravity_problem=\"localharness_external not found at ${antigravity_helper}; install it from the same release as the runtime\"\n fi\n if [ -z \"$antigravity_problem\" ]; then\n capability_ok=$((capability_ok + 1))\n antigravity_row=\"ok\"\n else\n capability_missing=$((capability_missing + 1))\n antigravity_row=\"missing\"\n fi\nfi\n\n# =====================================================\n# Output\n# =====================================================\n\necho \"\"\nif [ -n \"$plugin_version\" ]; then\n ok \"Plugin version v${plugin_version}\"\nfi\n\nsection \"Optional capabilities ${capability_ok}/${capability_total}\"\n\nfor result in \"${results[@]}\"; do\n IFS='|' read -r name status install_cmd url capability \u003c \u003c(printf '%s\\n' \"$result\")\n if [ \"$status\" = \"ok\" ]; then\n ok \"$name -- $capability\"\n else\n warn \"$name -- unavailable: $capability\"\n if [[ \"$install_cmd\" == *\"brew install\"* ]] && [ \"$has_brew\" != \"yes\" ]; then\n detail \"$url\"\n else\n detail \"$install_cmd\"\n detail \"$url\"\n fi\n fi\ndone\n\nif [ \"$node_row\" = \"ok\" ]; then\n ok \"node -- cross-model peers (Node $node_version, npx)\"\nelse\n warn \"node -- unavailable: cross-model peers\"\n detail \"$node_problem\"\n detail \"https://nodejs.org/en/download\"\nfi\n\nif [ \"$antigravity_row\" = \"ok\" ]; then\n ok \"antigravity -- Gemini cross-model peer (runtime and helper found)\"\nelif [ \"$antigravity_row\" = \"missing\" ]; then\n warn \"antigravity -- unavailable: Gemini cross-model peer\"\n detail \"$antigravity_problem\"\n detail \"https://github.com/agentclientprotocol/registry/blob/main/antigravity-acp/agent.json\"\nfi\n\nif [ \"$legacy_codex_map\" = \"yes\" ]; then\n section \"Codex instructions\"\n warn \"Legacy Compound Codex tool map in ${codex_agents_file}\"\n detail \"Retired block from a pre-native Bun install; one line tells Codex to collapse subagent dispatch.\"\n detail \"Remove it -- see this skill's references/legacy-codex-tool-map.md\"\nfi\n\nif [ \"$in_repo\" = \"yes\" ]; then\n section \"Project config\"\n\n if [ \"$legacy_cfg\" = \"present\" ]; then\n warn \"Obsolete compound-engineering.local.md exists\"\n project_issues=$((project_issues + 1))\n else\n ok \"No obsolete compound-engineering.local.md\"\n fi\n\n if [ \"$tracked_cfg\" = \"present\" ]; then\n ok \".compound-engineering/config.yaml exists\"\n else\n skip \"No repo config yet (.compound-engineering/config.yaml)\"\n fi\n\n if [ \"$local_cfg\" = \"present\" ]; then\n ok \".compound-engineering/config.local.yaml exists\"\n if [ \"$repo_cfg_gitignore\" = \"ok\" ]; then\n ok \"Local config is gitignored\"\n else\n warn \"Local config is not safely gitignored\"\n project_issues=$((project_issues + 1))\n fi\n else\n skip \"No local override yet (.compound-engineering/config.local.yaml)\"\n fi\n\n if [ \"$scratch_gitignore\" = \"ok\" ]; then\n ok \"CE scratch space is gitignored\"\n else\n skip \"CE scratch space is not gitignored\"\n detail \"Skills that keep local scratch write it under .context/compound-engineering/\"\n fi\n\n if [ \"$docs_root_status\" = \"default\" ]; then\n ok \"Artifact root: docs/ (default — docs_root not set)\"\n elif [ \"$docs_root_status\" = \"configured\" ]; then\n ok \"Artifact root: ${docs_root_value}/ (from ${docs_root_source})\"\n elif [ \"$docs_root_status\" = \"invalid\" ]; then\n warn \"Invalid docs_root '${docs_root_value}' in ${docs_root_source}: ${docs_root_error}\"\n detail \"CE artifacts will not be written until docs_root is corrected or removed.\"\n fi\n if [ -n \"$docs_root_local_ignored\" ]; then\n skip \"Local docs_root '${docs_root_local_ignored}' is ignored; set docs_root only in config.yaml\"\n fi\n\n if [ \"$work_engine_cfg\" = \"native\" ]; then\n ok \"CE Work implementation engine: native (${work_engine_detail})\"\n if [ -n \"$work_engine_preferences_note\" ]; then\n if [ \"$work_engine_preferences_note_level\" = \"warn\" ]; then\n warn \"$work_engine_preferences_note\"\n else\n detail \"$work_engine_preferences_note\"\n fi\n fi\n elif [ \"$work_engine_cfg\" = \"prefer\" ] || [ \"$work_engine_cfg\" = \"require\" ]; then\n ok \"CE Work implementation engine: ${work_engine_cfg} -> ${work_engine_detail}\"\n elif [ \"$work_engine_cfg\" = \"unavailable\" ]; then\n warn \"CE Work implementation engine unavailable: ${work_engine_detail}\"\n elif [ \"$work_engine_cfg\" = \"invalid\" ]; then\n warn \"CE Work implementation engine: ${work_engine_detail}\"\n fi\n [ -n \"$work_engine_migration_note\" ] && warn \"$work_engine_migration_note\"\n for effort_note in ${work_engine_effort_notes[@]+\"${work_engine_effort_notes[@]}\"}; do\n warn \"$effort_note\"\n project_issues=$((project_issues + 1))\n done\n\n if [ \"$example_cfg\" = \"ok\" ]; then\n ok \"Example config is current\"\n elif [ \"$example_cfg\" = \"missing\" ]; then\n warn \"Example config missing (.compound-engineering/config.example.yaml)\"\n project_issues=$((project_issues + 1))\n elif [ \"$example_cfg\" = \"outdated\" ]; then\n warn \"Example config outdated (new settings available)\"\n project_issues=$((project_issues + 1))\n fi\n\n for key in \"${retired_keys[@]}\"; do\n case \"$key\" in\n plan_use_fable) warn \"Retired config key '$key' — removed; use 'plan_model' instead\" ;;\n brainstorm_use_fable) warn \"Retired config key '$key' — removed; use 'brainstorm_model' instead\" ;;\n fable_nudge) warn \"Retired config key '$key' — removed; model elevation is always available\" ;;\n esac\n project_issues=$((project_issues + 1))\n done\n # --- Compound Packs (packs: config key) -------------------------------------\n section \"Compound Packs\"\n packs_python=\"$(for c in python3 python py; do command -v \"$c\" >/dev/null 2>&1 && \"$c\" -c '' >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\"\n packs_resolver=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/packs-resolve.py\"\n if [ -z \"$packs_python\" ]; then\n skip \"No Python interpreter found; pack health not checked\"\n elif [ ! -f \"$packs_resolver\" ]; then\n skip \"packs-resolve.py not found beside check-health; pack health not checked\"\n else\n packs_json=\"$(\"$packs_python\" \"$packs_resolver\" 2>/dev/null)\"\n if [ -z \"$packs_json\" ]; then\n warn \"packs-resolve.py failed to run\"\n project_issues=$((project_issues + 1))\n else\n packs_report=\"$(printf '%s' \"$packs_json\" | \"$packs_python\" -c '\nimport json, os, re, subprocess, sys\ndata = json.load(sys.stdin)\nroots, errors, warns = data.get(\"roots\", []), data.get(\"errors\", []), data.get(\"warnings\", [])\nif not roots and not errors and not warns:\n print(\"SKIP\\tNo packs configured\")\nfor r in roots:\n line = \"OK\\tpack \" + r[\"id\"]\n url, ref = r.get(\"url\"), r.get(\"ref\")\n if url and ref:\n line += \" (\" + ref + \")\"\n # Only a full commit id is immutable. A branch tip advances and a tag can\n # be force-moved upstream, so for either compare the cached HEAD with the\n # remote target of that name -- the peeled commit for an annotated tag,\n # which is why the ls-remote asks for `\u003ctag>^{}` too.\n if not re.fullmatch(r\"[0-9a-f]{40}|[0-9a-f]{64}\", ref):\n try:\n genv = dict(os.environ)\n genv[\"GIT_TERMINAL_PROMPT\"] = \"0\"\n genv.setdefault(\"GIT_ASKPASS\", \"true\")\n _ssh = genv.get(\"GIT_SSH_COMMAND\") or \"ssh\"\n if \"BatchMode\" not in _ssh:\n genv[\"GIT_SSH_COMMAND\"] = _ssh + \" -o BatchMode=yes\"\n names = [\"refs/tags/\" + ref + \"^{}\", \"refs/tags/\" + ref, \"refs/heads/\" + ref]\n remote = subprocess.run([\"git\", \"ls-remote\", \"--end-of-options\", url, *names],\n capture_output=True, text=True, timeout=10, env=genv)\n targets = {}\n for row in remote.stdout.splitlines() if remote.returncode == 0 else []:\n sha, _, name = row.partition(\"\\t\")\n if name:\n targets[name] = sha\n rsha = next((targets[n] for n in names if n in targets), \"\")\n local = subprocess.run([\"git\", \"-C\", r[\"dir\"], \"rev-parse\", \"HEAD\"], capture_output=True, text=True, timeout=10)\n lsha = local.stdout.strip() if local.returncode == 0 else \"\"\n if rsha and lsha and rsha != lsha:\n line += \" -- cached resolution is behind upstream\"\n except Exception:\n pass # offline or slow remote: silently skip the drift note\n # Subdirectories are storage, so rule-shaped files there are a note on the\n # OK line, never a warning: the author may keep drafts and evidence with frontmatter.\n nested = r.get(\"nested_rule_shaped\", 0)\n if nested:\n line += \" -- \" + str(nested) + \" rule-shaped file(s) in subfolders kept as storage\"\n print(line)\nfor w in warns:\n print(\"WARN\\t\" + w)\nfor e in errors:\n print(\"ERROR\\t\" + e)\n')\"\n while IFS=

Compound Engineering Setup Interaction Method Ask each question below using the host's blocking question tool already in the current tool list (match by capability, not by a host-specific name). Presence in the current tool list is proof the tool exists; never call a user-facing question tool to discover whether it exists. If a matching tool is listed but unloaded, use the host's tool-discovery primitive to load that capability — do not search for another host's tool name. Fall back to a numbered list on the host's user-visible chat surface only when no such tool is in the list or a real ques…

\\t' read -r kind msg; do\n [ -z \"$kind\" ] && continue\n case \"$kind\" in\n OK) ok \"$msg\" ;;\n SKIP) skip \"$msg\" ;;\n WARN) warn \"$msg\" ;;\n ERROR) warn \"Pack config error: $msg\"; project_issues=$((project_issues + 1)) ;;\n esac\n done \u003c \u003c(printf '%s\\n' \"$packs_report\")\n fi\n fi\nelse\n section \"Project config\"\n skip \"Not inside a git repository\"\nfi\n\necho \"\"\nif [ \"$project_issues\" -eq 0 ]; then\n echo \" ✅ Project config healthy. Optional capabilities available: ${capability_ok}/${capability_total}\"\nelse\n echo \" ⚠️ ${project_issues} project issue(s) found. Optional capabilities available: ${capability_ok}/${capability_total}\"\nfi\n\nif [ \"$legacy_codex_map\" = \"yes\" ]; then\n echo \" Environment: the legacy Codex tool map above still needs attention.\"\nfi\n\nif [ \"$capability_missing\" -gt 0 ]; then\n echo \" Missing optional tools do not block setup; install them only for the workflows you use.\"\nfi\n\necho \"\"\n","content_type":"text/plain; charset=utf-8","language":null,"size":36346,"content_sha256":"b9b934bdb0df953a32cb0fbf24b254d8714e5aaacfd1e5e4bfb35a816c17990e"},{"filename":"scripts/packs-resolve.py","content":"#!/usr/bin/env python3\n\"\"\"Resolve the Compound Packs declared in this repo's CE config into pack roots.\n\nReads the `packs:` list from `\u003crepo-root>/.compound-engineering/config.yaml`\nand `config.local.yaml` (both layers concatenate; local adds, never replaces),\nvalidates each entry, resolves path and git sources, enumerates the packs each\nsource publishes, applies selection, and prints one JSON object to stdout:\n\n {\"roots\": [{\"id\": \"...\", \"dir\": \"/abs/path\", \"nested_rule_shaped\": 0}],\n \"warnings\": [...], \"errors\": [...], \"entries\": \u003cnumber of parsed packs entries>}\n\n`nested_rule_shaped` counts the rule-shaped `.md` files one level below the\npack's top level. Discovery never reads them (subdirectories are storage), so\nthe count is informational and is reported by the health check, not warned.\n\nExit 0 whenever resolution ran (per-entry failures are data in `errors` /\n`warnings`); non-zero only when the resolver itself cannot run. Consumers treat\n`errors` as loud per-entry configuration problems and `warnings` as degraded\navailability (e.g. an unreachable git source skipped per the warn-and-continue\ncontract).\n\n`--declared-only` answers the config-only question without touching git or the\ncache: it parses both config layers, shape-checks each entry, and prints\n\n {\"declared\": \u003cbool|null>, \"entries\": \u003cn>, \"errors\": [...]}\n\nwhere `declared` is true when any entry parsed or the `packs:` block is\nmalformed (a broken declaration is still a declaration the consumer should\nsurface), false when neither config layer names packs, and null when no\nrepository -- and so no config -- could be located.\n\nEntry shape (documented subset -- anything else under `packs:` is a loud error):\n\n packs:\n - source: packs/local-rules # repo-relative path\n - source: ~/packs/kk-style # ~ or absolute path\n - source: https://github.com/o/r # git URL: ref required\n ref: v1.2.0 # tag, sha, or branch\n path: packs # optional subfolder (git only)\n pack: [rails, inertia] # one id, a list, or omit = all\n id: rails-core # rename (single-pack entries)\n - source: https://github.com/o/r/tree/main/packs # tree-URL sugar\n\nGit sources cache under `\u003cscratch-root>/ce-packs/\u003csha256(url\\\\nref)>` with an\natomic temp-clone-then-rename, so a keyed path's existence proves a complete\nclone. All git subprocesses run non-interactively (GIT_TERMINAL_PROMPT=0, ssh\nBatchMode, bounded timeout): missing credentials degrade to a warning, never a\nhang. A missing `git` binary degrades git sources only (each warns and is\nskipped); path sources still resolve, with the repository located by walking up\nfrom the working directory to the nearest `.git` entry. Environment overrides:\nCE_PACKS_CACHE_ROOT (cache base for tests), CE_PACKS_GIT_TIMEOUT (seconds,\ndefault 60).\n\nA published pack is a directory a consumer lists and reads itself, so nothing\nin it may link outside its source: a pack whose tree holds such a link is not\npublished (a loud per-entry error), never trimmed a file at a time.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport functools\nimport hashlib\nimport json\nimport os\nimport re\nimport shutil\nimport stat\nimport subprocess\nimport sys\nimport tempfile\n\nIS_WINDOWS = os.name == \"nt\"\n_uid_getter = getattr(os, \"geteuid\", None) or getattr(os, \"getuid\", None)\n_EFFECTIVE_UID = _uid_getter() if _uid_getter is not None else None\nGIT_TIMEOUT = float(os.environ.get(\"CE_PACKS_GIT_TIMEOUT\") or 60)\n\nCONFIG_FILES = (\"config.yaml\", \"config.local.yaml\")\nKNOWN_KEYS = {\"source\", \"ref\", \"path\", \"pack\", \"id\"}\nSCALAR_KEYS = (\"source\", \"ref\", \"path\", \"id\") # every known key but the list-valued `pack`\n_TREE_URL_RE = re.compile(\n r\"^(?P\u003cbase>https?://github\\.com/[^/\\s]+/[^/\\s]+?)(?:\\.git)?/tree/(?P\u003cref>[^/\\s]+)(?:/(?P\u003cpath>[^\\s]*))?/?$\"\n)\n\n\ndef _is_git_url(source: str) -> bool:\n return bool(\n re.match(r\"^(https?|ssh|git|file)://\", source) or re.match(r\"^[\\w.-]+@[\\w.-]+:\", source)\n )\n\n\ndef _within(path: str, parent: str) -> bool:\n \"\"\"True when `path` is `parent` or lies below it (both already realpath'd).\"\"\"\n return path == parent or path.startswith(parent + os.sep)\n\n\n# --- scratch root (peer-job-runner shape: probe /tmp, fall back to TMPDIR) ---\n\ndef _owned_dir(path: str) -> bool:\n \"\"\"Directory, not a symlink, owned by the effective uid (POSIX).\"\"\"\n try:\n st = os.lstat(path)\n except OSError:\n return False\n if not stat.S_ISDIR(st.st_mode):\n return False\n if _EFFECTIVE_UID is not None and st.st_uid != _EFFECTIVE_UID:\n return False\n return True\n\n\ndef _private_root_usable(path: str) -> bool:\n \"\"\"Create or repair `path` as a private (0700) root owned by this user.\"\"\"\n try:\n os.mkdir(path, 0o700)\n except FileExistsError:\n pass\n except OSError:\n return False\n if not IS_WINDOWS:\n if not _owned_dir(path):\n return False\n try:\n os.chmod(path, 0o700)\n except OSError:\n return False\n return os.path.isdir(path) and os.access(path, os.W_OK)\n\n\ndef _trusted_checkout(path: str) -> bool:\n \"\"\"A real directory (never a symlink) that this user owns; ownership is POSIX-only.\"\"\"\n if os.path.islink(path) or not os.path.isdir(path):\n return False\n return IS_WINDOWS or _owned_dir(path)\n\n\[email protected]_cache(maxsize=None)\ndef cache_base() -> str | None:\n configured = os.environ.get(\"CE_PACKS_CACHE_ROOT\")\n if configured:\n root = os.path.abspath(configured)\n os.makedirs(root, exist_ok=True)\n return root\n if IS_WINDOWS:\n base = os.environ.get(\"LOCALAPPDATA\") or tempfile.gettempdir()\n root = os.path.join(base, \"compound-engineering-packs\")\n return root if _private_root_usable(root) else None\n if _EFFECTIVE_UID is None:\n return None\n for base in (\"/tmp\", os.environ.get(\"TMPDIR\") or \"/tmp\"):\n root = os.path.join(base, f\"compound-engineering-{_EFFECTIVE_UID}\")\n if _private_root_usable(root):\n packs = os.path.join(root, \"ce-packs\")\n if _private_root_usable(packs):\n return packs\n return None\n\n\n# --- minimal YAML reader for the documented packs: subset --------------------\n\ndef _strip_comment(line: str) -> str:\n \"\"\"Drop a trailing comment (a # preceded by whitespace, outside quotes).\n\n A quote toggles quoted state only when it opens a value (start of line or\n after `: `/`- `/`[`/`,`) or closes one it opened -- a mid-word apostrophe\n (``it's``) is ordinary content and must not absorb a later comment.\n \"\"\"\n out, quote = [], \"\"\n for i, ch in enumerate(line):\n prev = line[i - 1] if i else \" \"\n if quote:\n if ch == quote:\n quote = \"\"\n elif ch in \"'\\\"\" and prev in \" \\t[,:\":\n quote = ch\n elif ch == \"#\" and prev in \" \\t\":\n break\n out.append(ch)\n return \"\".join(out).rstrip()\n\n\ndef _scalar(raw: str):\n raw = raw.strip()\n if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in \"'\\\"\":\n return raw[1:-1]\n if raw.lower() in (\"true\", \"false\"):\n return raw.lower() == \"true\"\n return raw\n\n\ndef _parse_value(raw: str):\n raw = raw.strip()\n if raw.startswith(\"[\") and raw.endswith(\"]\"):\n inner = raw[1:-1].strip()\n return [] if not inner else [_scalar(part) for part in inner.split(\",\")]\n return _scalar(raw)\n\n\ndef parse_packs_block(path: str, errors: list) -> list:\n \"\"\"Return the entry dicts under this file's top-level `packs:` key.\"\"\"\n if not os.path.isfile(path):\n return []\n with open(path, encoding=\"utf-8-sig\", errors=\"replace\") as fh:\n lines = fh.read().splitlines()\n entries, in_packs, current, pending_list_key = [], False, None, None\n for lineno, raw in enumerate(lines, 1):\n line = _strip_comment(raw)\n if not line.strip():\n continue\n indent = len(line) - len(line.lstrip())\n if indent == 0 and not (in_packs and line.lstrip().startswith(\"-\")):\n # A new top-level key ends the packs block; a zero-indent list item\n # (`- source: ...`) is still part of it -- YAML allows both styles.\n key, sep, rest = line.partition(\":\")\n in_packs = bool(sep) and key.strip() == \"packs\" and rest.strip() in (\"\", \"[]\")\n if sep and key.strip() == \"packs\" and not in_packs:\n # `packs: \u003cinline value>` is malformed, not absent: say so rather\n # than letting a flow list or a bare path declare nothing.\n errors.append(\n f\"{os.path.basename(path)}:{lineno}: `packs:` must be a block list of\"\n f\" `- source: ...` entries (got `{line.strip()}`)\"\n )\n current, pending_list_key = None, None\n continue\n if not in_packs:\n continue\n stripped = line.strip()\n loc = f\"{os.path.basename(path)}:{lineno}\"\n if stripped.startswith(\"- \") or stripped == \"-\":\n body = stripped[1:].strip()\n if pending_list_key and current is not None and \":\" not in body:\n current[pending_list_key].append(_scalar(body))\n continue\n current, pending_list_key = {\"_origin\": os.path.basename(path), \"_line\": lineno}, None\n entries.append(current)\n if body:\n if \":\" not in body:\n errors.append(f\"{loc}: unrecognized packs entry `{stripped}` -- expected `key: value`\")\n continue\n key, _, val = body.partition(\":\")\n _set_key(current, key.strip(), val, loc, errors)\n continue\n if current is None:\n errors.append(f\"{loc}: unrecognized line under packs: `{stripped}` -- expected a `- source: ...` entry\")\n continue\n if \":\" not in stripped:\n errors.append(f\"{loc}: unrecognized line under packs: `{stripped}` -- expected `key: value`\")\n continue\n key, _, val = stripped.partition(\":\")\n key = key.strip()\n if val.strip() == \"\" and key == \"pack\":\n current[key] = []\n pending_list_key = key\n continue\n pending_list_key = None\n _set_key(current, key, val, loc, errors)\n return entries\n\n\ndef _set_key(entry: dict, key: str, raw_val: str, loc: str, errors: list) -> None:\n if key not in KNOWN_KEYS:\n errors.append(f\"{loc}: unknown packs entry key `{key}:` -- accepted keys: {', '.join(sorted(KNOWN_KEYS))}\")\n return\n entry[key] = _parse_value(raw_val)\n\n\n# --- git ---------------------------------------------------------------------\n\[email protected]_cache(maxsize=None)\ndef _git_env() -> dict:\n env = dict(os.environ)\n env[\"GIT_TERMINAL_PROMPT\"] = \"0\"\n env[\"GIT_ASKPASS\"] = env.get(\"GIT_ASKPASS\") or \"true\"\n ssh = env.get(\"GIT_SSH_COMMAND\") or \"ssh\"\n if \"BatchMode\" not in ssh:\n env[\"GIT_SSH_COMMAND\"] = ssh + \" -o BatchMode=yes\"\n return env\n\n\ndef _run_git(args: list, cwd: str | None = None):\n return subprocess.run(\n [\"git\", *args], cwd=cwd, env=_git_env(), timeout=GIT_TIMEOUT,\n capture_output=True, text=True,\n )\n\n\ndef resolve_git_source(url: str, ref: str, warnings: list, label: str) -> str | None:\n \"\"\"Return the cached checkout dir for url@ref, cloning on miss. None = warn+skip.\"\"\"\n if shutil.which(\"git\") is None:\n warnings.append(f\"{label}: git binary not found; source skipped\")\n return None\n base = cache_base()\n if base is None:\n warnings.append(f\"{label}: no writable cache root for git sources; source skipped\")\n return None\n key = hashlib.sha256(f\"{url}\\n{ref}\".encode()).hexdigest()\n dest = os.path.join(base, key)\n if os.path.lexists(dest):\n if _trusted_checkout(dest):\n return dest\n warnings.append(f\"{label}: cached checkout {dest} is a symlink or not owned by this user; refetching\")\n # rmtree refuses to follow a symlink (and ignores a plain file); unlink\n # those explicitly so a planted link is removed, never its target.\n shutil.rmtree(dest, ignore_errors=True)\n if os.path.islink(dest) or os.path.isfile(dest):\n try:\n os.unlink(dest)\n except OSError:\n pass\n if os.path.lexists(dest):\n warnings.append(f\"{label}: cannot replace untrusted cached checkout {dest}; source skipped\")\n return None\n tmp = tempfile.mkdtemp(prefix=f\"{key}.part-\", dir=base)\n try:\n try:\n proc = _run_git([\"clone\", \"--quiet\", \"--depth\", \"1\", \"--no-recurse-submodules\",\n \"--branch\", ref, \"--end-of-options\", url, tmp])\n except subprocess.TimeoutExpired:\n warnings.append(f\"{label}: git clone timed out after {int(GIT_TIMEOUT)}s; source skipped\")\n return None\n if proc.returncode != 0:\n # tag/branch clone failed -- retry treating ref as a commit sha\n try:\n fetched = (\n _run_git([\"init\", \"--quiet\", tmp]).returncode == 0\n and _run_git([\"fetch\", \"--quiet\", \"--depth\", \"1\", \"--end-of-options\", url, ref], cwd=tmp).returncode == 0\n and _run_git([\"checkout\", \"--quiet\", \"FETCH_HEAD\"], cwd=tmp).returncode == 0\n )\n if not fetched:\n warnings.append(f\"{label}: cannot fetch `{ref}` from {url}; source skipped\")\n return None\n except subprocess.TimeoutExpired:\n warnings.append(f\"{label}: git fetch timed out after {int(GIT_TIMEOUT)}s; source skipped\")\n return None\n if not os.path.lexists(dest):\n try:\n os.replace(tmp, dest)\n except OSError:\n # Expected when another resolver published the same key\n # concurrently; anything else leaves no checkout to return.\n if not os.path.lexists(dest):\n warnings.append(f\"{label}: could not publish the clone to {dest}; source skipped\")\n return None\n if _trusted_checkout(dest):\n return dest\n warnings.append(\n f\"{label}: cached checkout {dest} appeared during the clone and is a symlink or not owned by this user; source skipped\"\n )\n return None\n finally:\n if os.path.isdir(tmp):\n shutil.rmtree(tmp, ignore_errors=True)\n\n\n# --- pack enumeration --------------------------------------------------------\n\n_FRONTMATTER_KEYS = (\"title:\", \"applies_when:\")\n_FRONTMATTER_CAP = 64 * 1024 # frontmatter must close within this many characters\n# A pack's README is its description, never a rule, whatever frontmatter it\n# carries: it is not published, not reported as skipped, and not counted.\n_README = \"readme.md\"\n\n\[email protected]_cache(maxsize=None)\ndef _is_knowledge_file(path: str) -> bool:\n \"\"\"True when the file opens with a `---` frontmatter block, closed by a `---`\n line within the cap, that carries `title:` and `applies_when:`. A UTF-8 BOM\n is not part of the content.\"\"\"\n try:\n with open(path, encoding=\"utf-8-sig\", errors=\"replace\") as fh:\n lines = fh.read(_FRONTMATTER_CAP).splitlines()\n except OSError:\n return False\n if not lines or lines[0].strip() != \"---\":\n return False\n for end, line in enumerate(lines[1:], 1):\n if line.strip() == \"---\":\n fm = \"\\n\".join(lines[1:end])\n break\n else:\n return False\n return all(re.search(rf\"^\\s*{re.escape(k)}\", fm, re.MULTILINE) for k in _FRONTMATTER_KEYS)\n\n\ndef _contained_md_files(directory: str, boundary: str, escaped: list) -> list:\n \"\"\"Paths of the `.md` entries directly under `directory`, minus its README,\n whose real path stays within `boundary` (a realpath). An entry that links\n outside it is appended to `escaped` and never opened, so a pack cannot read\n files off the user's machine.\"\"\"\n try:\n names = sorted(os.listdir(directory))\n except OSError:\n return []\n files = []\n for name in names:\n if not name.endswith(\".md\") or name.lower() == _README:\n continue\n child = os.path.join(directory, name)\n if _within(os.path.realpath(child), boundary):\n files.append(child)\n else:\n escaped.append(child)\n return files\n\n\ndef _contained_child_dirs(directory: str, boundary: str, escaped: list) -> list:\n \"\"\"`(name, path)` of the non-hidden directories directly under `directory`\n whose real path stays within `boundary`; one that links outside it is\n appended to `escaped` and never entered.\"\"\"\n try:\n names = sorted(os.listdir(directory))\n except OSError:\n return []\n dirs = []\n for name in names:\n child = os.path.join(directory, name)\n if name.startswith(\".\") or not os.path.isdir(child):\n continue\n if _within(os.path.realpath(child), boundary):\n dirs.append((name, child))\n else:\n escaped.append(child)\n return dirs\n\n\ndef _has_knowledge_files(directory: str, boundary: str, escaped: list) -> bool:\n return any(_is_knowledge_file(f) for f in _contained_md_files(directory, boundary, escaped))\n\n\ndef _escaping_links(root: str, boundary: str) -> list:\n \"\"\"Symlinks anywhere under `root` (walked without following links) whose real\n path leaves `boundary`, sorted. Only a link can leave: every other entry sits\n under `root`, which is already inside the boundary.\"\"\"\n leaks = []\n for dirpath, dirnames, filenames in os.walk(root, followlinks=False):\n for name in dirnames + filenames:\n child = os.path.join(dirpath, name)\n if os.path.islink(child) and not _within(os.path.realpath(child), boundary):\n leaks.append(child)\n return sorted(leaks)\n\n\ndef enumerate_packs(source_root: str, boundary: str, escaped: list, self_name: str | None = None) -> dict:\n \"\"\"Map published pack id -> dir. Immediate children only; self = single pack.\n\n `boundary` is the realpath every child directory and rule file must stay\n within (the git checkout, the repository, or the source root itself); a\n child that links outside it is recorded in `escaped` and skipped. Symlinks\n that stay inside the boundary are ordinary content.\n \"\"\"\n if _has_knowledge_files(source_root, boundary, escaped):\n name = self_name or os.path.basename(os.path.abspath(source_root))\n return {name: source_root}\n return {\n name: child\n for name, child in _contained_child_dirs(source_root, boundary, escaped)\n if _has_knowledge_files(child, boundary, escaped)\n }\n\n\ndef nested_rule_shaped(pack_dir: str, boundary: str) -> tuple:\n \"\"\"`(total, subdirs)`: how many rule-shaped files sit in the immediate\n subdirectories of `pack_dir`, and which subdirectories hold them. Scans one\n level down only, inside `boundary`, so the pack's data is never walked.\n Subdirectories are storage, so these files are counted, never published.\"\"\"\n hits, total = [], 0\n for name, child in _contained_child_dirs(pack_dir, boundary, []):\n count = sum(1 for f in _contained_md_files(child, boundary, []) if _is_knowledge_file(f))\n if count:\n hits.append(name)\n total += count\n return total, hits\n\n\ndef nested_rules_warning(pack_id: str, pack_dir: str, boundary: str) -> str | None:\n \"\"\"The warning for a pack directory with no rule at its top level whose\n subdirectories hold rule-shaped files: it registers, yet nothing can ever be\n discovered. None when the subdirectories hold none. The caller establishes\n that the top level is empty of rules; a pack with top-level rules keeps its\n nested files as storage and gets `nested_rule_shaped` instead.\"\"\"\n total, hits = nested_rule_shaped(pack_dir, boundary)\n if not hits:\n return None\n where = \", \".join(f\"`{name}/`\" for name in hits)\n return (\n f\"pack `{pack_id}` has {total} rule-shaped file(s) under {where} that discovery\"\n \" never reads -- move rules to the pack's top level (see https://everyinc.github.io/compound-engineering-plugin/guides/packs/, Pack layout)\"\n )\n\n\n# --- entry resolution --------------------------------------------------------\n\ndef _entry_label(entry: dict) -> str:\n return f\"{entry.get('_origin', 'config')}:{entry.get('_line', '?')}\"\n\n\ndef _entry_shape_ok(entry: dict, label: str, errors: list) -> bool:\n \"\"\"I/O-free checks on one parsed entry: `source:` present, and the scalar\n keys actually scalar. False after appending the error.\"\"\"\n for key in SCALAR_KEYS:\n val = entry.get(key)\n if val is not None and not isinstance(val, str):\n errors.append(f\"{label}: `{key}:` must be a single string (got {val!r})\")\n return False\n if not entry.get(\"source\"):\n errors.append(f\"{label}: entry has no `source:`\")\n return False\n return True\n\n\ndef resolve_entry(entry: dict, repo_root: str, roots: list, warnings: list, errors: list) -> None:\n label = _entry_label(entry)\n if not _entry_shape_ok(entry, label, errors):\n return\n source, ref, sub_path = entry[\"source\"], entry.get(\"ref\"), entry.get(\"path\")\n\n tree = _TREE_URL_RE.match(source)\n if tree:\n t_ref, t_path = tree.group(\"ref\"), tree.group(\"path\") or \"\"\n if isinstance(ref, str) and ref != t_ref:\n errors.append(f\"{label}: tree URL pins ref `{t_ref}` but entry says `ref: {ref}` -- remove one\")\n return\n if isinstance(sub_path, str) and sub_path.strip(\"/\") != t_path.strip(\"/\"):\n errors.append(f\"{label}: tree URL path `{t_path}` conflicts with `path: {sub_path}` -- remove one\")\n return\n source, ref, sub_path = tree.group(\"base\"), t_ref, t_path or None\n\n if _is_git_url(source):\n if not isinstance(ref, str) or not ref:\n errors.append(f\"{label}: git source `{source}` requires `ref:` (tag, sha, or branch)\")\n return\n if ref.startswith(\"-\") or source.startswith(\"-\"):\n errors.append(f\"{label}: git source/ref may not begin with `-`\")\n return\n checkout = resolve_git_source(source, ref, warnings, label)\n if checkout is None:\n if tree:\n warnings.append(\n f\"{label}: if the branch name contains `/`, tree-URL parsing splits it wrong -- use explicit `ref:` and `path:` fields\"\n )\n return\n git_meta = {\"url\": source, \"ref\": ref}\n source_root = os.path.join(checkout, sub_path) if sub_path else checkout\n real_root, real_checkout = os.path.realpath(source_root), os.path.realpath(checkout)\n if not _within(real_root, real_checkout):\n errors.append(f\"{label}: path `{sub_path}` escapes the source checkout\")\n return\n source_root, boundary = real_root, real_checkout\n if not os.path.isdir(source_root):\n errors.append(f\"{label}: path `{sub_path}` does not exist in {source}@{ref}\")\n return\n else:\n git_meta = None\n if ref is not None:\n errors.append(f\"{label}: `ref:` is only valid on git sources; path sources are read live\")\n return\n if sub_path is not None:\n errors.append(f\"{label}: `path:` is only valid on git sources; point `source:` at the directory instead\")\n return\n expanded = os.path.expanduser(source)\n if os.path.isabs(expanded):\n source_root = os.path.realpath(expanded)\n boundary = source_root\n else:\n source_root = os.path.realpath(os.path.join(repo_root, expanded))\n repo_real = os.path.realpath(repo_root)\n if not _within(source_root, repo_real) or _within(source_root, os.path.join(repo_real, \".git\")):\n errors.append(f\"{label}: repo-relative source `{source}` resolves outside the repository\")\n return\n boundary = repo_real\n if not os.path.isdir(source_root):\n errors.append(f\"{label}: source directory `{source}` does not exist\")\n return\n\n if git_meta:\n # Display name for a single-pack git source: the path: subfolder's\n # basename, else the URL's last path segment (never the cache key).\n tail = (sub_path or source).rstrip(\"/\").rsplit(\"/\", 1)[-1]\n self_name = re.sub(r\"\\.git$\", \"\", tail.split(\":\")[-1]) or None\n else:\n self_name = None\n escaped = []\n published = enumerate_packs(source_root, boundary, escaped, self_name)\n for link in escaped:\n warnings.append(\n f\"{label}: skipped `{os.path.relpath(link, source_root)}` in `{source}` -- it links outside the source\"\n )\n if not published:\n warnings.append(f\"{label}: source `{source}` publishes no packs (no directories with valid knowledge files)\")\n # Each child directory is a would-be pack with no top-level rule (one\n # with a rule would have published); say when its rules sit one level\n # too deep, so the author learns why nothing published.\n for name, child in _contained_child_dirs(source_root, boundary, []):\n nested = nested_rules_warning(name, child, boundary)\n if nested:\n warnings.append(f\"{label}: {nested}\")\n return\n\n selection = entry.get(\"pack\")\n if selection is None:\n selected = dict(published)\n else:\n wanted = selection if isinstance(selection, list) else [selection]\n if not wanted:\n warnings.append(f\"{label}: `pack:` lists no ids; nothing installed from `{source}`\")\n return\n missing = [w for w in wanted if w not in published]\n if missing:\n errors.append(\n f\"{label}: pack id(s) {', '.join(map(str, missing))} not published by `{source}`\"\n f\" -- available: {', '.join(sorted(published)) or 'none'}\"\n )\n return\n selected = {w: published[w] for w in wanted}\n\n override = entry.get(\"id\")\n if override is not None:\n if len(selected) != 1:\n errors.append(f\"{label}: `id:` override requires the entry to install exactly one pack\")\n return\n selected = {str(override): next(iter(selected.values()))}\n\n for pack_id, pack_dir in selected.items():\n # Consumers list the pack directory themselves, so a link that leaves\n # the source anywhere inside it would let pack content read files off\n # the user's machine: refuse the whole pack. (Top-level escapes were\n # already named as skipped during enumeration.)\n leaks = _escaping_links(pack_dir, boundary)\n if leaks:\n names = \", \".join(f\"`{os.path.relpath(p, pack_dir)}`\" for p in leaks)\n errors.append(f\"{label}: pack `{pack_id}` not published -- {names} link(s) outside the source\")\n continue\n for child in _contained_md_files(pack_dir, boundary, []):\n name = os.path.basename(child)\n if os.path.isfile(child) and not _is_knowledge_file(child):\n warnings.append(\n f\"{label}: skipped pack file `{pack_id}/{name}` (missing `title`/`applies_when` frontmatter)\"\n )\n # A published pack has a rule at its top level, so rule-shaped files in\n # its subdirectories are storage: counted for the health report, not warned.\n nested_total, _ = nested_rule_shaped(pack_dir, boundary)\n root = {\"id\": pack_id, \"dir\": pack_dir, \"nested_rule_shaped\": nested_total, \"_label\": label}\n if git_meta:\n root.update(git_meta)\n roots.append(root)\n\n\ndef _emit(declared_only: bool, entries: list, roots: list, warnings: list, errors: list,\n declared: bool | None = None) -> int:\n if declared_only:\n print(json.dumps({\"declared\": declared, \"entries\": len(entries), \"errors\": errors}))\n else:\n print(json.dumps({\n \"roots\": [{k: v for k, v in r.items() if not k.startswith(\"_\")} for r in roots],\n \"warnings\": warnings,\n \"errors\": errors,\n \"entries\": len(entries),\n }))\n return 0\n\n\ndef _repo_root() -> str | None:\n \"\"\"The enclosing checkout's top level: git's answer when git is on PATH,\n otherwise the nearest ancestor of the working directory holding a `.git`\n entry (a directory, or the file a worktree or submodule leaves). None when\n the working directory is not inside a checkout.\"\"\"\n if shutil.which(\"git\") is not None:\n proc = subprocess.run([\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)\n return proc.stdout.strip() if proc.returncode == 0 else None\n current = os.getcwd()\n while True:\n if os.path.lexists(os.path.join(current, \".git\")):\n return current\n parent = os.path.dirname(current)\n if parent == current:\n return None\n current = parent\n\n\ndef _main(argv: list) -> int:\n parser = argparse.ArgumentParser(description=\"Resolve the Compound Packs declared in CE config.\")\n parser.add_argument(\n \"--declared-only\", action=\"store_true\",\n help=\"parse and shape-check the packs: entries only; no git or cache work\",\n )\n args = parser.parse_args(argv)\n warnings, errors, roots, entries = [], [], [], []\n\n repo_root = _repo_root()\n if repo_root is None:\n warnings.append(\"not inside a git repository; no CE config to read\")\n return _emit(args.declared_only, entries, roots, warnings, errors)\n cfg_dir = os.path.join(repo_root, \".compound-engineering\")\n for name in CONFIG_FILES:\n entries.extend(parse_packs_block(os.path.join(cfg_dir, name), errors))\n\n if args.declared_only:\n for entry in entries:\n _entry_shape_ok(entry, _entry_label(entry), errors)\n return _emit(True, entries, roots, warnings, errors, declared=bool(entries or errors))\n\n for entry in entries:\n try:\n resolve_entry(entry, repo_root, roots, warnings, errors)\n except Exception as exc: # one entry's surprise is that entry's error, not everyone's\n errors.append(f\"{_entry_label(entry)}: unexpected error resolving entry: {exc}\")\n\n # First declaration wins: config.yaml entries precede config.local.yaml in\n # CONFIG_FILES, so a personal pack can never displace the team's.\n by_id = {}\n final = []\n for root in roots:\n prev = by_id.get(root[\"id\"])\n if prev is not None:\n errors.append(\n f\"duplicate pack id `{root['id']}`: {root['_label']} ignored, {prev['_label']} kept\"\n \" -- rename one with `id:`\"\n )\n continue\n by_id[root[\"id\"]] = root\n final.append(root)\n return _emit(False, entries, final, warnings, errors)\n\n\ndef main() -> int:\n try:\n return _main(sys.argv[1:])\n except Exception as exc: # never a traceback: consumers need valid JSON\n print(json.dumps({\n \"roots\": [], \"warnings\": [], \"errors\": [f\"packs resolver failed unexpectedly: {exc}\"], \"entries\": 0,\n }))\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","content_type":"text/x-python; charset=utf-8","language":"python","size":31561,"content_sha256":"39c36946cd1a59ca564e60e4e049934831eb4bfb5cfce9de32ab6b4b522ef228"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Compound Engineering Setup","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Interaction Method","type":"text"}]},{"type":"paragraph","content":[{"text":"Ask each question below using the host's blocking question tool already in the current tool list (match by capability, not by a host-specific name). Presence in the current tool list is proof the tool exists; never call a user-facing question tool to discover whether it exists. If a matching tool is listed but unloaded, use the host's tool-discovery primitive to load that capability — do not search for another host's tool name. Fall back to a numbered list on the host's user-visible chat surface only when no such tool is in the list or a real question call errors. Never silently skip or auto-configure.","type":"text"}]},{"type":"paragraph","content":[{"text":"ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" is a lightweight health check and repo-local config helper. It does ","type":"text"},{"text":"not","type":"text","marks":[{"type":"strong"}]},{"text":" bulk-install every optional dependency. Missing tools are reported as optional capabilities so the user can install only the workflows they use.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Pack Scaffold","type":"text"}]},{"type":"paragraph","content":[{"text":"When the invocation names a Compound Pack to add, create, or scaffold (the ","type":"text"},{"text":"pack:\u003cid>","type":"text","marks":[{"type":"code_inline"}]},{"text":" argument, or the same request in words), read ","type":"text"},{"text":"references/pack-scaffold.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" from this skill's directory and follow it in place of Phases 1-2 (Diagnose and Fix Repo-Local Issues): it writes the pack and its config entry only after the user approves, runs the health check itself, and reports into Phase 3 (Summary).","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Review Docs","type":"text"}]},{"type":"paragraph","content":[{"text":"When the invocation asks to draft, refresh, or update coding standards or review docs (the ","type":"text"},{"text":"standards","type":"text","marks":[{"type":"code_inline"}]},{"text":" argument, or the same request in words), read ","type":"text"},{"text":"references/project-docs.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" and follow it in place of Phases 1-2, drafting the whole set of files even when the request names one. Report into Phase 3.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Artifact Root Resolution","type":"text"}]},{"type":"paragraph","content":[{"text":"Every Compound Engineering skill that writes or reads an artifact directory (","type":"text"},{"text":"solutions","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"plans","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"ideation","type":"text","marks":[{"type":"code_inline"}]},{"text":", and the other CE-owned trees) resolves its root through the rule below. ","type":"text"},{"text":"ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" carries the canonical statement and reports the resolved root so an operator can confirm where artifacts land before running other skills.","type":"text"}]},{"type":"paragraph","content":[{"text":"\u003c!-- ce-docs-root:start --> ","type":"text"},{"text":"Resolve the CE artifact root ","type":"text","marks":[{"type":"strong"}]},{"text":"\u003croot>","type":"text","marks":[{"type":"code_inline"},{"type":"strong"}]},{"text":" before composing any artifact path.","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Read","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"docs_root","type":"text","marks":[{"type":"code_inline"}]},{"text":" from ","type":"text"},{"text":"\u003crepo-root>/.compound-engineering/config.yaml","type":"text","marks":[{"type":"code_inline"}]},{"text":" only (","type":"text"},{"text":"\u003crepo-root>","type":"text","marks":[{"type":"code_inline"}]},{"text":" = ","type":"text"},{"text":"git rev-parse --show-toplevel","type":"text","marks":[{"type":"code_inline"}]},{"text":"). Do not read it from ","type":"text"},{"text":"config.local.yaml","type":"text","marks":[{"type":"code_inline"}]},{"text":". Unset -> ","type":"text"},{"text":"\u003croot>","type":"text","marks":[{"type":"code_inline"}]},{"text":" is ","type":"text"},{"text":"docs","type":"text","marks":[{"type":"code_inline"}]},{"text":", exactly as before.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate","type":"text","marks":[{"type":"strong"}]},{"text":" a set value: a repo-relative directory whose real, symlink-resolved path stays inside the repo and is neither the repo root nor under ","type":"text"},{"text":".git/","type":"text","marks":[{"type":"code_inline"}]},{"text":". Otherwise stop with an error naming ","type":"text"},{"text":"docs_root","type":"text","marks":[{"type":"code_inline"}]},{"text":" and the value -- never fall back to ","type":"text"},{"text":"docs","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"\u003croot>","type":"text","marks":[{"type":"code_inline"}]},{"text":" as the sole artifact location: create it if absent, compose each path as ","type":"text"},{"text":"\u003croot>/\u003csubdir>","type":"text","marks":[{"type":"code_inline"}]},{"text":" with this skill's own subdirectory, and never also read ","type":"text"},{"text":"docs","type":"text","marks":[{"type":"code_inline"}]},{"text":". \u003c!-- ce-docs-root:end -->","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Phase 1: Diagnose","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 1: Determine Plugin Version","type":"text"}]},{"type":"paragraph","content":[{"text":"Detect the installed compound-engineering plugin version by reading the plugin metadata or manifest when the platform exposes it. If the version cannot be determined, skip this step.","type":"text"}]},{"type":"paragraph","content":[{"text":"If a version is found, pass it to the check script via ","type":"text"},{"text":"--version","type":"text","marks":[{"type":"code_inline"}]},{"text":". Otherwise omit the flag.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 2: Run the Health Check","type":"text"}]},{"type":"paragraph","content":[{"text":"Before running the script, display:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"Compound Engineering -- checking your environment...","type":"text"}]},{"type":"paragraph","content":[{"text":"Run the bundled check script. Set ","type":"text"},{"text":"SKILL_DIR","type":"text","marks":[{"type":"code_inline"}]},{"text":" to the absolute directory you loaded this ","type":"text"},{"text":"ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" SKILL.md from — the Bash tool's CWD is the user's project, not the skill dir, so a bare ","type":"text"},{"text":"scripts/","type":"text","marks":[{"type":"code_inline"}]},{"text":" path will not resolve:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"SKILL_DIR=\"\u003cabsolute path of the directory containing this SKILL.md>\";\nif [ -f \"$SKILL_DIR/scripts/check-health\" ]; then bash \"$SKILL_DIR/scripts/check-health\" --version VERSION; else echo \"Bundled health script not found at $SKILL_DIR/scripts/check-health; run the inline checks from ce-setup instead.\"; fi","type":"text"}]},{"type":"paragraph","content":[{"text":"Use the same command without ","type":"text"},{"text":"--version VERSION","type":"text","marks":[{"type":"code_inline"}]},{"text":" if Step 1 could not determine a version.","type":"text"}]},{"type":"paragraph","content":[{"text":"If the script is unavailable, run the inline equivalent listed in ","type":"text"},{"text":"references/repo-fixes.md","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"paragraph","content":[{"text":"Display the diagnostic output to the user. Missing optional tools are not setup failures. The health report includes the resolved artifact root and which config layer supplied it (per Artifact Root Resolution above); show that line so the operator can confirm where CE artifacts will be written. Missing ","type":"text"},{"text":"config.yaml","type":"text","marks":[{"type":"code_inline"}]},{"text":" is a reported absence, not a project issue.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 3: Decide Whether Fixes Are Needed","type":"text"}]},{"type":"paragraph","content":[{"text":"Repo-local fixes the health report names apply only to the checkout that report diagnosed. If Phase 2 will write to a different writable checkout, diagnose that checkout first. Session-level findings such as plugin version and optional tools still come from this session's Phase 1.","type":"text"}]},{"type":"paragraph","content":[{"text":"After the health report, decide Phase 2 from writable-checkout availability:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If this session has a writable git checkout, run Phase 2 locally, including when ","type":"text"},{"text":"project_issues","type":"text","marks":[{"type":"code_inline"}]},{"text":" is 0. Phase 2 always refreshes the example and always offers to create ","type":"text"},{"text":"config.yaml","type":"text","marks":[{"type":"code_inline"}]},{"text":" when that file is missing.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If this session has no writable checkout, but the user named a repository and the harness exposes a remote repo-work surface with a writable checkout, run Phase 2 on that surface instead and report the remote repo-local fixes in Phase 3.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Otherwise skip Phase 2 and go to Phase 3, saying repo-local writes were skipped because no writable checkout is available.","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Two offers concern this machine rather than the checkout, so they stand whether or not Phase 2 runs. If the report names a legacy Compound Codex tool map, offer to remove it following ","type":"text"},{"text":"references/legacy-codex-tool-map.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" from this skill's directory. If the bundled health script reported the ","type":"text"},{"text":"node","type":"text","marks":[{"type":"code_inline"}]},{"text":" row available, offer to warm the npm cache for cross-model peers following ","type":"text"},{"text":"references/acpx-cache-warm.md","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"paragraph","content":[{"text":"Phase 2 remediates every project issue the report names, each in its own step of ","type":"text"},{"text":"references/repo-fixes.md","type":"text","marks":[{"type":"code_inline"}]},{"text":". That includes a ","type":"text"},{"text":"ce-work","type":"text","marks":[{"type":"code_inline"}]},{"text":" implementation engine the report marks unavailable or invalid, retired scalar routing keys, and malformed dormant ","type":"text"},{"text":"work_engine_preferences","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"work_engine_effort","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"paragraph","content":[{"text":"If optional tools are missing, do not offer a bulk install. The diagnostic already printed the relevant install command or project URL. Say: \"Install optional tools only for the workflows you use.\"","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Phase 2: Fix Repo-Local Issues","type":"text"}]},{"type":"paragraph","content":[{"text":"Read ","type":"text"},{"text":"references/repo-fixes.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" from this skill's directory before making any repo-local change. It carries Steps 4-10: removing the obsolete ","type":"text"},{"text":"compound-engineering.local.md","type":"text","marks":[{"type":"code_inline"}]},{"text":", refreshing the example config, offering to create ","type":"text"},{"text":"config.yaml","type":"text","marks":[{"type":"code_inline"}]},{"text":", repairing invalid ","type":"text"},{"text":"work_engine_preferences","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"docs_root","type":"text","marks":[{"type":"code_inline"}]},{"text":", the two ","type":"text"},{"text":".gitignore","type":"text","marks":[{"type":"code_inline"}]},{"text":" offers, and the agent-instructions offers (a knowledge-store mention, the compounding directive, and the chat-register directive for ","type":"text"},{"text":"ce-noslop","type":"text","marks":[{"type":"code_inline"}]},{"text":"), and the offer to draft the project's review docs.","type":"text"}]},{"type":"paragraph","content":[{"text":"Every change to a user-owned file is offered and applied only if the user approves.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Phase 3: Summary","type":"text"}]},{"type":"paragraph","content":[{"text":"User-runnable invocation rendering.","type":"text","marks":[{"type":"strong"}]},{"text":" In setup summaries, default to ","type":"text"},{"text":"/ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"/ce-help","type":"text","marks":[{"type":"code_inline"}]},{"text":"; use ","type":"text"},{"text":"$ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"$ce-help","type":"text","marks":[{"type":"code_inline"}]},{"text":" only when the active host is Codex or explicitly documents dollar-prefixed skill invocation. On oh-my-pi (","type":"text"},{"text":"omp","type":"text","marks":[{"type":"code_inline"}]},{"text":"), use ","type":"text"},{"text":"/skill:ce-setup","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"/skill:ce-help","type":"text","marks":[{"type":"code_inline"}]},{"text":". Render only the invocation as inline code and output one form only.","type":"text"}]},{"type":"paragraph","content":[{"text":"Display a brief summary:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"✅ Compound Engineering setup complete\n\nFixed: \u003cfixes applied, or none>\nSkipped: \u003cfixes declined, or none>\nOptional: \u003cmissing optional tools, or all available>\n\nRun `\u003crendered invocation>` anytime to re-check.\nRun `\u003crendered ce-help invocation>` to ask which skill fits or what comes next.","type":"text"}]}]},"metadata":{"date":"2026-11-02","name":"ce-setup","author":"@skillopedia","source":{"stars":25863,"repo_name":"compound-engineering-plugin","origin_url":"https://github.com/EveryInc/compound-engineering-plugin/blob/HEAD/skills/ce-setup/SKILL.md","repo_owner":"EveryInc","body_sha256":"4036911e689d3541048bef2d00bf8f1c343caa99aba48e60269ea1c8184868b2","cluster_key":"54bcc70a0a04cda566968043873f64ca48a9ce01b6f827f9784a815cc87bd280","clean_bundle":{"format":"clean-skill-bundle-v1","source":"EveryInc/compound-engineering-plugin/skills/ce-setup/SKILL.md","text_bytes":112997,"source_commit":"77cc431daaebea7ee9f33ac530a66eec5404572b","skills_sh_rank":5931,"attachment_count":12,"text_attachments":12,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"skills/ce-setup/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"general","category_label":"General"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"general","import_tag":"skills-sh-top20k-2026-11","description":"Check Compound Engineering health and repo-local config, scaffold a Compound Pack with `pack:\u003cid>`, or draft or refresh coding standards and review docs with `standards`.","argument-hint":"[pack:\u003cid> | standards]","disable-model-invocation":true}},"renderedAt":1793671375221}

Compound Engineering Setup Interaction Method Ask each question below using the host's blocking question tool already in the current tool list (match by capability, not by a host-specific name). Presence in the current tool list is proof the tool exists; never call a user-facing question tool to discover whether it exists. If a matching tool is listed but unloaded, use the host's tool-discovery primitive to load that capability — do not search for another host's tool name. Fall back to a numbered list on the host's user-visible chat surface only when no such tool is in the list or a real ques…