Paths: File paths ( , ) are relative to this skill directory. ln-162-skill-reviewer Type: L3 Worker (standalone-capable) Category: 1XX Documentation Pipeline Universal reviewer with two modes: - for - for - repo suite for this skills repository when / is requested or the current repo is Plan Mode behavior: Phases 1-4 and 6-7 are research. Run them fully in Plan Mode, write the report plus fix list into the plan, and apply edits only after approval. --- Mode Detection | Condition | Mode | Review Profile | |-----------|------|----------------| | files exist in CWD | SKILL | Full D1-D11 + M1-M6…

| grep -v '{' | sort -u | while read path; do\n [ -f \"$dir/$path\" ] || [ -f \"$path\" ] || echo \"FAIL: missing MANDATORY READ target: $path (from $f)\"\n done\ndone\n```\n\n## Check 6: Orphan references (D7)\n```bash\nfor f in {scoped SKILL.md files}; do\n dir=$(dirname \"$f\")\n if [ -d \"$dir/references\" ]; then\n find \"$dir/references\" -type f | while read ref; do\n base=$(basename \"$ref\")\n [[ \"$base\" == .* ]] && continue\n grep -q \"$base\" \"$f\" || echo \"FAIL: orphan reference: $ref (not in $f)\"\n done\n fi\ndone\n```\n\n## Check 7: Passive file reference (D2)\n```bash\nfor f in {scoped SKILL.md files}; do\n # Pattern 1: See/Per/Follows prose patterns\n grep -nE '(^See |^Per |^Follows |See \\[).*\\.(md|txt|yaml)' \"$f\" | grep -v \"MANDATORY READ\" && echo \"WARN: passive prose ref in $f\"\n # Pattern 2: Markdown links to local files [text](path.md)\n grep -nE '\\[[^\\]]*\\]\\([^)]*\\.(md|txt|yaml)\\)' \"$f\" | grep -vE '(MANDATORY READ|https?://)' && echo \"WARN: passive markdown link in $f\"\ndone\n```\n\n## Check 8: Definition of Done (D7)\n```bash\nfor f in {scoped SKILL.md files}; do\n grep -q \"## Definition of Done\" \"$f\" || echo \"FAIL: no Definition of Done: $f\"\n # Verify checkbox format (- [ ]) if DoD section exists\n if grep -q \"## Definition of Done\" \"$f\"; then\n count=$(sed -n '/## Definition of Done/,/^---/p' \"$f\" | grep -c '^\\- \\[ \\]')\n [ \"$count\" -eq 0 ] && echo \"FAIL: DoD has no checkbox items (- [ ]): $f\"\n fi\ndone\n```\n\n## Check 9: Meta-Analysis L1/L2 (D7)\n```bash\nfor f in {scoped SKILL.md files}; do\n # Detect skill level from Type line\n level=$(grep -oE 'L[12]' \"$f\" | head -1)\n if [ -n \"$level\" ]; then\n grep -q \"Meta-Analysis\" \"$f\" || echo \"FAIL: L1/L2 skill missing Meta-Analysis: $f\"\n grep -q \"meta_analysis_protocol\" \"$f\" || echo \"FAIL: L1/L2 skill missing meta_analysis_protocol MANDATORY READ: $f\"\n fi\ndone\n```\n\n## Check 10: Publishing skill requirements (D7)\n```bash\nfor f in {scoped SKILL.md files}; do\n if grep -qE '(gh api graphql.*mutation|gh issue comment)' \"$f\"; then\n grep -qi \"fact.check\" \"$f\" || echo \"FAIL: publishing skill missing Fact-Check phase: $f\"\n grep -q \"humanizer_checklist\" \"$f\" || echo \"FAIL: publishing skill missing humanizer_checklist MANDATORY READ: $f\"\n fi\ndone\n```\n\n## Check 11: Description trigger quality (D8, WARN)\n```bash\nfor f in {scoped SKILL.md files}; do\n desc=$(sed -n '/^description:/p' \"$f\" | sed 's/^description: *//' | tr -d '\"')\n if [ -n \"$desc\" ]; then\n echo \"$desc\" | grep -qiE '(Use (this )?(skill )?(when|for|before|after)|Trigger when|Invoked when|should be used when|Not for )' \\\n || echo \"WARN: description lacks trigger condition (WHEN): $f\"\n fi\ndone\n```\n\n## Check 12: Execution proximity (D2b, WARN)\n```bash\nfor f in {scoped SKILL.md files}; do\n # Find imperative actions referencing external tools without inline command template\n grep -nE '(Launch|Run|Execute) .*(agent_runner|--agent|background task|BOTH agents)' \"$f\" | while read match; do\n linenum=$(echo \"$match\" | cut -d: -f1)\n # Check 10 lines around for inline code block with actual command\n nearby=$(sed -n \"$((linenum > 5 ? linenum-5 : 1)),$((linenum+10))p\" \"$f\")\n echo \"$nearby\" | grep -qE '```|`node |`bash |--prompt-file|--output-file|--agent ' \\\n || echo \"WARN: imperative tool action at line $linenum without inline command template: $f\"\n done\ndone\n```\n\n## Check 13: Platform API Compatibility\n```bash\nfor f in {scoped SKILL.md files}; do\n grep -n 'Agent(resume:' \"$f\" && echo \"FAIL: unsupported Agent(resume:) in $f — use SendMessage({to: agentId})\"\n grep -nE 'effort.*\"max\"|effort: max' \"$f\" && echo \"FAIL: unsupported effort \\\"max\\\" in $f — use low/medium/high\"\ndone\n```\n\n## Check 17: Worker invocation enforcement (D8b)\n```bash\nfor f in {scoped SKILL.md files}; do\n level=$(grep -oE 'L[12]' \"$f\" | head -1)\n [ -z \"$level\" ] && continue\n worker_count=$(grep -oE 'ln-[0-9]+-[a-z-]+' \"$f\" | sort -u | while read w; do\n self=$(basename $(dirname \"$f\") | grep -oE 'ln-[0-9]+-[a-z-]+')\n [ \"$w\" != \"$self\" ] && echo \"$w\"\n done | sort -u | wc -l)\n [ \"$worker_count\" -eq 0 ] && continue\n skill_calls=$(grep -c 'Skill(skill:' \"$f\" || true)\n [ \"$skill_calls\" -eq 0 ] && echo \"FAIL: $level skill delegates to $worker_count workers but has no Skill() invocation code blocks: $f\"\n grep -q 'Worker Invocation (MANDATORY)' \"$f\" || echo \"FAIL: $level skill missing Worker Invocation (MANDATORY) section: $f\"\n grep -q 'TodoWrite format (mandatory)' \"$f\" || echo \"WARN: $level skill missing TodoWrite format section: $f\"\ndone\n```\n\n## Check 18: Type line presence (D7)\n```bash\nfor f in {scoped SKILL.md files}; do\n grep -q '\\*\\*Type:\\*\\*' \"$f\" || echo \"FAIL: no **Type:** line: $f\"\ndone\n```\n\nEvery SKILL.md must have a `**Type:**` line (e.g., `**Type:** L1 Top Orchestrator`). Without it, Check 9 (Meta-Analysis) and Check 17 (Worker Invocation) silently skip the skill.\n\n## Check 19: Worker independence (D8)\n```bash\nfor f in {scoped SKILL.md files}; do\n grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qi 'worker' || continue\n grep -q '^\\*\\*Coordinator:\\*\\*' \"$f\" && echo \"FAIL: worker declares Coordinator: $f\"\n grep -q '^\\*\\*Parent:\\*\\*' \"$f\" && echo \"FAIL: worker declares Parent: $f\"\n grep -nE 'Invoked by ln-[0-9]+|called by ln-[0-9]+' \"$f\" && echo \"FAIL: worker declares caller coupling: $f\"\ndone\n```\n\n## Check 20: Docs-model alignment for extraction skills (D4)\n```bash\nfor f in {scoped SKILL.md files}; do\n case \"$f\" in\n *ln-160-*|*ln-161-*)\n grep -q 'markdown_read_protocol' \"$f\" || echo \"FAIL: docs extraction skill missing markdown_read_protocol: $f\"\n grep -q 'docs_quality_contract' \"$f\" || echo \"FAIL: docs extraction skill missing docs_quality_contract: $f\"\n grep -q 'procedural_extraction_rules' \"$f\" || echo \"FAIL: docs extraction skill missing procedural_extraction_rules: $f\"\n ;;\n esac\ndone\n```\n\n## Check 21: Standalone summary workers (D8)\n```bash\nfor f in {scoped SKILL.md files}; do\n case \"$f\" in\n *ln-011-*|*ln-012-*|*ln-013-*|*ln-014-*|*ln-221-*|*ln-222-*|*ln-301-*|*ln-302-*)\n grep -q 'summaryArtifactPath' \"$f\" || echo \"FAIL: standalone summary worker missing summaryArtifactPath contract: $f\"\n grep -qi 'standalone' \"$f\" || echo \"FAIL: standalone summary worker missing standalone wording: $f\"\n grep -nE 'Invoked by ln-|called by ln-|returning control to `ln-|handing control back to `ln-' \"$f\" && echo \"FAIL: standalone summary worker has caller coupling: $f\"\n ;;\n esac\ndone\n```\n\n## Check 22: Run-scoped runtime artifact paths (D2)\n```bash\nfor f in {scoped SKILL.md files}; do\n grep -nP '\\.hex-skills/runtime-artifacts/(?!runs/)' \"$f\" && echo \"FAIL: non-run-scoped runtime artifact path: $f\"\ndone\n```\n\n## Check 23: SOP/TWI procedural executability (D2b, WARN)\n```bash\nfor f in {scoped SKILL.md files}; do\n grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qiE 'orchestrator|coordinator|worker' || continue\n grep -nEi '\\b(typically|periodically|regularly|as needed|when appropriate)\\b' \"$f\" && echo \"WARN: vague procedural modal wording: $f\"\n grep -nE '^[0-9]+\\. .*\\b(and then|; then|, then)\\b' \"$f\" && echo \"WARN: compound procedural step: $f\"\n if grep -qiE '(Agent\\(|Skill\\(skill:|record-worker|checkpoint|advance --to|update .*status)' \"$f\"; then\n grep -qiE 'Risk Checklist|Preflight|guard|Evidence|checkpoint|artifact' \"$f\" || echo \"WARN: procedural skill may lack point-of-use checklist/evidence: $f\"\n fi\ndone\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":9139,"content_sha256":"36ad3bc7f2e51ab2efe4b98ca31e1e9245852c1b35f5fcdf17963fd8f5e62b2a"},{"filename":"references/clean_code_checklist.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/clean_code_checklist.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Clean Code Checklist\n\nUniversal patterns for detecting dead code, backward-compat shims, and legacy remnants.\n\n## 4 Dead Code Categories\n\n### 1. Unreachable Code\n\nCode after `return`/`throw`/`break`; dead branches (always-true/false conditions).\n\n**Severity:** MEDIUM\n\n### 2. Unused Code\n\n| What | Severity |\n|------|----------|\n| Unused functions, classes, methods | MEDIUM |\n| Unused exports (exported but never imported) | MEDIUM |\n| Unused imports, variables, parameters | LOW |\n\n### 3. Commented-Out Code\n\nLarge code blocks in comments (>5 lines with code syntax). Git preserves history — delete, don't comment.\n\n**Severity:** LOW\n\n### 4. Backward-Compat & Legacy\n\n| Pattern | Example | Severity |\n|---------|---------|----------|\n| Old aliases | `const oldName = newName` | medium |\n| Wrapper functions | `function oldFunc() { return newFunc() }` | medium |\n| Unsupported re-exports | `export { newModule as oldModule }` | medium |\n| Migration shims/adapters | `LegacyAdapter`, `*Compat`, `*Shim` | high if critical path |\n| Version conditionals | `if (isOldVersion) { oldFunc() }` | medium |\n| Legacy naming | `_old*`, `_legacy*`, `_compat*`, `_unsupported*` | medium |\n| Legacy markers in comments | `// backward compat`, `// unsupported`, `// TODO: remove in v` | low |\n\n## Replacement Rule\n\nWhen implementation replaces old code:\n\n1. Delete old implementation entirely\n2. Update ALL callers to use new API\n3. Remove old signatures (don't alias)\n4. Remove re-exports of old names\n5. Delete adapter/shim files\n\n**Anti-pattern:** keeping old code \"just in case\" — git history preserves it.\n\n## Exceptions\n\n| Exception | When OK |\n|-----------|---------|\n| Published packages (npm/NuGet) | Unsupported API cycle required (major version bump) |\n| Active migration (\u003c3 months) | Clear removal timeline documented |\n| External API contract | Consumers not yet migrated (tracked as tech debt) |\n\n## Quick Checklist\n\n```\n[] No unused imports/variables/functions\n[] No commented-out code blocks (>5 lines)\n[] No backward-compat wrappers or aliases\n[] No unsupported re-exports\n[] No _old/_legacy/_compat naming\n[] All callers updated to new API\n[] Old files deleted (not just emptied)\n```\n\n---\n**Version:** 1.0.0\n**Last Updated:** 2026-02-08\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2379,"content_sha256":"55b91e1cf53fe3d97bb46fe0c9543ae422e898f1c1c1da1ec1a87d8d2c219cdb"},{"filename":"references/command_review_criteria.md","content":"# Command Review Criteria (COMMAND Mode)\n\n\u003c!-- DO NOT add here: Workflow phases -> ln-162-skill-reviewer SKILL.md -->\n\nReview criteria for `.claude/commands/*.md` files in target projects.\n\n## Criteria\n\n| # | Criterion | Check | Auto-Fix | Severity |\n|---|-----------|-------|----------|----------|\n| C1 | Frontmatter present | `---` block with `description` field | Add empty frontmatter | FAIL |\n| C2 | allowed-tools present | `allowed-tools:` in frontmatter | Infer from content (Bash if shell commands, Read if file reads) | FAIL |\n| C3 | Description length | `description` \u003c= 100 chars | Truncate with `...` | WARN |\n| C4 | File size | \u003c= 300 lines | Flag for manual split | WARN |\n| C5 | Actionable content | >= 3 imperative verb lines (Run, Execute, Deploy, Install, etc.) | Flag as too declarative | WARN |\n| C6 | No orphan file refs | All relative paths in `[text](path)` or backtick paths exist | Remove broken refs | FAIL |\n| C7 | No placeholders | No `[TBD]`, `TODO`, `FIXME`, `{{VAR}}`, `{PLACEHOLDER}` | Flag for completion | WARN |\n| C8 | No duplicate purpose | No other `.claude/commands/*.md` with overlapping `description` | Flag for merge/rename | WARN |\n| C9 | Stack consistency | Commands (npm/pip/dotnet/docker) match project's package manager | Flag mismatch | WARN |\n| C10 | Last Updated date | `**Last Updated:**` present at end of file | Add current date | FAIL |\n| C11 | Source provenance | `## Source` identifies source doc and section | Flag missing provenance | WARN |\n| C12 | No copied doc shell | No `DOC_KIND`, `DOC_ROLE`, `Quick Navigation`, `Agent Entry`, `Maintenance` sections | Remove copied shell sections if exact matches | FAIL |\n\n## Verdicts\n\n| Verdict | Condition |\n|---------|-----------|\n| **PASS** | All criteria pass |\n| **FIXED** | Auto-fixed 1+ issues, now passes |\n| **WARN** | Unfixable WARN-severity issues flagged |\n| **FAIL** | Unfixable FAIL-severity issues remain |\n\n## allowed-tools Inference Rules\n\n| Content Pattern | Inferred Tool |\n|----------------|---------------|\n| `bash` / `sh` code blocks, shell commands | Bash |\n| `Read` / `Load` / file path references | Read |\n| `Edit` / `modify` / `update file` instructions | Edit |\n| `Grep` / `search` / `find in files` | Grep |\n| `Glob` / `find files` / pattern matching | Glob |\n| `Skill(` / skill invocation | Skill |\n| `AskUserQuestion` / user confirmation steps | AskUserQuestion |\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2394,"content_sha256":"e6191347c0608982362c3cd0914d7c944b105685e656d5b2406dc5db2cb21ff6"},{"filename":"references/creation_quality_checklist.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/creation_quality_checklist.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Creation Quality Checklist\n\nPrevention checklist for content creators. Maps to story validation criteria — following these rules prevents penalty points at validation stage.\n\nFor full validation rules and auto-fix logic, see story validator `references/` (10 validation files).\n\n## Vocabulary\n\n**Actor:** The entity that makes the decision or performs the action described in an AC.\n\nRules:\n- The actor is the entity that executes, not the entity that launches, schedules, or dispatches.\n- If the AC describes a delegated action (spawned process, background worker, agent session), the actor is the delegate — not the delegator.\n- Scenario segments (3) Discovery and (4) Usage Context must be answered from the actor's perspective: what does the actor discover, what context does the actor have at the point of execution.\n\n## Story Creation Checklist\n\nFor Story creation workflow.\n\n| # | Criterion | Penalty | Rule |\n|---|-----------|---------|------|\n| 1 | Story Structure | 1 | 9 sections per template (in order): Story, Context, Acceptance Criteria, Implementation Tasks, Test Strategy, Technical Notes, Definition of Done, Dependencies, Assumptions |\n| 3 | Story Statement | 1 | Format: \"As a {persona}, I want {capability}, so that {value}\" — all 3 parts required |\n| 4 | AC Quality | 3 | 3-5 Given/When/Then scenarios: happy path + error + edge case. Include HTTP codes, timing, exact messages |\n| 5 | Standards Compliance | 10 | Every technical decision references specific RFC/OWASP/REST standard by number in Technical Notes. Use standards research results |\n| 6 | Library & Version | 5 | Latest stable versions in Technical Notes. Query Context7/MCP Ref to verify |\n| 9 | Story Size | 3 | 1-8 tasks (3-5 optimal), 3-5 AC (**HARD LIMIT: >5 ACs = MUST split**), 6-20 hours total, tests justified by Priority ≥15. If outside range — split or merge |\n| 11 | YAGNI | 3 | Each AC = real user need from Epic Scope In. No speculative features. No research-driven ACs (research → Technical Notes only). Every Task maps to >= 1 AC |\n| 12 | KISS | 3 | Simplest approach. No task requires >3 new abstractions. If >3 — split or simplify |\n| 14 | Documentation Complete | 5 | Pattern docs (from best practices research) referenced in Technical Notes. No orphan patterns |\n| 16 | Story-Task Alignment | 3 | Each Task title contains keyword from Story AC (grep-verifiable) |\n| 17 | AC-Task Coverage | 3 | Coverage matrix: every AC covered by >= 1 Task. No empty rows |\n| 17b | AC Invocability | 5 | Every AC where an actor invokes a mechanism must map to a task creating a concrete, named mechanism. Infrastructure-only tasks (queue, registry, store) do NOT satisfy ACs requiring something to *use* that infrastructure. One named mechanism per actor — no vague \"via X or Y\" |\n| 17c | Scenario Completeness | 5 | Each AC traces 5 segments: (1) Trigger, (2) Entry Point, (3) Discovery, (4) Usage Context, (5) Outcome. All 5 must be addressed across covering tasks. Traceability table with these columns required in the plan. See ln-300 Phase 2 for segment definitions |\n| 17d | Layer Separation | 5 | Segments map to layers: Foundation, Invocation, Knowledge, Wiring. Buildable artifacts in different layers = separate tasks. A foundation task must not also deliver the invocation mechanism or the actor's knowledge of how to use it, unless the artifact is trivially small (config line, not a new file/module) |\n| 18 | Story Dependencies | 10 | No forward dependencies on Stories not yet created. Only reference earlier Stories |\n| 24 | Assumption Registry | 3 | Assumptions section with >=1 typed entry per relevant category (FEASIBILITY/DEPENDENCY/DATA/SCOPE). Each entry has Confidence and Invalidation Impact |\n| 28 | AC Purity | 3 | Every AC describes observable user behavior (Given user does X, Then user sees Y). System internals (lookup priority, cache layers, endpoint URLs, architecture) belong in Technical Notes, not ACs |\n| 29 | Scope Minimalism | 3 | Simplest design that delivers Epic Goal. No benchmark-driven inflation (\"industry does X\" is not a reason to add AC). Standards Research → Technical Notes only |\n| 30 | Feature Bundling | 3 | Story title has no conjunctions joining distinct capabilities (\"and\", \"&\", \"+\"). Each distinct user capability = separate Story |\n\n**Total exposure:** 77 penalty points if all violated.\n\n## Task Creation Checklist\n\nFor Task creation workflow.\n\n| # | Criterion | Penalty | Rule |\n|---|-----------|---------|------|\n| 2 | Tasks Structure | 1 | 7 sections per template (in order): Context, Implementation Plan, Technical Approach, Acceptance Criteria, Affected Components, Existing Code Impact, Definition of Done |\n| 8 | Documentation Integration | 3 | No standalone doc-only tasks. Doc updates fold into implementation task DoD |\n| 13 | Task Order | 3 | Foundation-First: DB -> Service -> API -> UI. Each layer builds on previous |\n| 15 | Code Quality Basics | 3 | No hardcoded values in Technical Approach. Use config/env/constants |\n| 19 | Task Dependencies | 3 | Task N uses only Tasks 1..N-1. No forward references to N+1, N+2 |\n| 22 | AC Verify Methods | 3 | Every task AC has `verify:` method (test/command/inspect). At least 1 non-inspect method per task |\n| 19b | Parallel Groups | 3 | Tasks in same group have no mutual deps; all deps point to earlier groups; numbers sequential. Skip if no groups assigned |\n\n**Total exposure:** 19 penalty points.\n\n## Validation-Only Criteria\n\nThese 7 criteria are handled during story validation, NOT by creators:\n\n| # | Criterion | Why validation-only |\n|---|-----------|---------------------|\n| 7 | Test Strategy | Section is placeholder at creation; filled by test planning later |\n| 10 | Test Task Cleanup | Cleanup action during validation; no premature test tasks expected |\n| 20 | Risk Analysis | Validator scans Story/Tasks for unmitigated risks (R1-R6) via keyword detection in Technical Notes and Implementation Plan |\n| 21 | Alternative Solutions | Validator searches MCP Ref + web for modern alternatives; adds \"Alternative Considered\" note if better option exists |\n| 25 | AC Cross-Story Overlap | Validator loads sibling Stories; checks structured traceability (AC IDs, Affected Components, file paths) for overlap and conflicts |\n| 26 | Task Cross-Story Duplication | Validator compares task Affected Components and file paths across sibling Stories |\n| 27 | Pre-mortem Analysis | Validator runs pre-mortem for complex Stories; Tigers → Risk #20, Elephants → Assumptions #24 |\n\n---\n**Version:** 1.0.0\n**Last Updated:** 2026-02-08\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6700,"content_sha256":"cee1e4dbb27277503f662d4e6382399937b163e878b205cc3438a2a3e0dd94bf"},{"filename":"references/goal_articulation_gate.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/goal_articulation_gate.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Goal Articulation Gate\n\nMandatory micro-step before execution/review/analysis. Forces explicit statement of the REAL goal to prevent surface-level reasoning failures.\n\n## Why\n\nModels latch onto the most salient feature (70% of failures) instead of the actual constraint. Articulating the real goal surfaces hidden requirements. Structured reasoning > context injection by 2.83x ([STAR framework](https://arxiv.org/abs/2602.21814), 2025).\n\n## Gate (4 questions, \u003c=25 tokens each, ~100 tokens total)\n\nBefore starting work, state in 1-2 sentences each:\n\n| # | Question | Guards Against |\n|---|----------|---------------|\n| 1 | **REAL GOAL:** What is the actual deliverable? (Name the primary subject — the thing being changed) | Distance heuristic — latching onto salient but wrong target |\n| 2 | **DONE LOOKS LIKE:** What does success look like concretely? | Vague completion — \"it works\" without measurable outcome |\n| 3 | **NOT THE GOAL:** What would a surface-level shortcut produce? What would over-engineering produce? | Environmental rationalization — plausible but wrong answer. Over-engineering: benchmark-driven scope inflation, bundling multiple features as \"unified\", adding industry patterns not in Epic Scope |\n| 4 | **INVARIANTS & HIDDEN CONSTRAINTS:** What implicit requirement isn't stated? What surrounding systems must stay unchanged? | Ironic self-awareness — knowing the constraint but ignoring it |\n\n## Anti-Hallucination Rule\n\nIf evidence for HIDDEN CONSTRAINTS is missing, write `UNKNOWN` and list assumptions explicitly. Do NOT invent constraints without a source anchor (task description, story AC, doc reference, or code path).\n\n## Example\n\n**Task:** \"Add authentication to API endpoints\"\n\n| # | Answer |\n|---|--------|\n| 1 | REAL GOAL: Every non-public endpoint rejects requests without valid JWT |\n| 2 | DONE: 401 on unauthorized, valid tokens pass, refresh works, tests cover all 3 |\n| 3 | NOT THE GOAL: Adding auth middleware to one route and calling it done |\n| 4 | HIDDEN: Existing integration tests break without test fixtures update. UNKNOWN: rate limiting requirements (assumption: not in scope) |\n\n**Anti-pattern example (over-engineering):**\n\n| # | Answer |\n|---|--------|\n| 1 | REAL GOAL: Translate user input using stored translations, cache repeated responses |\n| 2 | DONE: Two Stories — TM lookup returns stored translation; Response cache returns cached response. 3-4 ACs each |\n| 3 | NOT THE GOAL (shortcut): Single endpoint with no cache. NOT THE GOAL (over-engineering): \"Unified Intelligent Memory\" with 5-level lookup priority, 11 endpoints, industry benchmark tables, architecture in ACs |\n| 4 | HIDDEN: TM and Cache are distinct capabilities — bundling them inflates scope. ACs must describe what USER sees, not system internals |\n\n## Self-Check\n\nIf your REAL GOAL statement does not name the **primary subject** (the thing being changed/delivered), rewrite it. The research found 100% of failures framed the goal around a secondary subject.\n\n## When to Use\n\n- **Every start:** Use this gate before execution, review, analysis, or decomposition\n- **Rework tasks:** Combine with 5 Whys (`problem_solving.md`) to ensure root cause is articulated alongside the rework goal\n\n## Usage in SKILL.md\n\n```markdown\n**MANDATORY READ:** `references/goal_articulation_gate.md`\nBefore starting work, complete the Goal Articulation Gate (4 questions, \u003c=25 tokens each).\n```\n\n---\n**Version:** 1.0.0\n**Last Updated:** 2026-02-27\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3608,"content_sha256":"b4d5ef0784baacf935a468e2e47c11b87eddb749375f890e9d0e95c986e06841"},{"filename":"references/humanizer_checklist.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/humanizer_checklist.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Humanizer Checklist\n\n\u003c!-- SCOPE: Anti-AI-slop audit for any skill that publishes text. Final pass before presenting draft to user. -->\n\u003c!-- DO NOT add here: GitHub markdown syntax → discussion_formatting.md; announcement/response templates → per-skill references -->\n\u003c!-- SOURCE: Wikipedia WikiProject AI Cleanup (24 patterns), adapted for GitHub Discussions context -->\n\nRun this checklist as a final audit on any draft before presenting to user.\n\n---\n\n## Anti-AI Patterns (Detect and Fix)\n\n### Content\n\n| Pattern | AI Tells | Fix |\n|---------|----------|-----|\n| **Significance inflation** | \"marking a pivotal moment in the evolution of...\" | State the fact: \"was added in v2.0\" |\n| **Promotional language** | \"powerful\", \"seamless\", \"cutting-edge\", \"groundbreaking\" | Drop the adjective or replace with a specific claim |\n| **Generic conclusions** | \"The future looks bright\", \"Exciting times ahead\" | Specific next steps or cut entirely |\n| **Formulaic challenges** | \"Despite challenges... continues to thrive\" | Name the actual challenge or remove |\n\n### Language\n\n| Pattern | AI Tells | Fix |\n|---------|----------|-----|\n| **AI vocabulary** | Additionally, Furthermore, Moreover, testament, landscape, showcasing, leverage, utilize, foster, streamline, delve, tapestry, multifaceted | Use: also, shows, use, help, explore, varied |\n| **Copula avoidance** | \"serves as\", \"functions as\", \"stands as\", \"acts as\" | Use: \"is\", \"has\" |\n| **Rule of three** | \"innovation, inspiration, and insights\" | Use the natural number of items (1, 2, or 4 is fine) |\n| **Negative parallelisms** | \"It's not just X, it's Y\" | State Y directly |\n| **Filler phrases** | \"In order to\", \"Due to the fact that\", \"It's important to note that\", \"It's worth mentioning\" | \"To\", \"Because\", cut entirely |\n| **Excessive hedging** | \"could potentially possibly\", \"it might be argued that\" | \"may\", state it or cut it |\n\n### Tone\n\n| Pattern | AI Tells | Fix |\n|---------|----------|-----|\n| **Sycophantic openers** | \"Great question!\", \"You're absolutely right!\", \"That's a fantastic idea!\" | Respond directly. Skip the flattery |\n| **Chatbot artifacts** | \"I hope this helps!\", \"Let me know if you need anything!\", \"Happy to help!\" | Remove entirely |\n| **Em dash overuse** | \"tools—not the people—yet this continues—\" | Use commas or periods. Max 1 em dash per paragraph |\n\n---\n\n## Positive Voice Rules\n\nWhat TO do (not just what to avoid):\n\n| Rule | Example |\n|------|---------|\n| **Be specific** | \"reduces 9 HTTP calls to 1\" not \"significantly improves performance\" |\n| **Be direct** | \"This is a profiler\" not \"This serves as a profiling mechanism\" |\n| **Vary rhythm** | Mix short sentences with longer ones. Not all the same length |\n| **Use plain verbs** | \"finds\", \"fixes\", \"checks\" not \"leverages\", \"facilitates\", \"orchestrates\" |\n| **First person when honest** | \"We built this because...\" not \"This was developed to address...\" |\n| **Repeat when clearest** | Say \"profiler\" 3 times, not \"profiler... analysis tool... diagnostic engine\" |\n| **State opinions** | \"This is faster\" not \"This could potentially be considered faster\" |\n\n---\n\n## Audit Protocol\n\nAfter composing a draft, scan for:\n\n1. **Word scan:** Ctrl+F for AI vocabulary words (Additionally, Furthermore, Moreover, testament, landscape, showcasing, leverage, utilize, foster, streamline, delve, tapestry, multifaceted, Additionally). Replace each\n2. **Pattern scan:** Read first sentence of each paragraph — do they all start with similar structure? Vary them\n3. **Adjective audit:** For each adjective (powerful, seamless, robust, comprehensive), ask: \"can I replace this with a number or specific claim?\" If not, cut it\n4. **Rule-of-three check:** Any group of exactly 3 items? If the 3 are generic (\"speed, quality, reliability\"), cut to the ones that actually matter\n5. **Conclusion check:** Does the ending say \"the future looks bright\" or similar? Replace with specific next steps or remove\n6. **Em dash count:** More than 2 in the entire draft? Convert extras to commas/periods\n\n**Gate:** If 3+ patterns found, rewrite the flagged sections before presenting to user.\n\n---\n\n**Version:** 1.0.0\n**Last Updated:** 2026-03-14\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4325,"content_sha256":"ff8b71a1dc664e6070b015a5b6d8c054abe4ceef6863e7e3312bdf1cf47ed639"},{"filename":"references/intent_review.md","content":"# Intent Review Dimensions (M1-M6)\n\n\u003c!-- DO NOT add here: Workflow phases -> ln-162-skill-reviewer SKILL.md -->\n\nEvaluate DESIGN INTENT of changes. Applies to primary skills only (affected/dependency skills have no changed intent).\n\nFor each primary skill, read the git diff (`git diff HEAD -- {skill_dir}/`).\n\n## M1: Goal Clarity\n- REAL GOAL evident from diff + commit message alone (apply `references/goal_articulation_gate.md`)\n- NOT THE GOAL identified -- surface-level reading would NOT produce same answer as REAL GOAL\n- Goal unclear from diff alone -> `UNCLEAR_GOAL` (RETHINK); warn that Phase 5 fixes may address wrong intent\n\n## M2: Approach Optimality (scope: NEW changes only)\n- New abstractions count \u003c= 3 (phases, reference files, shared patterns)\n- No Red Flags triggered from SKILL_ARCHITECTURE_GUIDE table\n- KISS/YAGNI criteria pass per `references/creation_quality_checklist.md` (#11, #12)\n- No simpler approach achieves same goal with fewer lines/phases/files\n- Simpler alternative exists -> finding with specific description (SIMPLIFY or RETHINK)\n- **Downstream verification:** When a primary skill changes behavior, enumerate ALL downstream skills in its delegation tree (Worker Invocation table). For each: verify the change is compatible with downstream input contracts (D10)\n- **Upstream verification:** Check all skills that delegate TO the changed skill. Verify their expectations still hold\n- **Concrete trace test:** For each behavioral change, formulate: \"If I call this skill with {input}, will it produce {expected output}?\" Trace through the delegation chain. If any step breaks -- finding\n\n## M3: Ecosystem Consistency\n- 2-3 peer skills in same category (same NXX prefix) use consistent delegation pattern, hierarchy level, workflow pattern\n- No existing `references/` file that changed skill should reuse but doesn't\n- Divergence from peers has documented rationale\n- Missed shared/ reuse -> finding with specific file path (SIMPLIFY)\n\n## M4: Rewrite Delta (scope: WHOLE skill-as-changed)\n- SRP Decision Tree applied to skill-as-changed (not just the diff)\n- Tree does NOT suggest different structure (split/combine/re-level)\n- If delta HIGH (>30% different from clean-slate design) -> 1-3 sentence structural recommendation (RETHINK)\n\n## M5: Necessity (YAGNI Classification)\n\nClassify each diff hunk against M1's REAL GOAL:\n\n| Label | Definition | Action |\n|-------|-----------|--------|\n| REQUESTED | Directly implements REAL GOAL | KEEP |\n| DERIVED | Necessary side-effect of REAL GOAL | KEEP |\n| SPECULATIVE | Not requested, model-generated addition | ASK user |\n\n**SPECULATIVE detection signals:**\n- Content keywords: `future-proof`, `might need`, `prepare for`, `extensible`, `scalable for`, `in case`, `optional`, `configurable`, `placeholder`, `eventually`\n- Structural: new files/phases/sections absent from request; error handling outside stated scope; config with single consumer; abstractions with single implementation; fallback paths for non-existent conditions\n\n**Additional checks (all hunks):**\n- No backward-compat shims or unused artifacts per `references/clean_code_checklist.md`\n- Research-to-Action Gate: change inspired by external research -- what specific defect does it fix? No defect -> REVERT\n\n**Output:** build classification table:\n\n| # | File:Lines | Label | Rationale |\n|---|-----------|-------|-----------|\n\n**Speculative Change Gate:** if SPECULATIVE items exist, present ALL via single AskUserQuestion:\n```\nM5 found {N} speculative additions not traced to REAL GOAL:\n1. {file:lines} -- {rationale}\n2. {file:lines} -- {rationale}\nReply KEEP or REVERT per item (e.g., '1:KEEP 2:REVERT'). Default: REVERT all.\n```\nUser KEEP -> reclassify as REQUESTED. Remaining SPECULATIVE -> REVERT finding for Phase 5.\n\n**Finding categories:**\n- **SIMPLIFY** -- concrete reduction possible, may be auto-fixed\n- **RETHINK** -- design decision needed, NOT auto-fixable, advisory only\n- **REVERT** -- change does not fix concrete defect, must be rolled back\n\n## M6: Performance Baseline (ADVISORY -- non-blocking)\n- Compare SKILL.md line count before/after change\n- If change adds >50 lines without new phases/features -> flag for compaction review\n- If change adds new MANDATORY READ files -> verify they're loaded conditionally, not always\n- Advisory only: findings are NOTE severity, never FAIL\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4346,"content_sha256":"3ad9d3bd6dcaae7cfcd37d7ba270b489fe711960447731525dbecf0eade11261"},{"filename":"references/loop_health_contract.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/loop_health_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Loop Health Contract\n\n**Version:** 1.0.0\n**Last Updated:** 2026-04-25\n\n> **Paths:** All paths are relative to the skills repository root.\n\n## Purpose\n\nLoop health is retry-usefulness evidence. It does not replace lifecycle status, checkpoints, artifacts, task board status, or domain verdicts.\n\nUse it when a procedural skill can repeat a task, worker, stage, scenario segment, advisor session, or quality cycle.\n\n## Model\n\n| Field | Meaning | Owner |\n|-------|---------|-------|\n| `status` | workflow location now | existing runtime state |\n| `artifact` / `checkpoint` | completion evidence | runtime artifact/checkpoint layer |\n| `loop_health` | whether another retry can add value | coordinator/orchestrator runtime |\n\n## Signal Classes\n\n| Class | Retry action |\n|-------|--------------|\n| `none` | continue normally |\n| `timeout_idle` | retry only while loop health allows |\n| `timeout_productive` | verify/review before retry |\n| `permission_denial` | pause immediately |\n| `tool_missing` | pause immediately |\n| `auth_missing` | pause immediately |\n| `rate_limited` | pause/defer; not a domain failure |\n| `asked_question` | pause for decision or refine prompt |\n| `agent_error` | retry only while loop health allows |\n| `unknown` | retry only while loop health allows |\n\n## Default Policy\n\n| Policy | Value |\n|--------|-------|\n| `no_progress_limit` | `3` |\n| `same_error_limit` | `3` |\n| immediate pause | `permission_denial`, `tool_missing`, `auth_missing` |\n| progress reset | any confirmed objective progress |\n\nValid progress evidence includes new/changed artifacts, checkpoint deltas, task/status transitions, changed finding sets, accepted repairs, changed metrics, new bottlenecks, or benchmark improvements.\n\nDo not treat repeated prose, identical findings, or unchanged failed assertions as progress.\n\n## Pause Output\n\nWhen loop health pauses a flow, include scope, reason, evidence key/error signature, and the next operator decision or missing dependency.\n\n## Runtime Requirements\n\n- `loop_health` remains optional so existing runtime state stays readable.\n- Runtime history records loop-health updates as `LOOP_HEALTH_RECORDED`.\n- Domain counters remain domain counters; loop health measures whether another retry is useful.\n- Transport/agent failures must not become domain verdicts without domain evidence.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2462,"content_sha256":"ce2741dc3e881242fd0b88035ed7a66f9fbc9762e3231ef16b82e0e296c313e0"},{"filename":"references/mcp_applicability_matrix.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/mcp_applicability_matrix.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# MCP Applicability Matrix\n\n\u003c!-- SCOPE: Catalog-wide policy for when skills should prefer hex-line, hex-graph, hex-research, or avoid them. Used by skill authors and ln-162-skill-reviewer. -->\n\n## Core Rule\n\n- `hex-line` is primary for code-like file interaction.\n- `hex-graph` is primary for semantic understanding of existing codebases in supported languages.\n- `hex-research` is primary for project researchgraph questions when `docs/hypotheses/`, `docs/goals/`, or `benchmark/runs/*/manifest.yaml` can change a planning or validation decision.\n- Built-in file/search tools are fallback only.\n- Skills that do not make code-file, semantic-code, or researchgraph decisions should not mention these MCPs just to look consistent.\n\n## Family Matrix\n\n| Skill family | `hex-line` | `hex-graph` | `hex-research` | Notes |\n|------|------|------|------|------|\n| `ln-210`, `ln-220`, `ln-230` planning/prioritization | avoid by default | avoid | conditional | Use research graph only when hypotheses, goals, or run evidence can change scope, priority, or readiness |\n| `ln-300` planning for existing-code Stories | optional | REQUIRED | conditional | Use code graph for modules; use research graph only when Story references H/G IDs or hypothesis implementation status |\n| `ln-401` to `ln-404` execution and rework | REQUIRED | conditional | avoid by default | Graph only when editing existing symbols or checking blast radius |\n| `ln-510` to `ln-512` quality and cleanup | REQUIRED | REQUIRED | avoid by default | Quality decisions depend on semantic diff, clones, dead code, references |\n| `ln-610` to `ln-612` docs audits | optional | avoid | avoid by default | Docs structure/content checks are not graph problems |\n| `ln-613` code comments audit | REQUIRED | avoid | avoid | Needs code-file reads, not semantic graph decisions |\n| `ln-614` docs fact checking | REQUIRED | conditional | avoid by default | Graph only for entity/reference ambiguity |\n| `ln-620` to `ln-654` code, architecture, persistence, test audits | optional | REQUIRED | avoid by default | Graph is primary for semantic findings; hex-line only when code-file reads need safer structure |\n| `ln-700` bootstrap coordinators | optional | conditional | avoid by default | Graph helps only in transform/existing-code analysis |\n| `ln-720` to `ln-775` generators, restructurers, setup workers | REQUIRED | conditional | avoid by default | Graph only when migrating existing code or checking references |\n| `ln-780` to `ln-783` verifiers/runners | avoid | avoid | avoid | Runtime/build/container evidence is primary |\n| `ln-810` to `ln-814` optimization | REQUIRED for executor | conditional | avoid | Graph can narrow hotspots; profiler/benchmark stays source of truth |\n| `ln-820` to `ln-823` dependency upgrades | REQUIRED for manifest/code edits | conditional | avoid | Graph only when usage impact matters |\n| `ln-830` to `ln-832` modernization | REQUIRED | REQUIRED | avoid | Replacement and optimization need safe edits plus reference analysis |\n| `ln-910` to `ln-914` community | avoid | avoid | avoid | GitHub/community state is primary |\n| `ln-310` validation | optional | conditional | conditional | Use research graph audits when graph files changed or readiness claims cite hypotheses/goals |\n| `ln-311` external-doc research | avoid | avoid | narrow preflight only | Local graph evidence may contextualize explicit H/G/run IDs; it does not replace official/current research |\n| `ln-110`, `ln-130`, `ln-200`, `ln-521`, `ln-812` | avoid by default | avoid | avoid by default | Docs, planning, market research, and external research should not force MCP code tools |\n\n## Structural Expectations\n\nIf a skill is marked `REQUIRED`:\n- include the relevant tool names in `allowed-tools`\n- load `references/mcp_tool_preferences.md`\n- for semantic-code skills, also load `references/mcp_integration_patterns.md`\n- for researchgraph-dependent skills, load `references/researchgraph_mcp_usage.md`\n- state primary-vs-fallback ordering in the body\n\nIf a skill is marked `avoid`:\n- do not add `hex-graph`, `hex-line`, or `hex-research` unless the workflow truly edits local code-like files, makes semantic-code decisions, or consumes a researchgraph layout\n- if used anyway, justify the use case in scope text\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4405,"content_sha256":"0c5a4ee76119cd2842c0a40c336f80956bd64f9240158fd70a12895d11fbc51c"},{"filename":"references/mcp_integration_patterns.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/mcp_integration_patterns.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# MCP Integration Patterns\n\nUse these only when a skill edits code/config/scripts/tests or makes semantic decisions from existing code. They are not required for docs-only, community, planning-only, external research, runtime verification, benchmark, or profiling work.\n\n## Patterns\n\n| Pattern | Use When | Flow |\n|---------|----------|------|\n| Outline-first read | unfamiliar code or large text file | `outline` or narrow `read_file` ranges before full reads |\n| Verified edit | repository text mutation | `read_file(edit_ready=true)` -> `edit_file(base_revision)` -> verify/check changes |\n| Semantic impact | public API, route, class, function, architecture, or non-trivial edit | `index_project` -> `analyze_edit_region` or symbol inspection |\n| Semantic diff review | reviewing implementation risk | `analyze_changes` or scoped `changes` |\n| Bulk literal cleanup | same replacement across several files | preview/dry-run first, then apply narrowly |\n\n## Skill Integration\n\nFor code-editing skills, require `mcp_tool_preferences.md` and this file only when host-level instructions do not already provide equivalent MCP policy. Otherwise, state the local tool need inline and rely on the host policy.\n\nFor semantic code reasoning, use `hex-graph` only after narrowing the project/path enough for useful results. For raw method-call or string patterns, use text search first.\n\n---\n**Version:** 3.0.0\n**Last Updated:** 2026-03-20\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1567,"content_sha256":"f0aff34db7d833bafdabe6080d55f0545046e07e1552778dafc8eb722f963659"},{"filename":"references/mcp_tool_preferences.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/mcp_tool_preferences.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Tool Preferences for Code Work\n\nCompact hard rules for skills that materially inspect or edit repository code, config, scripts, or tests.\n\n## Primary Policy\n\n- Use `hex-line` first for repository text reads/search/edits when available.\n- Use `hex-graph` first only for semantic code questions: symbol identity, references, architecture, edit blast radius, clone groups, or semantic diff risk.\n- Use `hex-research` first only for project researchgraph questions: hypotheses, goals, benchmark runs, evidence, lineage, goal alignment, proposal readiness, or graph drift.\n- Use built-in Read/Edit/Write/Grep/Glob or shell only when MCP is unavailable, unsupported, outside scope, or the task is shell-native.\n- Do not use repo-wide shell search/read patterns when `hex-line` or `hex-graph` covers the task.\n- Do not require `hex-graph` for docs, community, external research, runtime execution, profiling, benchmarking, or other work that does not depend on semantic code structure.\n- Do not require `hex-research` unless the project has `docs/hypotheses/`, `docs/goals/`, or `benchmark/runs/*/manifest.yaml` and graph state can change the decision.\n\n## Minimal Flow\n\n| Need | Preferred flow |\n|------|----------------|\n| Discover files | `inspect_path` with a narrow path |\n| Search text | `grep_search(output_mode=\"summary\")`, then narrow before content mode |\n| Read code | `outline` or targeted `read_file`; use edit-ready reads only before verified edits |\n| Edit code | `read_file(edit_ready=true)` -> `edit_file(base_revision)` -> verify/check changes |\n| Semantic risk | `index_project` -> symbol/architecture/edit-region analysis |\n| Researchgraph status | `verify_index` -> targeted hypothesis/goal/run query or audit |\n\n## Fallback Contract\n\nFallbacks are valid for Git history, builds, tests, package managers, containers, images, PDFs, notebooks, external websites, binary/media files, paths outside the project root, unsupported languages, unavailable MCP servers, missing researchgraph layout, or small markdown/metadata reads where MCP setup adds no value.\n\nWhen falling back, keep the scope narrow and preserve the same evidence standard.\n\n---\n**Version:** 5.0.0\n**Last Updated:** 2026-03-20\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2338,"content_sha256":"578914a82f4825c50cee778ecdefd9346cd60f3a24f2f64d1df7f078dade1e3d"},{"filename":"references/meta_analysis_protocol.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/meta_analysis_protocol.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Meta-Analysis Protocol\n\nOptional post-run self-audit for skills that need protocol-formatted reflection. Do not load this file by default; load it only when the user asks for meta-analysis, when a command explicitly requires a run retrospective, or when debugging repeated skill failures.\n\n## Use When Requested\n\nProduce only actionable findings from the current run:\n- deliverable gaps against the user's goal\n- failed, wasted, or repeated tool/agent steps\n- worker or subagent failures that changed the result\n- concrete skill or command improvements tied to observed evidence\n\nSkip generic SDLC commentary. If there are no findings, write: `Meta-analysis: clean run.`\n\n## Output\n\n```markdown\n### Meta-Analysis: {Skill Name}\n\n#### Improvements\n| # | Finding | Target | Fix |\n|---|---------|--------|-----|\n| 1 | {observed issue} | {skill/phase/file} | {specific change} |\n\n#### Session Errors\n| Problem Type | Count | Examples |\n|--------------|-------|----------|\n| {type} | {N} | {brief examples} |\n```\n\nOmit empty sections. For subagents, add a separate `#### Subagent Errors: {Agent Name}` table only when that agent had material failures.\n\n## Issue Suggestion Trigger\n\nIf the same failure pattern is reproducible across multiple runs, suggest creating an issue with the affected skill, evidence, and expected fix.\n\n---\n**Version:** 4.2.0\n**Last Updated:** 2026-03-21\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1509,"content_sha256":"b97ce62dc95b7fe171baef2fbc5f7cdb91626e1b2fee14a7850cd02c02f77b49"},{"filename":"references/procedural_skill_sop_guide.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/procedural_skill_sop_guide.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Procedural Skill SOP/TWI Guide\n\n**Version:** 1.0.0\n**Last Updated:** 2026-04-25\n\n> **Paths:** All paths are relative to the skills repository root.\n\n## Purpose\n\nUse this guide when writing procedural, orchestrating, or mutating skills: skills that tell an agent how to change files, move work through a state machine, invoke workers, update external systems, or recover from failures.\n\nThe goal is reliable execution, not longer prose.\n\n## Procedural Step Model\n\nWrite risky workflow steps with this shape:\n\n| Field | Requirement |\n|-------|-------------|\n| Action | One concrete action the agent can execute now |\n| Key point | The non-obvious constraint that prevents the common mistake |\n| Why | Why the key point matters; prevents quiet improvisation |\n| Evidence | Observable artifact, status, diff, checkpoint, or command output |\n| Exception | What to do when the step cannot be completed |\n| Automation/guard | Script, runtime guard, checklist, or validator that can catch failure |\n\nUse the full shape at high-risk points. Low-risk linear steps can stay compact.\n\n## Point-of-Use Checklists\n\nCritical checks must be placed where the risk occurs.\n\nDo this:\n- Put worker artifact validation immediately after worker invocation.\n- Put retry/loop checks immediately before another retry.\n- Put permission/tool/auth preflight before external agent launch.\n- Put status-transition assertions next to the transition.\n\nDo not rely on a final Definition of Done to catch missed critical checks. Final DoD verifies completion; point-of-use checklists prevent bad execution.\n\n## TWI Rule\n\nFor risky steps, include:\n\n```text\nAction: {do this}\nKey point: {critical detail}\nWhy: {consequence if skipped}\nEvidence: {what proves it happened}\nException: {pause/retry/ask path}\nAutomation/guard: {script/check/runtime field}\n```\n\n## Wording Rules\n\nAvoid vague modal words in executable workflow steps:\n- `typically`\n- `periodically`\n- `regularly`\n- `as needed`\n- `when appropriate`\n\nReplace them with exact triggers:\n- `after every worker run`\n- `before retrying the same task`\n- `when artifact_path is missing`\n- `if the same error signature repeats 3 times`\n\n## Compound Step Rule\n\nOne step should contain one action. Split steps that say:\n- do A and then B\n- inspect A, update B, and report C\n- run X; if it fails, run Y; otherwise update Z\n\nDecision branches are allowed, but each branch needs its own action and evidence.\n\n## Runtime Compatibility\n\nIf a skill depends on tooling, include a first self-check that proves the runtime can execute it:\n- command exists\n- auth exists when required\n- expected config file exists\n- required MCP/tool namespace is available\n- output path is writable\n\nWhen a self-check fails, pause with a concrete operator action instead of treating it as a domain failure.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2934,"content_sha256":"b70e5a0d4a5bf75790f04fa3348b976d30fd86c4ef6eefa038c2c3a0df8d35fe"},{"filename":"references/researchgraph_mcp_usage.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/researchgraph_mcp_usage.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Research Graph MCP Usage\n\n\u003c!-- SCOPE: Routing policy for using hex-research MCP against hypothesis, goal, evidence, and benchmark graphs. -->\n\n## Applicability\n\nUse `hex-research` only when project evidence can change planning, validation, readiness, scope, or priority and the project has at least one canonical graph path: `docs/hypotheses/*.md`, `docs/goals/*.md`, or `benchmark/runs/*/manifest.yaml`.\n\nDo not use it for code symbol identity, references, architecture, or edit blast radius; those remain `hex-graph` concerns.\n\n## Safety Rules\n\n- Prefer read-only query/audit tools first.\n- Start with `verify_index({ path })`.\n- Run `index_hypotheses({ path })` only when the index is missing, stale, explicitly requested, or current graph state is required.\n- Treat `STALE` as graph debt, not tool failure.\n- Treat `INVALID` from `verify_index` as diagnostic state; `INVALID` from `index_hypotheses` means rebuild failed.\n- Goal `metrics_current` is derived from explicit comprehensive run manifests; manual `metrics_current` in goal frontmatter is drift.\n- Source quality is derived from `sources`, optional `docs/sources/lib.yaml`, source type inference, and weighted `evidence_depth`.\n- Run `export_canvas` and `export_research_map` with `dry_run: true` before writing.\n- If MCP is unavailable, read split markdown/manifests manually and mark confidence degraded.\n\n## Intent Routing\n\n| Intent | Tool |\n|--------|------|\n| freshness | `verify_index` |\n| rebuild/first index | `index_hypotheses` |\n| hypothesis search/status | `find_hypotheses` |\n| inspect `H##` / `G##` | `inspect_hypothesis` / `inspect_goal` |\n| evidence, citations, benchmark runs | `find_evidence`, `find_runs` |\n| lineage, graph shape, goal tree | `trace_lineage`, `analyze_topology`, `trace_goal_tree` |\n| gaps, drift, readiness | `audit_orphans`, `audit_goal_alignment`, `analyze_progress`, `analyze_proposed` |\n| goal metric drift / missing comprehensive metrics | `inspect_goal`, `audit_goal_alignment` |\n| source quality / evidence depth | `inspect_hypothesis`, `find_evidence`, `analyze_proposed` |\n| field-level diff | `analyze_progress` |\n| visual map / generated research-map.md | `export_canvas`, `export_research_map` |\n\n## Integration Rules\n\n- Planning/review skills use graph evidence only when H/G IDs, benchmark runs, readiness, or changed researchgraph files affect the decision.\n- External-doc research still prioritizes official/current sources; graph evidence is local preflight only.\n- Task planning keeps `hex-graph` for code modules and uses `hex-research` only for hypothesis/task readiness and proposal status.\n- Manual fallback reads frontmatter in hypotheses/goals, narrowed benchmark manifests, and wiki links by direct file lookup; label lineage/topology/drift as manual approximations.\n\n---\n**Version:** 0.1.0\n**Last Updated:** 2026-05-08\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2981,"content_sha256":"128b6ff36dbe20a5d2337dba38862a6b4c0d7f85867c7c27f3c95589f8f66016"},{"filename":"references/scripts/check_marketplace.mjs","content":"#!/usr/bin/env node\n// Checks marketplace.json skill count for a given plugin name.\n// Usage: node check_marketplace.mjs \u003cplugin-name>\n// Returns: skill count (number) to stdout\n\nimport { readFileSync } from 'fs';\n\nconst plugin = process.argv[2];\nif (!plugin) { console.log(0); process.exit(0); }\n\nconst manifest = JSON.parse(readFileSync('.claude-plugin/marketplace.json', 'utf8'));\nconst entry = manifest.plugins.find(p => p.name === plugin);\nconsole.log(entry ? entry.skills.length : 0);\n","content_type":"text/javascript","language":"javascript","size":491,"content_sha256":"623b0cb8034f6463248deb7c639bf01e457db87b8ac90d3a5e28ffc5c753f3f9"},{"filename":"references/scripts/coordinator-runtime/lib/artifacts.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/artifacts.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nfunction safeSegment(value) {\n return String(value || \"default\")\n .trim()\n .replace(/[^a-zA-Z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase() || \"default\";\n}\n\nexport function runtimeArtifactDir(projectRoot, runId, summaryKind) {\n return join(\n resolve(projectRoot || process.cwd()),\n \".hex-skills\",\n \"runtime-artifacts\",\n \"runs\",\n safeSegment(runId),\n safeSegment(summaryKind),\n );\n}\n\nexport function runtimeArtifactPath(projectRoot, runId, summaryKind, identifier) {\n return join(runtimeArtifactDir(projectRoot, runId, summaryKind), `${safeSegment(identifier)}.json`);\n}\n\nexport function runtimeArtifactPathForFile(projectRoot, runId, summaryKind, fileName) {\n return join(runtimeArtifactDir(projectRoot, runId, summaryKind), fileName);\n}\n\nexport function resolveArtifactWritePath(projectRoot, artifactPath) {\n const resolvedProjectRoot = resolve(projectRoot || process.cwd());\n const resolvedArtifactPath = resolve(resolvedProjectRoot, artifactPath);\n if (dirname(resolvedArtifactPath) === resolvedProjectRoot) {\n throw new Error(\"Runtime artifacts must not be written to the project root\");\n }\n return resolvedArtifactPath;\n}\n\nexport function writeRuntimeArtifactJsonToPath(projectRoot, artifactPath, payload) {\n const resolvedArtifactPath = resolveArtifactWritePath(projectRoot, artifactPath);\n mkdirSync(dirname(resolvedArtifactPath), { recursive: true });\n writeFileSync(resolvedArtifactPath, JSON.stringify(payload, null, 2) + \"\\n\", \"utf8\");\n return resolvedArtifactPath;\n}\n\nexport function writeRuntimeArtifactJson(projectRoot, runId, summaryKind, identifier, payload) {\n const artifactPath = runtimeArtifactPath(projectRoot, runId, summaryKind, identifier);\n const nextPayload = payload && typeof payload === \"object\" && payload.payload && typeof payload.payload === \"object\"\n ? {\n ...payload,\n payload: {\n ...payload.payload,\n artifact_path: payload.payload.artifact_path || artifactPath,\n },\n }\n : payload;\n return writeRuntimeArtifactJsonToPath(projectRoot, artifactPath, nextPayload);\n}\n","content_type":"text/javascript","language":"javascript","size":2463,"content_sha256":"b920166d0ad5bad12343c792a8b8f59abc88172d405c238290b8cf20f70a3898"},{"filename":"references/scripts/coordinator-runtime/lib/cli-helpers.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/cli-helpers.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nexport function outputJson(data) {\n process.stdout.write(JSON.stringify(data, null, 2) + \"\\n\");\n}\n\nexport function failJson(message, code = 2) {\n process.stderr.write(JSON.stringify({ ok: false, error: message }) + \"\\n\");\n process.exit(code);\n}\n\nexport function failResult(result, code = 2) {\n if (typeof result === \"string\") {\n failJson(result, code);\n }\n process.stderr.write(JSON.stringify({ ok: false, ...result }) + \"\\n\");\n process.exit(code);\n}\n\nfunction windowsTmpHint(filePath) {\n if (process.platform !== \"win32\") return \"\";\n if (typeof filePath !== \"string\") return \"\";\n // Detect both raw Unix-style (/tmp/, /var/, /home/, /root/) and Git Bash\n // MSYS-translated Windows temp paths (AppData/Local/Temp, /Temp/, Temp\\).\n const unixStyle = /^\\/(tmp|var|home|root)\\//.test(filePath);\n const winTemp = /AppData[\\\\/]Local[\\\\/]Temp|[\\\\/]Temp[\\\\/]/i.test(filePath);\n if (!unixStyle && !winTemp) return \"\";\n return ` Hint: path \"${filePath}\" looks like a temp path on Windows. Git Bash resolves /tmp/ to a location that Node.js CLIs cannot always read (MSYS vs native path mismatch). Use a project-relative path (e.g. .hex-skills/runtime/) instead.`;\n}\n\nexport function readPayload(values, readJsonFile) {\n if (values[\"payload-file\"]) {\n const payload = readJsonFile(values[\"payload-file\"]);\n if (payload == null) {\n failJson(`Unable to read payload file: ${values[\"payload-file\"]}.${windowsTmpHint(values[\"payload-file\"])}`);\n }\n return payload;\n }\n if (!values.payload) {\n return {};\n }\n try {\n return JSON.parse(values.payload);\n } catch (error) {\n failJson(`Invalid JSON payload: ${error.message}`);\n }\n}\n\nexport function readManifestOrFail(values, readJsonFile, flagName = \"manifest-file\") {\n const filePath = values[flagName];\n const manifest = readJsonFile(filePath);\n if (manifest == null) {\n failJson(`Manifest file not found or invalid: ${filePath}.${windowsTmpHint(filePath)}`);\n }\n return manifest;\n}\n\nfunction buildRuntimeMeta(run, stateOverride = null) {\n const state = stateOverride || run.state;\n return {\n skill: run.manifest.skill,\n identifier: run.manifest.identifier,\n run_id: state.run_id,\n phase: state.phase,\n complete: state.complete,\n };\n}\n\nexport function outputInactiveRuntime(output) {\n output({\n ok: true,\n active: false,\n runtime: null,\n });\n}\n\nexport function outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction) {\n output({\n ok: true,\n active: !run.state.complete,\n runtime: buildRuntimeMeta(run),\n manifest: run.manifest,\n state: run.state,\n checkpoints: run.checkpoints,\n paths: runtimePaths(projectRoot, run.state.run_id, run.manifest.skill, run.manifest.identifier),\n resume_action: computeResumeAction(run.manifest, run.state, run.checkpoints),\n });\n}\n\nexport function outputRuntimeState(output, run, state, extra = {}) {\n output({\n ok: true,\n runtime: buildRuntimeMeta(run, state),\n state,\n ...extra,\n });\n}\n\nexport function outputGuardFailure(output, guard) {\n output({\n ok: false,\n error: guard.error || \"Transition blocked\",\n validation_errors: guard.details || [],\n guard,\n });\n process.exit(1);\n}\n","content_type":"text/javascript","language":"javascript","size":3569,"content_sha256":"97c265d018bcc12185f997bf9398e818450678d5d34662ceb9e91a46bedb4ea5"},{"filename":"references/scripts/coordinator-runtime/lib/core.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/core.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n appendFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n activePointerSchema,\n buildRuntimeStateSchema,\n runtimeCheckpointEntrySchema,\n runtimeCheckpointHistorySchema,\n runtimeHistoryEventSchema,\n} from \"./schemas.mjs\";\nimport { assertSchema } from \"./validate.mjs\";\nimport { updateLoopHealthMap } from \"./loop-health.mjs\";\n\nconst LOCK_FILE = \".lock\";\nconst HISTORY_FILE = \"history.jsonl\";\n\nfunction resolveParts(projectRoot, parts) {\n return join(resolve(projectRoot || process.cwd()), ...(parts || []));\n}\n\nfunction safeReadJson(filePath) {\n try {\n return JSON.parse(readFileSync(filePath, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction safeIdentifier(value) {\n return String(value || \"default\")\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase() || \"default\";\n}\n\nfunction atomicWrite(filePath, data) {\n mkdirSync(dirname(filePath), { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}`;\n try {\n writeFileSync(tmpPath, JSON.stringify(data, null, 2) + \"\\n\", \"utf8\");\n renameSync(tmpPath, filePath);\n } catch (error) {\n try {\n unlinkSync(tmpPath);\n } catch {\n // Best-effort cleanup only.\n }\n throw error;\n }\n}\n\nfunction defaultRunId(skill, identifier) {\n const safeSkill = safeIdentifier(skill || \"runtime\");\n const safeRunIdentifier = safeIdentifier(identifier || \"run\");\n return `${safeSkill}-${safeRunIdentifier}-${Date.now()}-${randomUUID().slice(0, 8)}`;\n}\n\nfunction normalizeCheckpoints(raw) {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return { _history: [], _next_sequence: 1 };\n }\n if (Array.isArray(raw._history)) {\n return {\n ...raw,\n _history: raw._history,\n _next_sequence: Number(raw._next_sequence || (raw._history.length + 1)),\n };\n }\n const history = Object.entries(raw)\n .filter(([key, value]) => !key.startsWith(\"_\") && value && typeof value === \"object\")\n .map(([phase, entry], index) => ({\n sequence: Number(entry.sequence || (index + 1)),\n phase,\n created_at: entry.created_at || new Date().toISOString(),\n payload: entry.payload || {},\n }));\n return {\n ...raw,\n _history: history,\n _next_sequence: history.length + 1,\n };\n}\n\nfunction appendCheckpoint(checkpoints, phase, payload) {\n const next = normalizeCheckpoints(checkpoints);\n const entry = {\n sequence: next._next_sequence,\n phase,\n created_at: new Date().toISOString(),\n payload: payload || {},\n };\n const entryValidation = assertSchema(runtimeCheckpointEntrySchema, entry, \"checkpoint entry\");\n if (!entryValidation.ok) {\n throw new Error(entryValidation.error);\n }\n const nextCheckpoints = {\n ...next,\n [phase]: entry,\n _history: [...next._history, entry],\n _next_sequence: entry.sequence + 1,\n };\n const checkpointsValidation = assertSchema(runtimeCheckpointHistorySchema, nextCheckpoints, \"checkpoint history\");\n if (!checkpointsValidation.ok) {\n throw new Error(checkpointsValidation.error);\n }\n return nextCheckpoints;\n}\n\nfunction acquireLock(dir) {\n const lockPath = join(dir, LOCK_FILE);\n mkdirSync(dir, { recursive: true });\n if (existsSync(lockPath)) {\n const existing = safeReadJson(lockPath);\n if (existing?.pid) {\n try {\n process.kill(existing.pid, 0);\n return { ok: false, error: `Runtime already running (PID ${existing.pid})` };\n } catch {\n // Stale lock.\n }\n }\n }\n atomicWrite(lockPath, { pid: process.pid, started_at: new Date().toISOString() });\n return { ok: true };\n}\n\nfunction releaseLock(dir) {\n try {\n unlinkSync(join(dir, LOCK_FILE));\n } catch {\n // Best-effort cleanup only.\n }\n}\n\nfunction withLock(dir, action) {\n const lock = acquireLock(dir);\n if (!lock.ok) {\n return lock;\n }\n try {\n return action();\n } finally {\n releaseLock(dir);\n }\n}\n\nfunction readHistory(filePath) {\n if (!existsSync(filePath)) {\n return [];\n }\n const content = readFileSync(filePath, \"utf8\");\n return content\n .split(/\\r?\\n/u)\n .map(line => line.trim())\n .filter(Boolean)\n .map(line => {\n try {\n return JSON.parse(line);\n } catch {\n return null;\n }\n })\n .filter(Boolean);\n}\n\nfunction appendHistoryEvent(filePath, eventType, payload) {\n mkdirSync(dirname(filePath), { recursive: true });\n const events = readHistory(filePath);\n const nextEvent = {\n sequence: events.length + 1,\n event_type: eventType,\n created_at: new Date().toISOString(),\n ...payload,\n };\n const validation = assertSchema(runtimeHistoryEventSchema, nextEvent, \"runtime history event\");\n if (!validation.ok) {\n throw new Error(validation.error);\n }\n appendFileSync(filePath, `${JSON.stringify(nextEvent)}\\n`, \"utf8\");\n return nextEvent;\n}\n\nfunction rebuildFromHistory(events, fallback) {\n let manifest = fallback?.manifest || null;\n let state = fallback?.state || null;\n let checkpoints = normalizeCheckpoints(fallback?.checkpoints || {});\n\n for (const event of events) {\n switch (event.event_type) {\n case \"RUN_STARTED\":\n manifest = event.manifest || manifest;\n state = event.state || state;\n checkpoints = normalizeCheckpoints(event.checkpoints || checkpoints);\n break;\n case \"STATE_SAVED\":\n case \"RUN_PAUSED\":\n case \"RUN_COMPLETED\":\n case \"LOOP_HEALTH_RECORDED\":\n state = event.state || state;\n break;\n case \"CHECKPOINT_RECORDED\":\n checkpoints = appendCheckpoint(checkpoints, event.phase, event.payload || {});\n break;\n default:\n break;\n }\n }\n\n if (!manifest || !state) {\n return null;\n }\n\n return { manifest, state, checkpoints, history: events };\n}\n\nexport function readJsonFile(filePath) {\n return safeReadJson(filePath);\n}\n\nexport function resolveTrackedPath(projectRoot, filePath) {\n if (!filePath) {\n return null;\n }\n return resolve(projectRoot || process.cwd(), filePath);\n}\n\nexport function fileExists(filePath) {\n return existsSync(filePath);\n}\n\nexport function createRuntimeStore(config) {\n const baseRootParts = config.baseRootParts;\n const activeRootParts = config.activeRootParts || baseRootParts;\n const stateSchema = config.stateSchema || buildRuntimeStateSchema();\n const runsSubdir = Object.prototype.hasOwnProperty.call(config, \"runsSubdir\")\n ? config.runsSubdir\n : \"runs\";\n\n function baseRoot(projectRoot) {\n return resolveParts(projectRoot, baseRootParts);\n }\n\n function activeRoot(projectRoot) {\n return resolveParts(projectRoot, activeRootParts);\n }\n\n function runsDir(projectRoot) {\n return runsSubdir ? join(baseRoot(projectRoot), runsSubdir) : baseRoot(projectRoot);\n }\n\n function runDir(projectRoot, runId) {\n return join(runsDir(projectRoot), runId);\n }\n\n function manifestPath(projectRoot, runId) {\n return join(runDir(projectRoot, runId), \"manifest.json\");\n }\n\n function statePath(projectRoot, runId) {\n return join(runDir(projectRoot, runId), \"state.json\");\n }\n\n function checkpointsPath(projectRoot, runId) {\n return join(runDir(projectRoot, runId), \"checkpoints.json\");\n }\n\n function historyPath(projectRoot, runId) {\n return join(runDir(projectRoot, runId), HISTORY_FILE);\n }\n\n function activeDir(projectRoot, skill) {\n return join(activeRoot(projectRoot), \"active\", safeIdentifier(skill));\n }\n\n function activePath(projectRoot, skill, identifier) {\n return join(activeDir(projectRoot, skill), `${safeIdentifier(identifier)}.json`);\n }\n\n function listActiveRuns(projectRoot, skill) {\n const dir = activeDir(projectRoot, skill);\n if (!existsSync(dir)) {\n return [];\n }\n return readdirSync(dir)\n .filter(name => name.endsWith(\".json\"))\n .map(name => safeReadJson(join(dir, name)))\n .filter(pointer => pointer?.run_id);\n }\n\n function loadRun(projectRoot, runId) {\n const manifest = safeReadJson(manifestPath(projectRoot, runId));\n const state = safeReadJson(statePath(projectRoot, runId));\n const checkpoints = normalizeCheckpoints(safeReadJson(checkpointsPath(projectRoot, runId)));\n const history = readHistory(historyPath(projectRoot, runId));\n if (history.length > 0) {\n return rebuildFromHistory(history, { manifest, state, checkpoints });\n }\n if (!manifest || !state) {\n return null;\n }\n return { manifest, state, checkpoints, history: [] };\n }\n\n function loadActiveRun(projectRoot, skill, identifier) {\n const pointer = identifier\n ? safeReadJson(activePath(projectRoot, skill, identifier))\n : (() => {\n const activeRuns = listActiveRuns(projectRoot, skill);\n return activeRuns.length === 1 ? activeRuns[0] : null;\n })();\n if (!pointer?.run_id) {\n return null;\n }\n return loadRun(projectRoot, pointer.run_id);\n }\n\n function saveActive(projectRoot, skill, identifier, runId) {\n const pointer = {\n skill,\n identifier,\n run_id: runId,\n updated_at: new Date().toISOString(),\n };\n const validation = assertSchema(activePointerSchema, pointer, \"active runtime pointer\");\n if (!validation.ok) {\n throw new Error(validation.error);\n }\n atomicWrite(activePath(projectRoot, skill, identifier), pointer);\n }\n\n function clearActive(projectRoot, skill, identifier, runId) {\n const filePath = activePath(projectRoot, skill, identifier);\n const pointer = safeReadJson(filePath);\n if (pointer?.run_id && pointer.run_id !== runId) {\n return;\n }\n try {\n unlinkSync(filePath);\n } catch {\n // Best-effort cleanup only.\n }\n }\n\n function startRun(projectRoot, manifestInput) {\n const manifest = config.normalizeManifest(manifestInput, projectRoot);\n if (!manifest.skill || !manifest.identifier) {\n return { ok: false, error: \"Manifest normalization must set skill and identifier\" };\n }\n if (config.manifestSchema) {\n const validation = assertSchema(config.manifestSchema, manifest, `${manifest.skill} manifest`);\n if (!validation.ok) {\n return validation;\n }\n }\n\n const activeRun = loadActiveRun(projectRoot, manifest.skill, manifest.identifier);\n if (activeRun && !activeRun.state.complete) {\n return { ok: false, recovery: true, run: activeRun };\n }\n\n const runId = (config.buildRunId || defaultRunId)(manifest.skill, manifest.identifier, manifestInput);\n const state = config.defaultState(manifest, runId);\n const stateValidation = assertSchema(stateSchema, state, `${manifest.skill} state`);\n if (!stateValidation.ok) {\n return stateValidation;\n }\n const checkpoints = normalizeCheckpoints({});\n const checkpointsValidation = assertSchema(runtimeCheckpointHistorySchema, checkpoints, `${manifest.skill} checkpoints`);\n if (!checkpointsValidation.ok) {\n return checkpointsValidation;\n }\n const result = withLock(baseRoot(projectRoot), () => {\n atomicWrite(manifestPath(projectRoot, runId), manifest);\n atomicWrite(statePath(projectRoot, runId), state);\n atomicWrite(checkpointsPath(projectRoot, runId), checkpoints);\n appendHistoryEvent(historyPath(projectRoot, runId), \"RUN_STARTED\", {\n run_id: runId,\n manifest,\n state,\n checkpoints,\n });\n saveActive(projectRoot, manifest.skill, manifest.identifier, runId);\n return { ok: true, run_id: runId, manifest, state, checkpoints };\n });\n return result;\n }\n\n function saveState(projectRoot, runId, state, eventType = \"STATE_SAVED\") {\n const nextState = {\n ...state,\n updated_at: new Date().toISOString(),\n };\n const validation = assertSchema(stateSchema, nextState, \"runtime state\");\n if (!validation.ok) {\n return validation;\n }\n const result = withLock(baseRoot(projectRoot), () => {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n atomicWrite(statePath(projectRoot, runId), nextState);\n appendHistoryEvent(historyPath(projectRoot, runId), eventType, {\n run_id: runId,\n state: nextState,\n });\n if (!nextState.complete) {\n saveActive(projectRoot, nextState.skill, nextState.identifier, runId);\n }\n return { ok: true, state: nextState };\n });\n return result.ok === false ? result : result.state;\n }\n\n function checkpointPhase(projectRoot, runId, phase, payload) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const nextCheckpoints = appendCheckpoint(run.checkpoints, phase, payload);\n return withLock(baseRoot(projectRoot), () => {\n atomicWrite(checkpointsPath(projectRoot, runId), nextCheckpoints);\n appendHistoryEvent(historyPath(projectRoot, runId), \"CHECKPOINT_RECORDED\", {\n run_id: runId,\n phase,\n payload: payload || {},\n });\n return { ok: true, checkpoints: nextCheckpoints };\n });\n }\n\n function updateState(projectRoot, runId, updater, options = {}) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const nextState = typeof updater === \"function\" ? updater(run.state, run) : updater;\n const saved = saveState(projectRoot, runId, nextState, options.eventType || \"STATE_SAVED\");\n if (saved?.ok === false) {\n return saved;\n }\n return { ok: true, state: saved };\n }\n\n function pauseRun(projectRoot, runId, reason) {\n return updateState(projectRoot, runId, state => ({\n ...state,\n phase: \"PAUSED\",\n paused_reason: reason || \"Paused\",\n pending_decision: null,\n }), { eventType: \"RUN_PAUSED\" });\n }\n\n function recordLoopHealth(projectRoot, runId, scopeKey, signal, options = {}) {\n let recordedEntry = null;\n let pauseRecommendation = null;\n const result = updateState(projectRoot, runId, state => {\n const updated = updateLoopHealthMap(state.loop_health || {}, scopeKey, signal, options.policy || {});\n recordedEntry = updated.entry;\n pauseRecommendation = updated.pause;\n const pauseState = options.pauseOnRecommendation !== false && updated.pause.pause\n ? {\n phase: \"PAUSED\",\n paused_reason: updated.pause.reason || \"Loop health pause\",\n pending_decision: null,\n }\n : {};\n return {\n ...state,\n ...pauseState,\n loop_health: updated.map,\n };\n }, { eventType: \"LOOP_HEALTH_RECORDED\" });\n if (!result.ok) {\n return result;\n }\n return {\n ok: true,\n state: result.state,\n loop_health: recordedEntry,\n pause: pauseRecommendation,\n };\n }\n\n function completeRun(projectRoot, runId) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const result = updateState(projectRoot, runId, state => ({\n ...state,\n phase: \"DONE\",\n complete: true,\n paused_reason: null,\n pending_decision: null,\n }), { eventType: \"RUN_COMPLETED\" });\n if (!result.ok) {\n return result;\n }\n clearActive(projectRoot, run.state.skill, run.state.identifier, runId);\n return result;\n }\n\n function resolveRunId(projectRoot, skill, runId, identifier) {\n if (runId) {\n return runId;\n }\n if (identifier) {\n const pointer = safeReadJson(activePath(projectRoot, skill, identifier));\n return pointer?.run_id || null;\n }\n const activeRuns = listActiveRuns(projectRoot, skill);\n if (activeRuns.length !== 1) {\n return null;\n }\n return activeRuns[0].run_id;\n }\n\n function runtimePaths(projectRoot, runId, skill, identifier) {\n const resolvedRunId = resolveRunId(projectRoot, skill, runId, identifier);\n if (!resolvedRunId) {\n return null;\n }\n return {\n root: baseRoot(projectRoot),\n run_dir: runDir(projectRoot, resolvedRunId),\n manifest: manifestPath(projectRoot, resolvedRunId),\n state: statePath(projectRoot, resolvedRunId),\n checkpoints: checkpointsPath(projectRoot, resolvedRunId),\n history: historyPath(projectRoot, resolvedRunId),\n active: identifier ? activePath(projectRoot, skill, identifier) : activeDir(projectRoot, skill),\n };\n }\n\n return {\n baseRoot,\n runtimePaths,\n loadRun,\n loadActiveRun,\n listActiveRuns,\n startRun,\n saveState,\n checkpointPhase,\n updateState,\n recordLoopHealth,\n pauseRun,\n completeRun,\n clearActiveRun(projectRoot, skill, identifier, runId) {\n clearActive(projectRoot, skill, identifier, runId);\n },\n resolveRunId,\n readHistory(projectRoot, runId) {\n return readHistory(historyPath(projectRoot, runId));\n },\n };\n}\n","content_type":"text/javascript","language":"javascript","size":19048,"content_sha256":"c98153f400f67794480805bfa08004a9011a6d0830848fcfb27d4407ec765bbd"},{"filename":"references/scripts/coordinator-runtime/lib/loop-health.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/loop-health.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nexport const LOOP_HEALTH_FAILURE_CLASSES = Object.freeze({\n NONE: \"none\",\n TIMEOUT_IDLE: \"timeout_idle\",\n TIMEOUT_PRODUCTIVE: \"timeout_productive\",\n PERMISSION_DENIAL: \"permission_denial\",\n TOOL_MISSING: \"tool_missing\",\n AUTH_MISSING: \"auth_missing\",\n RATE_LIMITED: \"rate_limited\",\n ASKED_QUESTION: \"asked_question\",\n AGENT_ERROR: \"agent_error\",\n UNKNOWN: \"unknown\",\n});\n\nexport const DEFAULT_LOOP_HEALTH_POLICY = Object.freeze({\n no_progress_limit: 3,\n same_error_limit: 3,\n immediate_pause_failure_classes: Object.freeze([\n LOOP_HEALTH_FAILURE_CLASSES.PERMISSION_DENIAL,\n LOOP_HEALTH_FAILURE_CLASSES.TOOL_MISSING,\n LOOP_HEALTH_FAILURE_CLASSES.AUTH_MISSING,\n ]),\n defer_failure_classes: Object.freeze([\n LOOP_HEALTH_FAILURE_CLASSES.RATE_LIMITED,\n ]),\n});\n\nconst FAILURE_CLASS_SET = new Set(Object.values(LOOP_HEALTH_FAILURE_CLASSES));\n\nfunction asText(value) {\n if (value == null) return \"\";\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function normalizeErrorSignature(text) {\n return asText(text)\n .toLowerCase()\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/[a-z]:[\\\\/][^\\s)'\"`]+/gi, \"\u003cpath>\")\n .replace(/\\/(?:[^/\\s)'\"`]+\\/)+[^/\\s)'\"`]+/g, \"\u003cpath>\")\n .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, \"\u003cuuid>\")\n .replace(/\\b\\d{4}-\\d{2}-\\d{2}t\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?z\\b/g, \"\u003ctimestamp>\")\n .replace(/\\b\\d+\\b/g, \"\u003cnum>\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 240);\n}\n\nfunction hasProgressSignal(input = {}) {\n const signals = input.progress_signals || {};\n return Boolean(\n input.progress_detected\n || input.artifact_delta\n || input.checkpoint_delta\n || input.status_delta\n || input.files_changed_delta\n || input.scenario_improved\n || input.metric_improved\n || input.new_evidence\n || signals.output_written\n || signals.log_written\n || signals.session_captured\n );\n}\n\nfunction classifyFromText(text) {\n const normalized = normalizeErrorSignature(text);\n if (!normalized) return LOOP_HEALTH_FAILURE_CLASSES.NONE;\n if (/\\b(rate limit|rate_limited|too many requests|quota|429)\\b/.test(normalized)) {\n return LOOP_HEALTH_FAILURE_CLASSES.RATE_LIMITED;\n }\n if (/\\b(permission denied|not allowed|access denied|operation not permitted|blocked by permissions)\\b/.test(normalized)) {\n return LOOP_HEALTH_FAILURE_CLASSES.PERMISSION_DENIAL;\n }\n if (/\\b(command not found|not found in path|enoent|tool missing|required tool)\\b/.test(normalized)) {\n return LOOP_HEALTH_FAILURE_CLASSES.TOOL_MISSING;\n }\n if (/\\b(auth|authentication|unauthorized|login required|api key|token missing|credentials)\\b/.test(normalized)) {\n return LOOP_HEALTH_FAILURE_CLASSES.AUTH_MISSING;\n }\n if (/\\?\\s*$|should i|do you want|please confirm|need clarification/.test(normalized)) {\n return LOOP_HEALTH_FAILURE_CLASSES.ASKED_QUESTION;\n }\n return LOOP_HEALTH_FAILURE_CLASSES.UNKNOWN;\n}\n\nexport function classifyLoopSignal(input = {}) {\n const combinedText = [\n input.error,\n input.stderr,\n input.stdout,\n input.response,\n input.message,\n input.evidence_key,\n ].map(asText).filter(Boolean).join(\"\\n\");\n\n let failureClass = input.failure_class || null;\n if (!FAILURE_CLASS_SET.has(failureClass)) {\n failureClass = classifyFromText(combinedText);\n }\n\n const progressDetected = hasProgressSignal(input);\n const errorSignature = normalizeErrorSignature(input.error_signature || combinedText || failureClass);\n\n return {\n failure_class: failureClass,\n progress_detected: progressDetected,\n error_signature: errorSignature || null,\n evidence_key: input.evidence_key || errorSignature || failureClass,\n reason: input.reason || null,\n progress_signals: {\n output_written: Boolean(input.progress_signals?.output_written),\n log_written: Boolean(input.progress_signals?.log_written),\n session_captured: Boolean(input.progress_signals?.session_captured),\n },\n recorded_at: new Date().toISOString(),\n };\n}\n\nexport function shouldPause(loopHealth = {}) {\n return {\n pause: Boolean(loopHealth.pause_recommended),\n reason: loopHealth.pause_reason || null,\n category: loopHealth.pause_category || null,\n };\n}\n\nexport function updateLoopHealth(previous = {}, signalInput = {}, policyInput = {}) {\n const policy = {\n ...DEFAULT_LOOP_HEALTH_POLICY,\n ...policyInput,\n };\n const signal = signalInput.failure_class && signalInput.error_signature !== undefined\n ? signalInput\n : classifyLoopSignal(signalInput);\n\n const immediateSet = new Set(policy.immediate_pause_failure_classes || []);\n const deferSet = new Set(policy.defer_failure_classes || []);\n const previousSignature = previous.last_error_signature || null;\n const sameError = Boolean(signal.error_signature && signal.error_signature === previousSignature);\n\n const noProgressCount = signal.progress_detected\n ? 0\n : Number(previous.no_progress_count || 0) + 1;\n const sameErrorCount = signal.progress_detected\n ? 0\n : (sameError ? Number(previous.same_error_count || 0) + 1 : 1);\n\n let pauseRecommended = false;\n let pauseCategory = null;\n let pauseReason = null;\n\n if (immediateSet.has(signal.failure_class)) {\n pauseRecommended = true;\n pauseCategory = signal.failure_class;\n pauseReason = `Immediate blocker: ${signal.failure_class}`;\n } else if (deferSet.has(signal.failure_class)) {\n pauseRecommended = true;\n pauseCategory = signal.failure_class;\n pauseReason = \"Rate limited; defer retry without counting as domain failure\";\n } else if (sameErrorCount >= policy.same_error_limit) {\n pauseRecommended = true;\n pauseCategory = \"same_error\";\n pauseReason = `Same error repeated ${sameErrorCount} times without progress`;\n } else if (noProgressCount >= policy.no_progress_limit) {\n pauseRecommended = true;\n pauseCategory = \"no_progress\";\n pauseReason = `No progress recorded for ${noProgressCount} attempts`;\n }\n\n return {\n attempts: Number(previous.attempts || 0) + 1,\n no_progress_count: noProgressCount,\n same_error_count: sameErrorCount,\n last_failure_class: signal.failure_class,\n last_error_signature: signal.error_signature,\n last_evidence_key: signal.evidence_key || null,\n last_progress_detected: signal.progress_detected,\n last_signal_at: signal.recorded_at || new Date().toISOString(),\n pause_recommended: pauseRecommended,\n pause_category: pauseCategory,\n pause_reason: pauseReason,\n history: [\n ...(previous.history || []).slice(-9),\n signal,\n ],\n };\n}\n\nexport function updateLoopHealthMap(previousMap = {}, scopeKey, signalInput = {}, policyInput = {}) {\n const key = String(scopeKey || \"default\");\n const nextEntry = updateLoopHealth(previousMap[key] || {}, signalInput, policyInput);\n return {\n map: {\n ...previousMap,\n [key]: nextEntry,\n },\n entry: nextEntry,\n pause: shouldPause(nextEntry),\n };\n}\n","content_type":"text/javascript","language":"javascript","size":7667,"content_sha256":"2455b79952b6bf708840ff0bb0406e374bbd51fb2a7c374b4588c25deb42af46"},{"filename":"references/scripts/coordinator-runtime/lib/runtime-constants.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/runtime-constants.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nexport const TERMINAL_RUNTIME_PHASES = Object.freeze({\n PAUSED: \"PAUSED\",\n DONE: \"DONE\",\n});\n\nexport const RUNTIME_HISTORY_EVENT_TYPES = Object.freeze({\n RUN_STARTED: \"RUN_STARTED\",\n STATE_SAVED: \"STATE_SAVED\",\n RUN_PAUSED: \"RUN_PAUSED\",\n RUN_COMPLETED: \"RUN_COMPLETED\",\n CHECKPOINT_RECORDED: \"CHECKPOINT_RECORDED\",\n LOOP_HEALTH_RECORDED: \"LOOP_HEALTH_RECORDED\",\n});\n\nexport const RUNTIME_HISTORY_EVENT_TYPE_LIST = Object.freeze(Object.values(RUNTIME_HISTORY_EVENT_TYPES));\n\nexport const WORKER_SUMMARY_STATUSES = Object.freeze({\n COMPLETED: \"completed\",\n SKIPPED: \"skipped\",\n ERROR: \"error\",\n});\n\nexport const WORKER_SUMMARY_STATUS_LIST = Object.freeze(Object.values(WORKER_SUMMARY_STATUSES));\n\nexport const REVIEW_AGENT_STATUSES = Object.freeze({\n SKIPPED: \"skipped\",\n LAUNCHED: \"launched\",\n RESULT_READY: \"result_ready\",\n DEAD: \"dead\",\n FAILED: \"failed\",\n});\n\nexport const REVIEW_AGENT_STATUS_LIST = Object.freeze(Object.values(REVIEW_AGENT_STATUSES));\nexport const REVIEW_RESOLVED_AGENT_STATUS_LIST = Object.freeze([\n REVIEW_AGENT_STATUSES.RESULT_READY,\n REVIEW_AGENT_STATUSES.DEAD,\n REVIEW_AGENT_STATUSES.FAILED,\n REVIEW_AGENT_STATUSES.SKIPPED,\n]);\nexport const REVIEW_RESOLVED_AGENT_STATUS_SET = new Set(REVIEW_RESOLVED_AGENT_STATUS_LIST);\n\nexport const PLANNING_PROGRESS_STATUSES = Object.freeze({\n COMPLETED: \"completed\",\n});\n\nexport const OPTIMIZATION_GATE_VERDICTS = Object.freeze({\n PROCEED: \"PROCEED\",\n CONCERNS: \"CONCERNS\",\n WAIVED: \"WAIVED\",\n BLOCK: \"BLOCK\",\n});\n\nexport const OPTIMIZATION_GATE_VERDICT_LIST = Object.freeze(Object.values(OPTIMIZATION_GATE_VERDICTS));\n\nexport const OPTIMIZATION_VALIDATION_VERDICTS = Object.freeze({\n GO: \"GO\",\n GO_WITH_CONCERNS: \"GO_WITH_CONCERNS\",\n WAIVED: \"WAIVED\",\n NO_GO: \"NO_GO\",\n});\n\nexport const OPTIMIZATION_EXECUTION_ALLOWED_VERDICT_LIST = Object.freeze([\n OPTIMIZATION_VALIDATION_VERDICTS.GO,\n OPTIMIZATION_VALIDATION_VERDICTS.GO_WITH_CONCERNS,\n OPTIMIZATION_VALIDATION_VERDICTS.WAIVED,\n]);\n\nexport const OPTIMIZATION_CHECKPOINT_STATUSES = Object.freeze({\n COMPLETED: \"completed\",\n SKIPPED_BY_MODE: \"skipped_by_mode\",\n});\n\nexport const OPTIMIZATION_CYCLE_STATUSES = Object.freeze({\n COMPLETED: \"completed\",\n});\n\nexport const OPTIMIZATION_CYCLE_STATUS_LIST = Object.freeze(Object.values(OPTIMIZATION_CYCLE_STATUSES));\n\nexport const STORY_GATE_VERDICTS = Object.freeze({\n PASS: \"PASS\",\n CONCERNS: \"CONCERNS\",\n WAIVED: \"WAIVED\",\n FAIL: \"FAIL\",\n});\n\nexport const STORY_GATE_VERDICT_LIST = Object.freeze(Object.values(STORY_GATE_VERDICTS));\n\nexport const STORY_GATE_FINALIZATION_STATUSES = Object.freeze({\n SKIPPED_BY_VERDICT: \"skipped_by_verdict\",\n});\n\nexport const TASK_BOARD_STATUSES = Object.freeze({\n BACKLOG: \"Backlog\",\n TODO: \"Todo\",\n IN_PROGRESS: \"In Progress\",\n TO_REVIEW: \"To Review\",\n TO_REWORK: \"To Rework\",\n DONE: \"Done\",\n SKIPPED: \"SKIPPED\",\n VERIFIED: \"VERIFIED\",\n});\n\nexport const STORY_GATE_COMPLETED_TEST_STATUS_LIST = Object.freeze([\n TASK_BOARD_STATUSES.DONE,\n TASK_BOARD_STATUSES.SKIPPED,\n TASK_BOARD_STATUSES.VERIFIED,\n]);\n\nexport const STORY_GATE_PRE_VERIFICATION_ALLOWED_TEST_STATUS_LIST = Object.freeze([\n TASK_BOARD_STATUSES.DONE,\n TASK_BOARD_STATUSES.SKIPPED,\n]);\n\nexport const STORY_EXECUTION_GROUP_STATUSES = Object.freeze({\n COMPLETED: \"completed\",\n});\n\nexport const STORY_EXECUTION_GROUP_STATUS_LIST = Object.freeze(Object.values(STORY_EXECUTION_GROUP_STATUSES));\n\nexport const ENVIRONMENT_SETUP_FINAL_RESULTS = Object.freeze({\n READY: \"READY\",\n DRY_RUN_PLAN: \"DRY_RUN_PLAN\",\n});\n\nexport const STORY_EXECUTION_FINAL_RESULTS = Object.freeze({\n READY_FOR_GATE: \"READY_FOR_GATE\",\n});\n","content_type":"text/javascript","language":"javascript","size":3880,"content_sha256":"66610a99e5fb0d9108e93f3a74cabd2614089911b354019035968f918478a37b"},{"filename":"references/scripts/coordinator-runtime/lib/schemas.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/schemas.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n OPTIMIZATION_CYCLE_STATUS_LIST,\n REVIEW_AGENT_STATUS_LIST,\n RUNTIME_HISTORY_EVENT_TYPE_LIST,\n STORY_GATE_VERDICT_LIST,\n STORY_EXECUTION_GROUP_STATUS_LIST,\n WORKER_SUMMARY_STATUS_LIST,\n} from \"./runtime-constants.mjs\";\n\nfunction stringArraySchema() {\n return {\n type: \"array\",\n items: { type: \"string\" },\n };\n}\n\nfunction nullableStringSchema() {\n return { type: [\"string\", \"null\"] };\n}\n\nfunction nonNegativeIntegerSchema() {\n return { type: \"integer\", minimum: 0 };\n}\n\nfunction dateTimeSchema() {\n return { type: \"string\", format: \"date-time\" };\n}\n\nfunction baseDecisionRecordSchema() {\n return {\n type: \"object\",\n required: [\"kind\", \"selected_choice\", \"answered_at\"],\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", minLength: 1 },\n selected_choice: { type: \"string\", minLength: 1 },\n answered_at: dateTimeSchema(),\n context: { type: \"object\" },\n },\n };\n}\n\nexport function buildRuntimeStateSchema(extraProperties = {}, extraRequired = []) {\n return {\n type: \"object\",\n required: [\n \"run_id\",\n \"skill\",\n \"identifier\",\n \"phase\",\n \"complete\",\n \"paused_reason\",\n \"pending_decision\",\n \"decisions\",\n \"final_result\",\n \"created_at\",\n \"updated_at\",\n ...extraRequired,\n ],\n properties: {\n run_id: { type: \"string\", minLength: 1 },\n skill: { type: \"string\", minLength: 1 },\n mode: { type: [\"string\", \"null\"] },\n identifier: { type: \"string\", minLength: 1 },\n phase: { type: \"string\", minLength: 1 },\n complete: { type: \"boolean\" },\n paused_reason: nullableStringSchema(),\n pending_decision: { type: [\"object\", \"null\"] },\n decisions: {\n type: \"array\",\n items: baseDecisionRecordSchema(),\n },\n final_result: { type: [\"string\", \"null\"] },\n created_at: dateTimeSchema(),\n updated_at: dateTimeSchema(),\n ...extraProperties,\n },\n };\n}\n\nexport const activePointerSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"run_id\", \"updated_at\"],\n additionalProperties: false,\n properties: {\n skill: { type: \"string\", minLength: 1 },\n identifier: { type: \"string\", minLength: 1 },\n run_id: { type: \"string\", minLength: 1 },\n updated_at: dateTimeSchema(),\n },\n};\n\nexport const runtimeCheckpointEntrySchema = {\n type: \"object\",\n required: [\"sequence\", \"phase\", \"created_at\", \"payload\"],\n additionalProperties: false,\n properties: {\n sequence: { type: \"integer\", minimum: 1 },\n phase: { type: \"string\", minLength: 1 },\n created_at: dateTimeSchema(),\n payload: { type: \"object\" },\n },\n};\n\nexport const runtimeCheckpointHistorySchema = {\n type: \"object\",\n required: [\"_history\", \"_next_sequence\"],\n properties: {\n _history: {\n type: \"array\",\n items: runtimeCheckpointEntrySchema,\n },\n _next_sequence: { type: \"integer\", minimum: 1 },\n },\n};\n\nexport const runtimeHistoryEventSchema = {\n type: \"object\",\n required: [\"sequence\", \"event_type\", \"created_at\"],\n properties: {\n sequence: { type: \"integer\", minimum: 1 },\n event_type: {\n type: \"string\",\n enum: RUNTIME_HISTORY_EVENT_TYPE_LIST,\n },\n created_at: dateTimeSchema(),\n run_id: { type: \"string\" },\n },\n};\n\nexport const runtimeStatusResponseSchema = {\n type: \"object\",\n required: [\"ok\", \"active\", \"runtime\"],\n properties: {\n ok: { type: \"boolean\" },\n active: { type: \"boolean\" },\n runtime: {\n type: [\"object\", \"null\"],\n properties: {\n skill: { type: \"string\" },\n identifier: { type: \"string\" },\n run_id: { type: \"string\" },\n phase: { type: \"string\" },\n complete: { type: \"boolean\" },\n },\n },\n manifest: { type: \"object\" },\n state: { type: \"object\" },\n checkpoints: { type: \"object\" },\n paths: { type: \"object\" },\n resume_action: { type: [\"string\", \"null\"] },\n error: { type: \"string\" },\n validation_errors: { type: \"array\" },\n },\n};\n\nexport function buildSummaryEnvelopeSchema(payloadSchema) {\n return {\n type: \"object\",\n required: [\"schema_version\", \"summary_kind\", \"run_id\", \"identifier\", \"producer_skill\", \"produced_at\", \"payload\"],\n additionalProperties: false,\n properties: {\n schema_version: { type: \"string\", minLength: 1 },\n summary_kind: { type: \"string\", minLength: 1 },\n run_id: { type: \"string\", minLength: 1 },\n identifier: { type: \"string\", minLength: 1 },\n producer_skill: { type: \"string\", minLength: 1 },\n produced_at: dateTimeSchema(),\n payload: payloadSchema || { type: \"object\" },\n },\n };\n}\n\nexport const pendingDecisionSchema = {\n type: \"object\",\n required: [\"kind\", \"question\", \"choices\", \"default_choice\", \"resume_to_phase\", \"blocking\"],\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", minLength: 1 },\n question: { type: \"string\", minLength: 1 },\n choices: {\n ...stringArraySchema(),\n minItems: 1,\n },\n default_choice: { type: \"string\", minLength: 1 },\n context: { type: \"object\" },\n resume_to_phase: { type: \"string\", minLength: 1 },\n blocking: { type: \"boolean\" },\n },\n};\n\nexport const environmentWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n targets: stringArraySchema(),\n changes: stringArraySchema(),\n warnings: stringArraySchema(),\n detail: { type: \"string\" },\n },\n};\n\nexport const opportunityDiscoveryWorkerPayloadSchema = {\n type: \"object\",\n required: [\"input_mode\", \"ideas_analyzed\", \"survivors_count\", \"killed_count\", \"warnings\"],\n additionalProperties: false,\n properties: {\n input_mode: { type: \"string\", minLength: 1 },\n ideas_analyzed: { type: \"integer\" },\n generated_ideas: { type: \"integer\" },\n survivors_count: { type: \"integer\" },\n killed_count: { type: \"integer\" },\n top_recommendation: nullableStringSchema(),\n report_path: nullableStringSchema(),\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const storyPlanWorkerPayloadSchema = {\n type: \"object\",\n required: [\"mode\", \"epic_id\", \"stories_created\", \"stories_updated\", \"stories_canceled\", \"story_urls\", \"warnings\", \"kanban_updated\"],\n additionalProperties: false,\n properties: {\n mode: { type: \"string\" },\n epic_id: { type: \"string\" },\n stories_planned: { type: \"integer\" },\n stories_created: { type: \"integer\" },\n stories_updated: { type: \"integer\" },\n stories_canceled: { type: \"integer\" },\n story_urls: stringArraySchema(),\n warnings: stringArraySchema(),\n kanban_updated: { type: \"boolean\" },\n research_path_used: { type: \"string\" },\n },\n};\n\nexport const storyPlanCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"mode\", \"epic_id\", \"stories_created\", \"stories_updated\", \"stories_canceled\", \"story_urls\", \"warnings\", \"kanban_updated\"],\n additionalProperties: false,\n properties: {\n mode: { type: \"string\" },\n epic_id: { type: \"string\" },\n stories_planned: { type: \"integer\" },\n stories_created: { type: \"integer\" },\n stories_updated: { type: \"integer\" },\n stories_canceled: { type: \"integer\" },\n story_urls: stringArraySchema(),\n warnings: stringArraySchema(),\n kanban_updated: { type: \"boolean\" },\n research_path_used: { type: \"string\" },\n worker_runs_completed: { type: \"integer\" },\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const taskPlanWorkerPayloadSchema = {\n type: \"object\",\n required: [\"mode\", \"story_id\", \"task_type\", \"tasks_created\", \"tasks_updated\", \"tasks_canceled\", \"task_urls\", \"warnings\", \"kanban_updated\"],\n additionalProperties: false,\n properties: {\n mode: { type: \"string\" },\n story_id: { type: \"string\" },\n task_type: { type: \"string\" },\n tasks_created: { type: \"integer\" },\n tasks_updated: { type: \"integer\" },\n tasks_canceled: { type: \"integer\" },\n task_urls: stringArraySchema(),\n dry_warnings_count: { type: \"integer\" },\n warnings: stringArraySchema(),\n kanban_updated: { type: \"boolean\" },\n },\n};\n\nexport const qualityWorkerPayloadSchema = {\n type: \"object\",\n required: [\"worker\", \"status\", \"verdict\", \"issues\", \"warnings\"],\n additionalProperties: false,\n properties: {\n worker: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n verdict: { type: \"string\", minLength: 1 },\n score: { type: \"number\" },\n issues: stringArraySchema(),\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const taskStatusWorkerPayloadSchema = {\n type: \"object\",\n required: [\"worker\", \"status\", \"from_status\", \"to_status\", \"warnings\"],\n additionalProperties: false,\n properties: {\n worker: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n from_status: { type: \"string\", minLength: 1 },\n to_status: { type: \"string\", minLength: 1 },\n result: nullableStringSchema(),\n tests_run: stringArraySchema(),\n files_changed: stringArraySchema(),\n issues: stringArraySchema(),\n score: { type: [\"number\", \"null\"] },\n comment_path: nullableStringSchema(),\n error: nullableStringSchema(),\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const testPlanningWorkerPayloadSchema = {\n type: \"object\",\n required: [\"worker\", \"status\", \"warnings\"],\n additionalProperties: false,\n properties: {\n worker: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n warnings: stringArraySchema(),\n research_comment_path: nullableStringSchema(),\n manual_result_path: nullableStringSchema(),\n test_task_id: nullableStringSchema(),\n test_task_url: nullableStringSchema(),\n coverage_summary: nullableStringSchema(),\n planned_scenarios: stringArraySchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const storyPrioritizationWorkerPayloadSchema = {\n type: \"object\",\n required: [\"epic_id\", \"stories_analyzed\", \"priority_distribution\", \"prioritization_path\", \"warnings\"],\n additionalProperties: false,\n properties: {\n epic_id: { type: \"string\", minLength: 1 },\n depth: { type: \"string\" },\n stories_analyzed: { type: \"integer\" },\n priority_distribution: {\n type: \"object\",\n required: [\"p0\", \"p1\", \"p2\", \"p3\"],\n additionalProperties: false,\n properties: {\n p0: nonNegativeIntegerSchema(),\n p1: nonNegativeIntegerSchema(),\n p2: nonNegativeIntegerSchema(),\n p3: nonNegativeIntegerSchema(),\n },\n },\n top_story_ids: stringArraySchema(),\n prioritization_path: { type: \"string\", minLength: 1 },\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const docsGenerationWorkerPayloadSchema = {\n type: \"object\",\n required: [\"worker\", \"status\", \"created_files\", \"skipped_files\", \"quality_inputs\", \"validation_status\", \"warnings\"],\n additionalProperties: false,\n properties: {\n worker: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n created_files: stringArraySchema(),\n skipped_files: stringArraySchema(),\n quality_inputs: {\n type: \"object\",\n additionalProperties: true,\n },\n validation_status: { type: \"string\", minLength: 1 },\n warnings: stringArraySchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const epicPlanCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"mode\", \"scope_identifier\", \"epics_created\", \"epics_updated\", \"epics_canceled\", \"epic_urls\", \"warnings\", \"kanban_updated\"],\n additionalProperties: false,\n properties: {\n mode: { type: \"string\" },\n scope_identifier: { type: \"string\", minLength: 1 },\n epics_created: { type: \"integer\" },\n epics_updated: { type: \"integer\" },\n epics_canceled: { type: \"integer\" },\n epic_urls: stringArraySchema(),\n warnings: stringArraySchema(),\n kanban_updated: { type: \"boolean\" },\n infrastructure_epic_included: { type: \"boolean\" },\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const scopeDecompositionPayloadSchema = {\n type: \"object\",\n required: [\"scope_identifier\", \"epic_runs_completed\", \"story_runs_completed\", \"warnings\"],\n additionalProperties: false,\n properties: {\n scope_identifier: { type: \"string\", minLength: 1 },\n epic_runs_completed: { type: \"integer\" },\n story_runs_completed: { type: \"integer\" },\n prioritization_runs_completed: { type: \"integer\" },\n warnings: stringArraySchema(),\n final_result: { type: \"string\" },\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const pipelineStageCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"stage\", \"story_id\", \"status\", \"final_result\", \"story_status\", \"warnings\"],\n additionalProperties: false,\n properties: {\n stage: { type: \"integer\", minimum: 0, maximum: 3 },\n story_id: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n story_status: { type: \"string\", minLength: 1 },\n verdict: nullableStringSchema(),\n readiness_score: { type: [\"number\", \"null\"] },\n quality_score: { type: [\"number\", \"null\"] },\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const auditSeverityCountsSchema = {\n type: \"object\",\n required: [\"critical\", \"high\", \"medium\", \"low\"],\n additionalProperties: false,\n properties: {\n critical: nonNegativeIntegerSchema(),\n high: nonNegativeIntegerSchema(),\n medium: nonNegativeIntegerSchema(),\n low: nonNegativeIntegerSchema(),\n },\n};\n\nexport const auditWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"category\", \"report_path\", \"score\", \"issues_total\", \"severity_counts\", \"warnings\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n category: { type: \"string\", minLength: 1 },\n report_path: { type: \"string\", minLength: 1 },\n score: { type: \"number\" },\n issues_total: nonNegativeIntegerSchema(),\n severity_counts: auditSeverityCountsSchema,\n warnings: stringArraySchema(),\n diagnostic_scores: {\n type: \"object\",\n additionalProperties: { type: \"number\" },\n },\n domain_name: nullableStringSchema(),\n scan_scope: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const auditCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"final_result\", \"report_path\", \"worker_count\", \"issues_total\", \"severity_counts\", \"warnings\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n report_path: { type: \"string\", minLength: 1 },\n results_log_path: nullableStringSchema(),\n overall_score: { type: [\"number\", \"null\"] },\n worker_count: nonNegativeIntegerSchema(),\n issues_total: nonNegativeIntegerSchema(),\n severity_counts: auditSeverityCountsSchema,\n warnings: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const evaluationWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"worker\", \"operation\", \"warnings\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n worker: { type: \"string\", minLength: 1 },\n operation: { type: \"string\", minLength: 1 },\n verdict: nullableStringSchema(),\n findings: {\n type: \"array\",\n items: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n metrics: {\n type: \"object\",\n additionalProperties: true,\n },\n decisions: {\n type: \"array\",\n items: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n report_path: nullableStringSchema(),\n artifact_path: nullableStringSchema(),\n warnings: stringArraySchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const evaluationCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"final_result\", \"report_path\", \"worker_count\", \"issues_total\", \"severity_counts\", \"warnings\", \"cleanup_verified\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n report_path: { type: \"string\", minLength: 1 },\n results_log_path: nullableStringSchema(),\n overall_score: { type: [\"number\", \"null\"] },\n worker_count: nonNegativeIntegerSchema(),\n agent_count: nonNegativeIntegerSchema(),\n issues_total: nonNegativeIntegerSchema(),\n severity_counts: auditSeverityCountsSchema,\n warnings: stringArraySchema(),\n cleanup_verified: { type: \"boolean\" },\n research_completed: { type: \"boolean\" },\n artifact_path: nullableStringSchema(),\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const optimizationWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"worker\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n worker: { type: \"string\", minLength: 1 },\n cycle: { type: \"integer\", minimum: 1 },\n phase_context: nullableStringSchema(),\n artifact_path: nullableStringSchema(),\n branch: { type: \"string\" },\n baseline: { type: \"object\" },\n performance_map: { type: \"object\" },\n wrong_tool_indicators: stringArraySchema(),\n e2e_test: { type: \"object\" },\n instrumented_files: stringArraySchema(),\n industry_benchmark: { type: \"object\" },\n target_metrics: { type: \"object\" },\n hypotheses: stringArraySchema(),\n local_codebase_findings: stringArraySchema(),\n verdict: { type: \"string\" },\n corrections_applied: stringArraySchema(),\n concerns: stringArraySchema(),\n final: { type: \"object\" },\n total_improvement_pct: { type: \"number\" },\n target_met: { type: \"boolean\" },\n strike_result: { type: \"string\" },\n hypotheses_applied: stringArraySchema(),\n hypotheses_removed: stringArraySchema(),\n recorded_at: dateTimeSchema(),\n },\n};\n\nexport const optimizationCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"final_result\", \"cycle_count\", \"report_ready\", \"execution_mode\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n cycle_count: nonNegativeIntegerSchema(),\n stop_reason: nullableStringSchema(),\n report_ready: { type: \"boolean\" },\n execution_mode: { type: \"string\", minLength: 1 },\n target_metric: { type: [\"object\", \"null\"] },\n total_improvement_pct: { type: [\"number\", \"null\"] },\n target_met: { type: [\"boolean\", \"null\"] },\n summary_artifact_path: nullableStringSchema(),\n report_path: nullableStringSchema(),\n },\n};\n\nexport const dependencyWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"worker\", \"package_manager\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n worker: { type: \"string\", minLength: 1 },\n package_manager: { type: \"string\", minLength: 1 },\n branch: nullableStringSchema(),\n upgrades: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"package\", \"from\", \"to\"],\n additionalProperties: false,\n properties: {\n package: { type: \"string\", minLength: 1 },\n from: { type: \"string\", minLength: 1 },\n to: { type: \"string\", minLength: 1 },\n breaking: { type: \"boolean\" },\n },\n },\n },\n warnings: stringArraySchema(),\n errors: stringArraySchema(),\n tests_passed: { type: \"boolean\" },\n build_passed: { type: \"boolean\" },\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const dependencyCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"final_result\", \"worker_count\", \"upgraded_packages\", \"verification_passed\", \"report_ready\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n worker_count: nonNegativeIntegerSchema(),\n upgraded_packages: nonNegativeIntegerSchema(),\n failed_workers: nonNegativeIntegerSchema(),\n verification_passed: { type: \"boolean\" },\n report_ready: { type: \"boolean\" },\n report_path: nullableStringSchema(),\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const modernizationWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"worker\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n worker: { type: \"string\", minLength: 1 },\n branch: nullableStringSchema(),\n changes_applied: nonNegativeIntegerSchema(),\n changes_discarded: nonNegativeIntegerSchema(),\n tests_passed: { type: \"boolean\" },\n build_passed: { type: \"boolean\" },\n modules_replaced: nonNegativeIntegerSchema(),\n loc_removed: nonNegativeIntegerSchema(),\n bundle_reduction_bytes: nonNegativeIntegerSchema(),\n warnings: stringArraySchema(),\n errors: stringArraySchema(),\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const modernizationCoordinatorPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"final_result\", \"worker_count\", \"verification_passed\", \"report_ready\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n final_result: { type: \"string\", minLength: 1 },\n worker_count: nonNegativeIntegerSchema(),\n verification_passed: { type: \"boolean\" },\n report_ready: { type: \"boolean\" },\n modules_replaced: nonNegativeIntegerSchema(),\n loc_removed: nonNegativeIntegerSchema(),\n bundle_reduction_bytes: nonNegativeIntegerSchema(),\n report_path: nullableStringSchema(),\n artifact_path: nullableStringSchema(),\n },\n};\n\nexport const benchmarkWorkerPayloadSchema = {\n type: \"object\",\n required: [\"status\", \"worker\", \"scenarios_total\", \"scenarios_passed\", \"scenarios_failed\", \"activation_valid\", \"validity_verdict\", \"warnings\"],\n additionalProperties: false,\n properties: {\n status: { type: \"string\", enum: WORKER_SUMMARY_STATUS_LIST },\n worker: { type: \"string\", minLength: 1 },\n scenarios_total: nonNegativeIntegerSchema(),\n scenarios_passed: nonNegativeIntegerSchema(),\n scenarios_failed: nonNegativeIntegerSchema(),\n activation_valid: { type: \"boolean\" },\n validity_verdict: { type: \"string\", minLength: 1 },\n report_path: nullableStringSchema(),\n artifact_path: nullableStringSchema(),\n scenario_ids: stringArraySchema(),\n warnings: stringArraySchema(),\n metrics: {\n type: \"object\",\n additionalProperties: true,\n },\n metadata: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n};\n\nexport const environmentWorkerSummarySchema = buildSummaryEnvelopeSchema(environmentWorkerPayloadSchema);\nexport const opportunityDiscoveryWorkerSummarySchema = buildSummaryEnvelopeSchema(opportunityDiscoveryWorkerPayloadSchema);\nexport const storyPlanWorkerSummarySchema = buildSummaryEnvelopeSchema(storyPlanWorkerPayloadSchema);\nexport const storyPlanCoordinatorSummarySchema = buildSummaryEnvelopeSchema(storyPlanCoordinatorPayloadSchema);\nexport const taskPlanWorkerSummarySchema = buildSummaryEnvelopeSchema(taskPlanWorkerPayloadSchema);\nexport const qualityWorkerSummarySchema = buildSummaryEnvelopeSchema(qualityWorkerPayloadSchema);\nexport const taskStatusWorkerSummarySchema = buildSummaryEnvelopeSchema(taskStatusWorkerPayloadSchema);\nexport const testPlanningWorkerSummarySchema = buildSummaryEnvelopeSchema(testPlanningWorkerPayloadSchema);\nexport const storyPrioritizationWorkerSummarySchema = buildSummaryEnvelopeSchema(storyPrioritizationWorkerPayloadSchema);\nexport const docsGenerationWorkerSummarySchema = buildSummaryEnvelopeSchema(docsGenerationWorkerPayloadSchema);\nexport const epicPlanCoordinatorSummarySchema = buildSummaryEnvelopeSchema(epicPlanCoordinatorPayloadSchema);\nexport const scopeDecompositionSummarySchema = buildSummaryEnvelopeSchema(scopeDecompositionPayloadSchema);\nexport const auditWorkerSummarySchema = buildSummaryEnvelopeSchema(auditWorkerPayloadSchema);\nexport const auditCoordinatorSummarySchema = buildSummaryEnvelopeSchema(auditCoordinatorPayloadSchema);\nexport const evaluationWorkerSummarySchema = buildSummaryEnvelopeSchema(evaluationWorkerPayloadSchema);\nexport const evaluationCoordinatorSummarySchema = buildSummaryEnvelopeSchema(evaluationCoordinatorPayloadSchema);\nexport const pipelineStageCoordinatorSummarySchema = buildSummaryEnvelopeSchema(pipelineStageCoordinatorPayloadSchema);\nexport const optimizationWorkerSummarySchema = buildSummaryEnvelopeSchema(optimizationWorkerPayloadSchema);\nexport const optimizationCoordinatorSummarySchema = buildSummaryEnvelopeSchema(optimizationCoordinatorPayloadSchema);\nexport const dependencyWorkerSummarySchema = buildSummaryEnvelopeSchema(dependencyWorkerPayloadSchema);\nexport const dependencyCoordinatorSummarySchema = buildSummaryEnvelopeSchema(dependencyCoordinatorPayloadSchema);\nexport const modernizationWorkerSummarySchema = buildSummaryEnvelopeSchema(modernizationWorkerPayloadSchema);\nexport const modernizationCoordinatorSummarySchema = buildSummaryEnvelopeSchema(modernizationCoordinatorPayloadSchema);\nexport const benchmarkWorkerSummarySchema = buildSummaryEnvelopeSchema(benchmarkWorkerPayloadSchema);\n\nexport const environmentStateSchema = {\n type: \"object\",\n required: [\"scanned_at\", \"agents\"],\n properties: {\n scanned_at: { type: \"string\", format: \"date-time\" },\n agents: {\n type: \"object\",\n required: [\"claude\", \"codex\"],\n properties: {\n claude: {\n type: \"object\",\n required: [\"available\"],\n properties: {\n available: { type: \"boolean\" },\n disabled: { type: \"boolean\" },\n version: { type: \"string\" },\n detail: { type: \"string\" },\n },\n },\n codex: {\n type: \"object\",\n required: [\"available\"],\n properties: {\n available: { type: \"boolean\" },\n disabled: { type: \"boolean\" },\n version: { type: \"string\" },\n config_aligned: { type: \"boolean\" },\n servers_aligned: { type: \"integer\" },\n marketplace_plugins: stringArraySchema(),\n alignment_actions: stringArraySchema(),\n detail: { type: \"string\" },\n },\n }\n },\n },\n task_management: {\n type: \"object\",\n properties: {\n provider: { type: \"string\", enum: [\"linear\", \"file\", \"github\"] },\n status: { type: \"string\" },\n fallback: { type: \"string\", enum: [\"file\"] },\n linear: {\n type: \"object\",\n properties: {\n team_id: { type: \"string\" },\n },\n },\n github: {\n type: \"object\",\n properties: {\n repository: { type: \"string\" },\n project_number: { type: \"integer\" },\n },\n },\n },\n },\n research: {\n type: \"object\",\n properties: {\n provider: { type: \"string\" },\n fallback_chain: stringArraySchema(),\n status: { type: \"string\" },\n },\n },\n claude_md: {\n type: \"object\",\n properties: {\n exists: { type: \"boolean\" },\n has_compact_instructions: { type: \"boolean\" },\n has_mcp_preferences: { type: \"boolean\" },\n has_date_stamp: { type: \"boolean\" },\n line_count: { type: \"integer\" },\n has_timestamps: { type: \"boolean\" },\n },\n },\n assessment: {\n type: \"object\",\n properties: {\n assessed_at: { type: \"string\", format: \"date-time\" },\n all_green: { type: \"boolean\" },\n score: { type: \"string\" },\n warnings: stringArraySchema(),\n info: stringArraySchema(),\n workers_run: stringArraySchema(),\n workers_skipped: stringArraySchema(),\n },\n },\n hooks: {\n type: \"object\",\n properties: {\n mode: {\n type: \"string\",\n enum: [\"blocking\", \"advisory\"],\n },\n },\n },\n ide_extension: {\n type: \"object\",\n properties: {\n cursor: ideExtensionEntrySchema(),\n vscode: ideExtensionEntrySchema(),\n },\n },\n },\n};\n\nfunction ideExtensionEntrySchema() {\n return {\n type: \"object\",\n properties: {\n installed: { type: \"boolean\" },\n extension_version: { type: \"string\" },\n settings_path: { type: \"string\" },\n initial_permission_mode: {\n type: \"string\",\n enum: [\"default\", \"acceptEdits\", \"plan\", \"bypassPermissions\"],\n },\n allow_dangerously_skip_permissions: { type: \"boolean\" },\n effective_state: {\n type: \"string\",\n enum: [\n \"default-prompt\",\n \"accept-edits\",\n \"plan-only\",\n \"bypass-active\",\n \"bypass-blocked\",\n \"no-ide\",\n ],\n },\n conflict_with_project_default_mode: {\n type: \"string\",\n enum: [\"aligned\", \"override\", \"n/a\"],\n },\n last_modified_by_skill: { type: \"string\" },\n },\n };\n}\n\nexport const reviewAgentRecordSchema = {\n type: \"object\",\n required: [\"name\"],\n additionalProperties: false,\n properties: {\n name: { type: \"string\", minLength: 1 },\n status: { type: \"string\", enum: REVIEW_AGENT_STATUS_LIST },\n prompt_file: nullableStringSchema(),\n result_file: nullableStringSchema(),\n log_file: nullableStringSchema(),\n metadata_file: nullableStringSchema(),\n pid: { type: [\"integer\", \"null\"] },\n session_id: nullableStringSchema(),\n started_at: { type: [\"string\", \"null\"], format: \"date-time\" },\n finished_at: { type: [\"string\", \"null\"], format: \"date-time\" },\n exit_code: { type: [\"integer\", \"null\"] },\n error: nullableStringSchema(),\n },\n};\n\nexport const storyGroupRecordSchema = {\n type: \"object\",\n required: [\"group_id\"],\n additionalProperties: false,\n properties: {\n group_id: { type: \"string\", minLength: 1 },\n task_ids: stringArraySchema(),\n status: { type: \"string\", enum: STORY_EXECUTION_GROUP_STATUS_LIST },\n result: { type: \"string\" },\n completed_at: dateTimeSchema(),\n inflight_workers: { type: \"object\" },\n },\n};\n\nexport const qualitySummarySchema = {\n type: \"object\",\n required: [\"story_id\", \"verdict\"],\n additionalProperties: false,\n properties: {\n story_id: { type: \"string\", minLength: 1 },\n verdict: { type: \"string\", enum: STORY_GATE_VERDICT_LIST },\n quality_score: { type: \"number\" },\n issues: stringArraySchema(),\n fast_track: { type: \"boolean\" },\n agent_review_summary: { type: \"object\" },\n regression_status: { type: \"string\" },\n },\n};\n\nexport const testSummarySchema = {\n type: \"object\",\n required: [\"story_id\", \"status\"],\n additionalProperties: false,\n properties: {\n story_id: { type: \"string\", minLength: 1 },\n mode: { type: \"string\" },\n test_task_id: { type: \"string\" },\n status: { type: \"string\", minLength: 1 },\n planned_scenarios: stringArraySchema(),\n coverage_summary: { type: \"string\" },\n planner_invoked: { type: \"boolean\" },\n error: { type: \"string\" },\n },\n};\n\nexport const optimizationWorkerResultSchema = optimizationWorkerPayloadSchema;\n\nexport const optimizationCycleSchema = {\n type: \"object\",\n required: [\"cycle\"],\n additionalProperties: false,\n properties: {\n cycle: { type: \"integer\", minimum: 1 },\n status: { type: \"string\", enum: OPTIMIZATION_CYCLE_STATUS_LIST },\n next_cycle: { type: \"integer\" },\n stop_reason: { type: \"string\" },\n final_result: { type: \"string\" },\n recorded_at: dateTimeSchema(),\n },\n};\n\n// ── Blueprint verification (ln-401 task executor) ──────────────────────────\n\nexport const blueprintCheckpointPayloadSchema = {\n type: \"object\",\n required: [\"blueprint\"],\n properties: {\n blueprint: {\n type: \"object\",\n required: [\"change_order\"],\n properties: {\n change_order: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"file\", \"action\"],\n properties: {\n file: { type: \"string\", minLength: 1 },\n action: { type: \"string\", enum: [\"create\", \"modify\"] },\n reason: { type: \"string\" },\n },\n },\n minItems: 1,\n },\n },\n },\n },\n};\n\nexport const blueprintStatusSchema = {\n type: \"object\",\n required: [\"planned_count\", \"completed\", \"skipped\", \"added\", \"completion_pct\"],\n properties: {\n planned_count: { type: \"integer\", minimum: 0 },\n completed: stringArraySchema(),\n skipped: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"file\", \"justification\"],\n properties: {\n file: { type: \"string\", minLength: 1 },\n justification: { type: \"string\", minLength: 1 },\n },\n },\n },\n added: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"file\", \"justification\"],\n properties: {\n file: { type: \"string\", minLength: 1 },\n justification: { type: \"string\", minLength: 1 },\n },\n },\n },\n completion_pct: { type: \"number\", minimum: 0, maximum: 100 },\n },\n};\n","content_type":"text/javascript","language":"javascript","size":38117,"content_sha256":"b41e4ceccb193d909d60a344e306fd08b587a9584c96c32dfd09b036c429bbc1"},{"filename":"references/scripts/coordinator-runtime/lib/validate.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/lib/validate.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nfunction isPlainObject(value) {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction matchesType(expectedType, value) {\n if (Array.isArray(expectedType)) {\n return expectedType.some(type => matchesType(type, value));\n }\n switch (expectedType) {\n case \"object\":\n return isPlainObject(value);\n case \"array\":\n return Array.isArray(value);\n case \"string\":\n return typeof value === \"string\";\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n default:\n return true;\n }\n}\n\nfunction validateNode(schema, value, path, errors) {\n if (!schema || typeof schema !== \"object\") {\n return;\n }\n\n if (schema.type && !matchesType(schema.type, value)) {\n errors.push({\n instancePath: path,\n message: `must be ${schema.type}`,\n });\n return;\n }\n\n if (schema.enum && !schema.enum.includes(value)) {\n errors.push({\n instancePath: path,\n message: `must be one of: ${schema.enum.join(\", \")}`,\n });\n }\n\n if (schema.type === \"string\" && schema.format === \"date-time\" && typeof value === \"string\") {\n if (Number.isNaN(Date.parse(value))) {\n errors.push({\n instancePath: path,\n message: \"must be a valid date-time string\",\n });\n }\n }\n\n if (schema.type === \"string\" && typeof value === \"string\" && typeof schema.minLength === \"number\") {\n if (value.length \u003c schema.minLength) {\n errors.push({\n instancePath: path,\n message: `must have length >= ${schema.minLength}`,\n });\n }\n }\n\n if (schema.type === \"array\" && Array.isArray(value) && typeof schema.minItems === \"number\") {\n if (value.length \u003c schema.minItems) {\n errors.push({\n instancePath: path,\n message: `must contain at least ${schema.minItems} item(s)`,\n });\n }\n }\n\n if ((schema.type === \"integer\" || schema.type === \"number\") && typeof value === \"number\" && typeof schema.minimum === \"number\") {\n if (value \u003c schema.minimum) {\n errors.push({\n instancePath: path,\n message: `must be >= ${schema.minimum}`,\n });\n }\n }\n\n if (schema.type === \"object\" && isPlainObject(value)) {\n const properties = schema.properties || {};\n const required = Array.isArray(schema.required) ? schema.required : [];\n\n for (const key of required) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n errors.push({\n instancePath: path,\n message: `missing required property: ${key}`,\n });\n }\n }\n\n if (schema.additionalProperties === false) {\n for (const key of Object.keys(value)) {\n if (!Object.prototype.hasOwnProperty.call(properties, key)) {\n errors.push({\n instancePath: path ? `${path}/${key}` : `/${key}`,\n message: \"additional property is not allowed\",\n });\n }\n }\n }\n\n for (const [key, propertySchema] of Object.entries(properties)) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n continue;\n }\n const nextPath = path ? `${path}/${key}` : `/${key}`;\n validateNode(propertySchema, value[key], nextPath, errors);\n }\n }\n\n if (schema.type === \"array\" && Array.isArray(value) && schema.items) {\n for (let index = 0; index \u003c value.length; index += 1) {\n validateNode(schema.items, value[index], `${path}/${index}`, errors);\n }\n }\n}\n\nexport function validateSchema(schema, data) {\n const errors = [];\n validateNode(schema, data, \"\", errors);\n return {\n ok: errors.length === 0,\n errors,\n };\n}\n\nexport function formatValidationErrors(errors) {\n return (errors || [])\n .map(error => `${error.instancePath || \"/\"} ${error.message}`.trim())\n .join(\"; \");\n}\n\nexport function assertSchema(schema, data, label = \"payload\") {\n const result = validateSchema(schema, data);\n if (result.ok) {\n return { ok: true };\n }\n return {\n ok: false,\n error: `Invalid ${label}: ${formatValidationErrors(result.errors)}`,\n details: result.errors,\n };\n}\n","content_type":"text/javascript","language":"javascript","size":4943,"content_sha256":"8aea4a181f03a1d22002563f844a973e5a71c45deb7fe6e668d37c5ea27b3196"},{"filename":"references/scripts/coordinator-runtime/test/cli-test-helpers.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/test/cli-test-helpers.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { execFileSync } from \"node:child_process\";\nimport { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function createProjectRoot(prefix) {\n return mkdtempSync(join(tmpdir(), prefix));\n}\n\nexport function writeJson(path, value) {\n writeFileSync(path, JSON.stringify(value, null, 2));\n}\n\nexport function readJson(path) {\n return JSON.parse(readFileSync(path, \"utf8\"));\n}\n\nexport function createJsonCliRunner(cliPath, projectRoot) {\n const compileCacheDir = join(projectRoot, \".node-compile-cache\");\n mkdirSync(compileCacheDir, { recursive: true });\n const env = {\n ...process.env,\n NODE_COMPILE_CACHE: process.env.NODE_COMPILE_CACHE || compileCacheDir,\n };\n\n return function run(args, { allowFailure = false } = {}) {\n try {\n return JSON.parse(execFileSync(process.execPath, [cliPath, ...args], {\n cwd: projectRoot,\n encoding: \"utf8\",\n env,\n }));\n } catch (error) {\n if (!allowFailure) {\n throw error;\n }\n const stdout = error.stdout?.toString().trim();\n const stderr = error.stderr?.toString().trim();\n const body = stdout || stderr || \"{}\";\n return JSON.parse(body);\n }\n };\n}\n","content_type":"text/javascript","language":"javascript","size":1533,"content_sha256":"92043c0a046a64548210abc7c50b347a8e27a2eda715c1d7aed7dc2e0fed41d8"},{"filename":"references/scripts/coordinator-runtime/test/consistency-scan.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/test/consistency-scan.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, extname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst skillsRepoRoot = resolve(__dirname, \"../../../..\");\nconst parentRepoRoot = resolve(skillsRepoRoot, \"..\");\n\nconst selfPath = normalizePath(fileURLToPath(import.meta.url));\nconst CONSISTENCY_SCAN_SUFFIX = \"/coordinator-runtime/test/consistency-scan.mjs\";\nconst isConsistencyScanFile = filePath => normalizePath(filePath).endsWith(CONSISTENCY_SCAN_SUFFIX);\n\nconst allowedLegacyPhaseDocs = new Set([\n selfPath,\n normalizePath(join(skillsRepoRoot, \"references/runtime_status_catalog.md\")),\n]);\n\nconst workerRuntimeWiringDocs = new Map([\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-200-scope-decomposer/SKILL.md\")),\n [\n \"node references/scripts/epic-planning-runtime/cli.mjs start\",\n \"node references/scripts/story-planning-runtime/cli.mjs start\",\n \"node references/scripts/planning-worker-runtime/cli.mjs start\",\n \"story-prioritization-worker/ln-230--{identifier}.json\",\n \"child_run\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-220-story-coordinator/SKILL.md\")),\n [\n \"node references/scripts/planning-worker-runtime/cli.mjs start\",\n \"story-plan-worker/{worker}--{identifier}.json\",\n \"child_run\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-300-task-coordinator/SKILL.md\")),\n [\n \"node references/scripts/task-plan-worker-runtime/cli.mjs start\",\n \"--run-id {childRunId}\",\n \"--summary-artifact-path {childSummaryArtifactPath}\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-400-story-executor/SKILL.md\")),\n [\n \"node references/scripts/task-worker-runtime/cli.mjs start\",\n \"task-status/{taskId}--{worker}.json\",\n \"task-status/{taskId}--ln-402.json\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-520-test-planner/SKILL.md\")),\n [\n \"node references/scripts/test-planning-worker-runtime/cli.mjs start\",\n \"test-planning-worker/{worker}--{storyId}.json\",\n \"child_run\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-523-auto-test-planner/SKILL.md\")),\n [\n \"task-plan-worker-runtime\",\n \"childSummaryArtifactPath = .hex-skills/runtime-artifacts/runs/{parent_run_id}/task-plan/ln-301--{storyId}.json\",\n \"child `task-plan` artifact\",\n ],\n ],\n [\n normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-500-story-quality-gate/SKILL.md\")),\n [\n \"node references/scripts/quality-runtime/cli.mjs start\",\n \"story-quality/{storyId}.json\",\n \"node references/scripts/test-planning-runtime/cli.mjs start\",\n \"story-tests/{storyId}.json\",\n \"child_run\",\n ],\n ],\n]);\n\nconst checks = [\n {\n name: \"legacy review phase alias in code or active skill docs\",\n test(filePath, content) {\n if (!/\\bPHASE_6_REFINE\\b/.test(content) && !/\\bPHASE_6_REFINEMENT\\b/.test(content)) {\n return null;\n }\n const np = normalizePath(filePath);\n if (allowedLegacyPhaseDocs.has(np) || np.endsWith(\"/references/runtime_status_catalog.md\") || isConsistencyScanFile(filePath)) {\n return null;\n }\n return \"Use PHASE_7_REFINEMENT only; PHASE_6_REFINE and PHASE_6_REFINEMENT must not appear outside explicit invalid-usage docs.\";\n },\n include: filePath => isDocumentationLike(filePath) || isJavaScript(filePath),\n },\n {\n name: \"stale agent review output status field\",\n regex: /status:\\s*\"success \\| failed \\| timeout\"/,\n message: \"Use runtime_status + execution_outcome; do not overload status with transport outcomes.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"ambiguous audit failure wording\",\n regex: /or equivalent per workflow/,\n message: \"Use explicit canonical statuses instead of ambiguous equivalents.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"plan mode stale pending progression\",\n regex: /pending → completed/,\n message: \"TodoWrite guidance must use explicit tool-local status progression, not stale pending→completed wording.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"task board shorthand statuses in docs\",\n regex: /Done\\/To Rework|In Progress\\/To Review\\/Done|In Progress\\/Review\\/Done|Backlog\\/Todo\\/In Progress\\/To Review\\/Done/,\n message: \"Use canonical task-board status names with explicit separators, e.g. `Done | To Rework` or `In Progress | To Review | Done`.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"legacy dated output directory wording\",\n regex: /Delete the dated output directory/,\n message: \"Use run-scoped runtime artifact wording instead of dated output directory language.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"mojibake artifacts in docs or script text\",\n regex: /[\\u00c3\\u00a2\\u00c3\\u0192\\u00c3\\u201a\\ufffd]/,\n message: \"Remove mojibake artifacts and normalize text to ASCII-safe wording.\",\n include: filePath => (isDocumentationLike(filePath) || isJavaScript(filePath)) && !isConsistencyScanFile(filePath),\n },\n {\n name: \"uncentralized story gate shortcut status in code\",\n regex: /\"skipped_by_verdict\"/,\n message: \"Use STORY_GATE_FINALIZATION_STATUSES.SKIPPED_BY_VERDICT instead of string literals.\",\n include: filePath => isJavaScript(filePath) && !filePath.endsWith(\"runtime-constants.mjs\") && !isConsistencyScanFile(filePath),\n },\n {\n name: \"pipeline phase field drift in docs\",\n regex: /state\\.stage/,\n message: \"Use canonical runtime field `state.phase`, not `state.stage`.\",\n include: filePath => isDocumentationLike(filePath),\n },\n {\n name: \"missing worker-runtime wiring in ln-1000 coordinator skills\",\n test(filePath, content) {\n const requiredSnippets = workerRuntimeWiringDocs.get(normalizePath(filePath));\n if (!requiredSnippets) {\n return null;\n }\n const missing = requiredSnippets.filter(snippet => !content.includes(snippet));\n if (missing.length === 0) {\n return null;\n }\n return `Add explicit managed worker-runtime wiring snippets: ${missing.join(\", \")}`;\n },\n include: filePath => workerRuntimeWiringDocs.has(normalizePath(filePath)),\n },\n {\n name: \"plain Stage 3 child coordinator invocation in ln-500\",\n test(filePath, content) {\n if (normalizePath(filePath) !== normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-500-story-quality-gate/SKILL.md\"))) {\n return null;\n }\n if (content.includes('Skill(skill: \"ln-510-quality-coordinator\", args: \"{storyId}\")')\n || content.includes('Skill(skill: \"ln-520-test-planner\", args: \"{storyId}\")')) {\n return \"Replace plain ln-510/ln-520 invocation examples with managed child-run flow.\";\n }\n return null;\n },\n include: filePath => normalizePath(filePath) === normalizePath(join(skillsRepoRoot, \"plugins/agile-workflow/skills/ln-500-story-quality-gate/SKILL.md\")),\n },\n {\n name: \"reverse-coupled audit worker contract wording\",\n regex: /\\*\\*Worker in ln-\\d+ coordinator pipeline\\*\\*|invoked by ln-\\d+/,\n message: \"Audit workers must stay standalone-capable and must not describe parent coordinator ownership in the public contract.\",\n include: filePath => /\\/ln-6\\d{2}[^/]*\\/SKILL\\.md$/.test(normalizePath(filePath))\n && !/\\/ln-(610|620|630|640|650)-/.test(normalizePath(filePath)),\n },\n {\n name: \"legacy audit summary fallback wording\",\n regex: /Legacy compact text output is allowed only when `summaryArtifactPath` is absent|If `?summaryArtifactPath`? is present, write JSON summary per /,\n message: \"Use managed-vs-standalone runtime wording from the shared audit worker contracts instead of legacy fallback prose.\",\n include: filePath => /\\/ln-6\\d{2}[^/]*\\/SKILL\\.md$/.test(normalizePath(filePath))\n && !/\\/ln-(610|620|630|640|650)-/.test(normalizePath(filePath)),\n },\n];\n\nconst rootsToScan = [\n skillsRepoRoot,\n join(parentRepoRoot, \"docs\"),\n join(parentRepoRoot, \"site\"),\n join(parentRepoRoot, \"AGENTS.md\"),\n join(parentRepoRoot, \"README.md\"),\n];\n\nconst findings = [];\n\nfor (const root of rootsToScan) {\n for (const filePath of walk(root)) {\n if (!isDocumentationLike(filePath) && !isJavaScript(filePath)) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const normalizedPath = normalizePath(filePath);\n for (const check of checks) {\n if (!check.include(filePath)) {\n continue;\n }\n if (check.test) {\n const failure = check.test(filePath, content);\n if (failure) {\n findings.push(`${normalizedPath}: ${failure}`);\n }\n continue;\n }\n if (check.regex?.test(content)) {\n findings.push(`${normalizedPath}: ${check.message}`);\n }\n }\n }\n}\n\nif (findings.length > 0) {\n process.stderr.write(`Consistency scan failed (${findings.length} issue(s))\\n`);\n for (const finding of findings) {\n process.stderr.write(`- ${finding}\\n`);\n }\n process.exit(1);\n}\n\nprocess.stdout.write(\"consistency scan passed\\n\");\n\nfunction walk(targetPath) {\n try {\n const stats = statSync(targetPath);\n if (stats.isFile()) {\n return [targetPath];\n }\n if (!stats.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const entries = readdirSync(targetPath, { withFileTypes: true });\n const files = [];\n for (const entry of entries) {\n const nextPath = join(targetPath, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\" || entry.name === \".git\") {\n continue;\n }\n if (/\\/plugins\\/[^/]+\\/shared(?:\\/|$)/.test(normalizePath(nextPath))) {\n continue;\n }\n files.push(...walk(nextPath));\n continue;\n }\n if (entry.isFile()) {\n files.push(nextPath);\n }\n }\n return files;\n}\n\nfunction isMarkdown(filePath) {\n const ext = extname(filePath).toLowerCase();\n return ext === \".md\" || ext === \".mdx\";\n}\n\nfunction isHtml(filePath) {\n return extname(filePath).toLowerCase() === \".html\";\n}\n\nfunction isDocumentationLike(filePath) {\n return isMarkdown(filePath) || isHtml(filePath);\n}\n\nfunction isJavaScript(filePath) {\n const ext = extname(filePath).toLowerCase();\n return ext === \".mjs\" || ext === \".js\";\n}\n\nfunction normalizePath(filePath) {\n return filePath.replace(/\\\\/g, \"/\");\n}\n","content_type":"text/javascript","language":"javascript","size":11847,"content_sha256":"cd64a5ff6a1c750c470c34edb04a587c1c8b84ca2c89c8336673ffc6a7f874a6"},{"filename":"references/scripts/coordinator-runtime/test/loop-health.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/test/loop-health.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n classifyLoopSignal,\n LOOP_HEALTH_FAILURE_CLASSES,\n normalizeErrorSignature,\n updateLoopHealth,\n} from \"../lib/loop-health.mjs\";\n\nfunction assert(condition, message) {\n if (!condition) {\n throw new Error(message);\n }\n}\n\nfunction testNormalizeErrorSignature() {\n const a = normalizeErrorSignature(\"Error at D:\\\\repo\\\\file.ts:123 on 2026-04-25T10:20:30Z\");\n const b = normalizeErrorSignature(\"Error at D:\\\\other\\\\file.ts:999 on 2026-04-25T11:22:33Z\");\n assert(a === b, \"volatile paths, numbers, and timestamps should normalize\");\n}\n\nfunction testProgressResetsCounters() {\n const first = updateLoopHealth({}, { error: \"ASSERT failed\", progress_detected: false });\n const second = updateLoopHealth(first, { error: \"ASSERT failed\", progress_detected: true });\n assert(second.no_progress_count === 0, \"progress should reset no-progress counter\");\n assert(second.same_error_count === 0, \"progress should reset same-error counter\");\n assert(second.pause_recommended === false, \"progress should not pause\");\n}\n\nfunction testNoProgressThreshold() {\n let health = {};\n const errors = [\"alpha failure\", \"beta failure\", \"gamma failure\"];\n for (let i = 0; i \u003c 3; i += 1) {\n health = updateLoopHealth(health, {\n failure_class: LOOP_HEALTH_FAILURE_CLASSES.UNKNOWN,\n error: errors[i],\n progress_detected: false,\n });\n }\n assert(health.pause_recommended === true, \"third no-progress attempt should pause\");\n assert(health.pause_category === \"no_progress\", \"pause should be no_progress\");\n}\n\nfunction testSameErrorThreshold() {\n let health = {};\n for (let i = 0; i \u003c 3; i += 1) {\n health = updateLoopHealth(health, {\n failure_class: LOOP_HEALTH_FAILURE_CLASSES.AGENT_ERROR,\n error: \"ASSERT failed: same segment\",\n progress_detected: false,\n });\n }\n assert(health.pause_recommended === true, \"third same-error attempt should pause\");\n assert(health.pause_category === \"same_error\", \"pause should be same_error\");\n}\n\nfunction testImmediateBlockers() {\n const health = updateLoopHealth({}, {\n failure_class: LOOP_HEALTH_FAILURE_CLASSES.PERMISSION_DENIAL,\n error: \"permission denied\",\n });\n assert(health.pause_recommended === true, \"permission denial should pause immediately\");\n assert(health.pause_category === LOOP_HEALTH_FAILURE_CLASSES.PERMISSION_DENIAL, \"pause category should preserve blocker\");\n}\n\nfunction testRateLimitDefers() {\n const signal = classifyLoopSignal({ error: \"429 too many requests\" });\n const health = updateLoopHealth({}, signal);\n assert(signal.failure_class === LOOP_HEALTH_FAILURE_CLASSES.RATE_LIMITED, \"rate limit should classify\");\n assert(health.pause_recommended === true, \"rate limit should pause/defer\");\n assert(health.pause_category === LOOP_HEALTH_FAILURE_CLASSES.RATE_LIMITED, \"pause category should be rate_limited\");\n}\n\ntestNormalizeErrorSignature();\ntestProgressResetsCounters();\ntestNoProgressThreshold();\ntestSameErrorThreshold();\ntestImmediateBlockers();\ntestRateLimitDefers();\n\nprocess.stdout.write(\"loop-health helper tests passed\\n\");\n","content_type":"text/javascript","language":"javascript","size":3347,"content_sha256":"6271efc6d67c87a17725cfe6f9cf2b698c2adac549d2b195de4dc06acc392187"},{"filename":"references/scripts/coordinator-runtime/test/platform-regression.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/coordinator-runtime/test/platform-regression.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createJsonCliRunner,\n createProjectRoot,\n writeJson,\n} from \"./cli-test-helpers.mjs\";\nimport { WORKER_SUMMARY_STATUSES } from \"../lib/runtime-constants.mjs\";\n\nconst scriptsRoot = resolve(dirname(fileURLToPath(import.meta.url)), \"../..\");\n\nconst envCli = join(scriptsRoot, \"environment-setup-runtime/cli.mjs\");\nconst storyCli = join(scriptsRoot, \"story-planning-runtime/cli.mjs\");\nconst taskCli = join(scriptsRoot, \"task-planning-runtime/cli.mjs\");\nconst evaluationCli = join(scriptsRoot, \"evaluation-runtime/cli.mjs\");\nconst executionCli = join(scriptsRoot, \"story-execution-runtime/cli.mjs\");\nconst gateCli = join(scriptsRoot, \"story-gate-runtime/cli.mjs\");\nconst optimizationCli = join(scriptsRoot, \"optimization-runtime/cli.mjs\");\n\nfunction assert(condition, message) {\n if (!condition) {\n throw new Error(message);\n }\n}\n\nfunction assertInactiveStatus(cliPath, args = []) {\n const projectRoot = createProjectRoot(\"runtime-platform-inactive-\");\n const run = createJsonCliRunner(cliPath, projectRoot);\n const status = run([\"status\", ...args]);\n assert(status.ok === true, `Inactive status failed for ${cliPath}`);\n assert(status.active === false, `Inactive status should be false for ${cliPath}`);\n assert(status.runtime === null, `Inactive runtime should be null for ${cliPath}`);\n}\n\nfunction writeManifest(projectRoot, name, payload) {\n const filePath = join(projectRoot, `${name}.json`);\n writeJson(filePath, payload);\n return filePath;\n}\n\nfunction testInactiveShape() {\n assertInactiveStatus(envCli);\n assertInactiveStatus(storyCli);\n assertInactiveStatus(taskCli);\n assertInactiveStatus(evaluationCli, [\"--skill\", \"ln-310\"]);\n assertInactiveStatus(executionCli);\n assertInactiveStatus(gateCli);\n assertInactiveStatus(optimizationCli);\n}\n\nfunction testEnvironmentReplayFromHistory() {\n const projectRoot = createProjectRoot(\"runtime-platform-replay-\");\n const run = createJsonCliRunner(envCli, projectRoot);\n const manifestFile = writeManifest(projectRoot, \"env-manifest\", {\n targets: [\"both\"],\n dry_run: true,\n });\n\n const started = run([\"start\", \"--identifier\", \"targets-both\", \"--manifest-file\", manifestFile]);\n assert(started.ok === true, \"Environment run should start\");\n\n run([\n \"checkpoint\",\n \"--identifier\",\n \"targets-both\",\n \"--phase\",\n \"PHASE_0_CONFIG\",\n \"--payload\",\n JSON.stringify({ initialized: true }),\n ]);\n run([\"advance\", \"--identifier\", \"targets-both\", \"--to\", \"PHASE_1_ASSESS\"]);\n run([\n \"checkpoint\",\n \"--identifier\",\n \"targets-both\",\n \"--phase\",\n \"PHASE_1_ASSESS\",\n \"--payload\",\n JSON.stringify({ assess_summary: { status: WORKER_SUMMARY_STATUSES.COMPLETED } }),\n ]);\n run([\"advance\", \"--identifier\", \"targets-both\", \"--to\", \"PHASE_1B_PROVIDER_SELECTION\"]);\n run([\n \"checkpoint\",\n \"--identifier\",\n \"targets-both\",\n \"--phase\",\n \"PHASE_1B_PROVIDER_SELECTION\",\n \"--payload\",\n JSON.stringify({\n provider_selection: {\n chosen: \"file\",\n available: [\"linear\", \"github\", \"file\"],\n reason: \"test\",\n selected_by: \"user\",\n },\n }),\n ]);\n run([\"advance\", \"--identifier\", \"targets-both\", \"--to\", \"PHASE_2_DISPATCH_PLAN\"]);\n\n const runDir = join(projectRoot, \".hex-skills\", \"environment-setup\", \"runtime\", \"runs\", started.run_id);\n writeFileSync(join(runDir, \"manifest.json\"), \"{broken\", \"utf8\");\n writeFileSync(join(runDir, \"state.json\"), \"{broken\", \"utf8\");\n writeFileSync(join(runDir, \"checkpoints.json\"), \"{broken\", \"utf8\");\n\n const status = run([\"status\", \"--identifier\", \"targets-both\"]);\n assert(status.ok === true, \"Replay status should succeed\");\n assert(status.state.phase === \"PHASE_2_DISPATCH_PLAN\", \"Replay should restore latest phase from history\");\n assert(status.runtime.run_id === started.run_id, \"Replay should preserve run id\");\n}\n\nfunction testPauseResumeAcrossPlanningFamilies() {\n const storyRoot = createProjectRoot(\"runtime-platform-story-\");\n const runStory = createJsonCliRunner(storyCli, storyRoot);\n const storyManifest = writeManifest(storyRoot, \"story-manifest\", {\n epic_id: \"42\",\n auto_approve: false,\n });\n\n runStory([\"start\", \"--epic\", \"42\", \"--manifest-file\", storyManifest]);\n runStory([\n \"pause\",\n \"--epic\",\n \"42\",\n \"--reason\",\n \"Preview required\",\n \"--payload\",\n JSON.stringify({\n kind: \"preview_confirmation\",\n question: \"Confirm preview?\",\n choices: [\"confirm_preview\", \"cancel\"],\n default_choice: \"confirm_preview\",\n context: { epic_id: \"42\" },\n resume_to_phase: \"PHASE_6_DELEGATE\",\n blocking: true,\n }),\n ]);\n const pausedStory = runStory([\"status\", \"--epic\", \"42\"]);\n assert(pausedStory.resume_action === \"Resolve pending decision: preview_confirmation\", \"Story planning resume action mismatch\");\n const resumedStory = runStory([\n \"set-decision\",\n \"--epic\",\n \"42\",\n \"--payload\",\n JSON.stringify({ selected_choice: \"confirm_preview\" }),\n ]);\n assert(resumedStory.state.phase === \"PHASE_6_DELEGATE\", \"Story planning should resume to delegate phase\");\n\n const taskRoot = createProjectRoot(\"runtime-platform-task-\");\n const runTask = createJsonCliRunner(taskCli, taskRoot);\n const taskManifest = writeManifest(taskRoot, \"task-manifest\", {\n story_id: \"99\",\n auto_approve: false,\n });\n\n runTask([\"start\", \"--story\", \"99\", \"--manifest-file\", taskManifest]);\n runTask([\n \"pause\",\n \"--story\",\n \"99\",\n \"--reason\",\n \"Readiness approval required\",\n \"--payload\",\n JSON.stringify({\n kind: \"readiness_approval\",\n question: \"Proceed with readiness score 5?\",\n choices: [\"continue\", \"cancel\"],\n default_choice: \"continue\",\n context: { story_id: \"99\" },\n resume_to_phase: \"PHASE_4_MODE_DETECTION\",\n blocking: true,\n }),\n ]);\n const pausedTask = runTask([\"status\", \"--story\", \"99\"]);\n assert(pausedTask.resume_action === \"Resolve pending decision: readiness_approval\", \"Task planning resume action mismatch\");\n const resumedTask = runTask([\n \"set-decision\",\n \"--story\",\n \"99\",\n \"--payload\",\n JSON.stringify({ selected_choice: \"continue\" }),\n ]);\n assert(resumedTask.state.phase === \"PHASE_4_MODE_DETECTION\", \"Task planning should resume to mode detection phase\");\n}\n\nfunction testIsolationAcrossIdentifiers() {\n const envRoot = createProjectRoot(\"runtime-platform-isolation-env-\");\n const runEnv = createJsonCliRunner(envCli, envRoot);\n const envManifest = writeManifest(envRoot, \"env-manifest\", {\n targets: [\"both\"],\n dry_run: true,\n });\n\n runEnv([\"start\", \"--identifier\", \"targets-both\", \"--manifest-file\", envManifest]);\n runEnv([\"start\", \"--identifier\", \"targets-codex\", \"--manifest-file\", envManifest]);\n\n const ambiguousEnv = runEnv([\"status\"], { allowFailure: true });\n assert(ambiguousEnv.ok === false, \"Environment status without identifier should fail when multiple runs exist\");\n\n const taskRoot = createProjectRoot(\"runtime-platform-isolation-task-\");\n const runTask = createJsonCliRunner(taskCli, taskRoot);\n const taskManifest = writeManifest(taskRoot, \"task-manifest\", {\n auto_approve: true,\n });\n\n runTask([\"start\", \"--story\", \"1\", \"--manifest-file\", taskManifest]);\n runTask([\"start\", \"--story\", \"2\", \"--manifest-file\", taskManifest]);\n\n const ambiguousTask = runTask([\"status\"], { allowFailure: true });\n assert(ambiguousTask.ok === false, \"Task planning status without story should fail when multiple runs exist\");\n}\n\nfunction testInvalidResumeToPhase() {\n const storyRoot = createProjectRoot(\"runtime-platform-bad-resume-\");\n const runStory = createJsonCliRunner(storyCli, storyRoot);\n const manifest = writeManifest(storyRoot, \"story-manifest\", {\n epic_id: \"bad-1\",\n auto_approve: false,\n });\n\n runStory([\"start\", \"--epic\", \"bad-1\", \"--manifest-file\", manifest]);\n\n // Test 1: invalid resume_to_phase at pause time\n const badPause = runStory([\n \"pause\", \"--epic\", \"bad-1\", \"--reason\", \"Test\",\n \"--payload\", JSON.stringify({\n kind: \"test\", question: \"Test?\", choices: [\"yes\", \"no\"],\n default_choice: \"yes\", context: {},\n resume_to_phase: \"PHASE_99_INVALID\", blocking: true,\n }),\n ], { allowFailure: true });\n assert(badPause.ok === false, \"Pause with invalid resume_to_phase should fail\");\n\n // Test 2: terminal phase (DONE) as resume target\n const terminalPause = runStory([\n \"pause\", \"--epic\", \"bad-1\", \"--reason\", \"Test\",\n \"--payload\", JSON.stringify({\n kind: \"test\", question: \"Test?\", choices: [\"yes\", \"no\"],\n default_choice: \"yes\", context: {},\n resume_to_phase: \"DONE\", blocking: true,\n }),\n ], { allowFailure: true });\n assert(terminalPause.ok === false, \"Pause with terminal resume_to_phase should fail\");\n\n // Test 3: valid pause, then invalid selected_choice\n runStory([\n \"pause\", \"--epic\", \"bad-1\", \"--reason\", \"Test\",\n \"--payload\", JSON.stringify({\n kind: \"test\", question: \"Test?\", choices: [\"yes\", \"no\"],\n default_choice: \"yes\", context: {},\n resume_to_phase: \"PHASE_6_DELEGATE\", blocking: true,\n }),\n ]);\n const badChoice = runStory([\n \"set-decision\", \"--epic\", \"bad-1\",\n \"--payload\", JSON.stringify({ selected_choice: \"maybe\" }),\n ], { allowFailure: true });\n assert(badChoice.ok === false, \"Decision with invalid selected_choice should fail\");\n}\n\n\ntestInactiveShape();\ntestEnvironmentReplayFromHistory();\ntestPauseResumeAcrossPlanningFamilies();\ntestIsolationAcrossIdentifiers();\ntestInvalidResumeToPhase();\n\nprocess.stdout.write(\"platform regression passed\\n\");\n","content_type":"text/javascript","language":"javascript","size":10470,"content_sha256":"fbd029937817751483080fe2170b60c0093e86c10195cbb340310e0a68423384"},{"filename":"references/scripts/docs-pipeline-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/docs-pipeline-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n SOURCE_SCAN: \"PHASE_1_SOURCE_SCAN\",\n CONFIRMATION: \"PHASE_2_CONFIRMATION\",\n DELEGATE: \"PHASE_3_DELEGATE\",\n QUALITY_GATE: \"PHASE_4_QUALITY_GATE\",\n CLEANUP: \"PHASE_5_CLEANUP\",\n SELF_CHECK: \"PHASE_6_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":615,"content_sha256":"3f817658715cbeea3abf1b5402181569de33c3ba5e11d7bff37088e26d8e48ec"},{"filename":"references/scripts/docs-pipeline-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/docs-pipeline-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport { docsGenerationWorkerSummarySchema } from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport {\n createPlanningManifestSchema,\n createPlanningRuntimeStore,\n createPlanningState,\n} from \"../../planning-runtime/lib/store.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst pipelineStore = createPlanningRuntimeStore({\n baseRootParts: [\".hex-skills\", \"docs-pipeline\", \"runtime\"],\n manifestSchema: createPlanningManifestSchema(\"pipeline_id\"),\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-100\",\n mode: manifestInput.mode || \"docs_pipeline\",\n identifier: manifestInput.identifier || \"docs-pipeline\",\n pipeline_id: manifestInput.pipeline_id || \"docs-pipeline\",\n task_provider: manifestInput.task_provider || \"unknown\",\n auto_approve: manifestInput.auto_approve === true,\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return createPlanningState(manifest, runId, PHASES.CONFIG, {\n pipeline_id: manifest.pipeline_id,\n source_manifest: [],\n source_mode: null,\n component_results: {},\n quality_summary: null,\n cleanup_summary: null,\n });\n },\n pausedPhase: PHASES.PAUSED,\n resumablePhases: new Set(Object.values(PHASES).filter(p => p !== PHASES.PAUSED && p !== PHASES.DONE)),\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n updateState,\n} = pipelineStore;\n\nexport function recordComponent(projectRoot, runId, summary) {\n return pipelineStore.recordSummary(\n projectRoot,\n runId,\n summary,\n docsGenerationWorkerSummarySchema,\n \"docs pipeline component summary\",\n (state, nextSummary) => ({\n ...state,\n component_results: {\n ...state.component_results,\n [nextSummary.payload.worker]: nextSummary,\n },\n }),\n );\n}\n","content_type":"text/javascript","language":"javascript","size":2431,"content_sha256":"083b4e37146a3f16f95c661f3768e977260e30144a2dc09e1cbc6499e076765d"},{"filename":"references/scripts/environment-setup-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n recordWorker,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n identifier: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-010\", values[\"run-id\"], values.identifier);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-010\");\n if (activeRuns.length > 1 && !values.identifier) {\n fail(\"Multiple active ln-010 runs found. Pass --identifier or --run-id.\");\n }\n fail(\"No active ln-010 run found. Pass --identifier or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n\n if (phase === PHASES.ASSESS) {\n nextState.assess_summary = payload.assess_summary || payload.summary || payload;\n }\n if (phase === PHASES.PROVIDER_SELECTION) {\n if (payload.provider_selection && typeof payload.provider_selection === \"object\") {\n nextState.provider_selection = payload.provider_selection;\n } else if (payload.chosen) {\n nextState.provider_selection = {\n chosen: payload.chosen,\n available: payload.available || [payload.chosen],\n reason: payload.reason || null,\n selected_by: payload.selected_by || \"user\",\n };\n }\n }\n if (phase === PHASES.DISPATCH_PLAN) {\n if (payload.dispatch_plan && typeof payload.dispatch_plan === \"object\") {\n nextState.dispatch_plan = payload.dispatch_plan;\n } else if (payload.plan && typeof payload.plan === \"object\") {\n nextState.dispatch_plan = payload.plan;\n }\n }\n if (phase === PHASES.VERIFY) {\n nextState.verification_summary = payload.verification_summary || payload.summary || payload;\n }\n if (phase === PHASES.WRITE_ENV_STATE) {\n nextState.env_state_written = payload.env_state_written === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.identifier || !values[\"manifest-file\"]) {\n fail(\"start requires --identifier and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, { ...manifest, identifier: values.identifier });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.identifier) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-010\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-010 runs found. Pass --identifier or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-010\", values.identifier);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-worker\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorker(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"set-decision\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordDecision(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = Object.keys(payload).length > 0\n ? setPendingDecision(projectRoot, runId, payload, values.reason || \"Decision required\")\n : pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-worker, set-decision, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":8150,"content_sha256":"5fa89e8445e4a26197ddec16e6a86bd6a220f1ce5306b9b59f0f44ea8182b5fe"},{"filename":"references/scripts/environment-setup-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.ASSESS])],\n [PHASES.ASSESS, new Set([PHASES.PROVIDER_SELECTION])],\n [PHASES.PROVIDER_SELECTION, new Set([PHASES.DISPATCH_PLAN])],\n [PHASES.DISPATCH_PLAN, new Set([PHASES.WORKER_EXECUTION])],\n [PHASES.WORKER_EXECUTION, new Set([PHASES.VERIFY])],\n [PHASES.VERIFY, new Set([PHASES.WRITE_ENV_STATE])],\n [PHASES.WRITE_ENV_STATE, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction requiredWorkers(dispatchPlan) {\n return (dispatchPlan?.workers_to_run || []).length;\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n if (state.pending_decision) {\n return { ok: false, error: \"Pending decision must be resolved before advancing\" };\n }\n\n if (toPhase === PHASES.PROVIDER_SELECTION && !state.assess_summary) {\n return { ok: false, error: \"Assessment summary missing\" };\n }\n\n if (toPhase === PHASES.DISPATCH_PLAN && !state.provider_selection?.chosen) {\n return { ok: false, error: \"Tracker provider selection missing - run Phase 1b\" };\n }\n\n if (toPhase === PHASES.WORKER_EXECUTION) {\n if (!state.dispatch_plan || !Array.isArray(state.dispatch_plan.workers_to_run)) {\n return { ok: false, error: \"Dispatch plan missing\" };\n }\n }\n\n if (toPhase === PHASES.VERIFY) {\n const expected = requiredWorkers(state.dispatch_plan);\n const actual = Object.keys(state.worker_results || {}).length;\n if (expected > 0 && actual \u003c expected) {\n return { ok: false, error: \"Not all dispatched workers recorded summaries\" };\n }\n }\n\n if (toPhase === PHASES.WRITE_ENV_STATE && !state.verification_summary) {\n return { ok: false, error: \"Verification summary missing\" };\n }\n\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.env_state_written && state.final_result !== \"DRY_RUN_PLAN\") {\n return { ok: false, error: \"Environment state write not recorded\" };\n }\n }\n\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n if (state.pending_decision) {\n return `Resolve pending decision: ${state.pending_decision.kind}`;\n }\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.PROVIDER_SELECTION && !state.provider_selection?.chosen) {\n return \"Resolve tracker provider selection (record-decision) before advancing\";\n }\n if (state.phase === PHASES.WORKER_EXECUTION) {\n const expected = requiredWorkers(state.dispatch_plan);\n const actual = Object.keys(state.worker_results || {}).length;\n if (expected > actual) {\n return \"Record remaining worker summaries before verification\";\n }\n }\n if (state.phase === PHASES.WRITE_ENV_STATE && !state.env_state_written) {\n return `Write .hex-skills/environment_state.json and checkpoint ${PHASES.WRITE_ENV_STATE}`;\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":4450,"content_sha256":"53295615de28d93446ff342fd148a8beffa13b1709afe7d6421b1d7349c43404"},{"filename":"references/scripts/environment-setup-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n ASSESS: \"PHASE_1_ASSESS\",\n PROVIDER_SELECTION: \"PHASE_1B_PROVIDER_SELECTION\",\n DISPATCH_PLAN: \"PHASE_2_DISPATCH_PLAN\",\n WORKER_EXECUTION: \"PHASE_3_WORKER_EXECUTION\",\n VERIFY: \"PHASE_4_VERIFY\",\n WRITE_ENV_STATE: \"PHASE_5_WRITE_ENV_STATE\",\n SELF_CHECK: \"PHASE_6_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":686,"content_sha256":"2400c3a89bc6a3007f915ebd70e021ac42d6d294b95c9c7ce09402cd7eba18b3"},{"filename":"references/scripts/environment-setup-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport { environmentWorkerSummarySchema, pendingDecisionSchema } from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst environmentSetupManifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n targets: {\n type: \"array\",\n items: { type: \"string\" },\n },\n dry_run: { type: \"boolean\" },\n plugins: {\n type: \"array\",\n items: { type: \"string\" },\n },\n auto_install_providers: { type: \"boolean\" },\n apply_ide_override: { type: \"boolean\" },\n project_root: { type: \"string\" },\n worker_registry: { type: \"array\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst environmentStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"environment-setup\", \"runtime\"],\n manifestSchema: environmentSetupManifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n const targets = Array.isArray(manifestInput.targets) && manifestInput.targets.length > 0\n ? manifestInput.targets\n : [manifestInput.targets || \"both\"];\n const plugins = Array.isArray(manifestInput.plugins) && manifestInput.plugins.length > 0\n ? manifestInput.plugins\n : [\"agile-workflow\"];\n return {\n skill: \"ln-010\",\n mode: manifestInput.mode || \"environment_setup\",\n identifier: manifestInput.identifier || `targets-${targets.join(\"-\")}`,\n targets,\n dry_run: manifestInput.dry_run === true,\n plugins,\n auto_install_providers: manifestInput.auto_install_providers === true,\n apply_ide_override: manifestInput.apply_ide_override === true,\n project_root: resolve(projectRoot || process.cwd()),\n worker_registry: manifestInput.worker_registry || [\"ln-011\", \"ln-012\", \"ln-013\", \"ln-014\"],\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n phase: PHASES.CONFIG,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n assess_summary: null,\n provider_selection: null,\n dispatch_plan: null,\n worker_results: {},\n verification_summary: null,\n env_state_written: false,\n self_check_passed: false,\n final_result: manifest.dry_run ? \"DRY_RUN_PLAN\" : null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = environmentStore;\n\nexport function recordWorker(projectRoot, runId, workerSummary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(environmentWorkerSummarySchema, workerSummary, \"environment worker summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n worker_results: {\n ...state.worker_results,\n [workerSummary.producer_skill]: workerSummary,\n },\n }));\n}\n\nexport function setPendingDecision(projectRoot, runId, pendingDecision, reason = \"Decision required\") {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(pendingDecisionSchema, pendingDecision, \"pending decision\");\n if (!validation.ok) {\n return validation;\n }\n if (pendingDecision.resume_to_phase === PHASES.PAUSED || pendingDecision.resume_to_phase === PHASES.DONE) {\n return { ok: false, error: `Invalid resume_to_phase: ${pendingDecision.resume_to_phase}` };\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n phase: PHASES.PAUSED,\n paused_reason: reason,\n pending_decision: pendingDecision,\n }), { eventType: \"RUN_PAUSED\" });\n}\n\nexport function recordDecision(projectRoot, runId, decision) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (!run.state.pending_decision) {\n return { ok: false, error: \"No pending decision recorded\" };\n }\n if (run.state.pending_decision.resume_to_phase === PHASES.PAUSED || run.state.pending_decision.resume_to_phase === PHASES.DONE) {\n return { ok: false, error: `Invalid resume_to_phase: ${run.state.pending_decision.resume_to_phase}` };\n }\n const choices = run.state.pending_decision.choices || [];\n if (choices.length > 0 && !choices.includes(decision.selected_choice)) {\n return { ok: false, error: `Invalid selected_choice: ${decision.selected_choice}. Valid: ${choices.join(\", \")}` };\n }\n const nextDecision = {\n kind: run.state.pending_decision.kind,\n selected_choice: decision.selected_choice,\n answered_at: new Date().toISOString(),\n context: decision.context || {},\n };\n return updateState(projectRoot, runId, state => ({\n ...state,\n phase: state.pending_decision.resume_to_phase,\n paused_reason: null,\n pending_decision: null,\n decisions: [...(state.decisions || []), nextDecision],\n }));\n}\n\nexport {\n readJsonFile,\n};\n","content_type":"text/javascript","language":"javascript","size":6246,"content_sha256":"ba6a0b2203d10c72d8bf95fde4e695690b096613c558d59314ed89b04fb22eae"},{"filename":"references/scripts/environment-setup-runtime/test/guards.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/test/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createJsonCliRunner,\n createProjectRoot,\n writeJson,\n} from \"../../coordinator-runtime/test/cli-test-helpers.mjs\";\nimport { WORKER_SUMMARY_STATUSES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"../lib/phases.mjs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst cliPath = join(__dirname, \"..\", \"cli.mjs\");\nconst projectRoot = createProjectRoot(\"env-setup-guards-\");\nconst run = createJsonCliRunner(cliPath, projectRoot);\n\nlet passed = 0;\nlet failed = 0;\nconst P = \"--project-root\";\nconst I = \"--identifier\";\nconst ID = \"env-g\";\n\nfunction expect(name, result, expectedOk) {\n if (result.ok === expectedOk) { passed++; process.stdout.write(` PASS: ${name}\\n`); }\n else { failed++; process.stdout.write(` FAIL: ${name} (expected ok=${expectedOk}, got ok=${result.ok}, error=${result.error})\\n`); }\n}\n\nfunction workerSummary(skill, runId) {\n return JSON.stringify({\n schema_version: \"1.0\", summary_kind: \"env-agent-install\",\n run_id: runId, identifier: ID, producer_skill: skill,\n produced_at: \"2026-03-30T00:00:00Z\",\n payload: { status: WORKER_SUMMARY_STATUSES.COMPLETED, targets: [\"codex\"] },\n });\n}\n\ntry {\n const manifestPath = join(projectRoot, \"manifest.json\");\n writeJson(manifestPath, { targets: [\"both\"], dry_run: false });\n\n const started = run([\"start\", P, projectRoot, I, ID, \"--manifest-file\", manifestPath]);\n if (started.manifest.plugins.join(\",\") !== \"agile-workflow\") {\n throw new Error(\"Default plugin selection must be agile-workflow\");\n }\n if (started.manifest.worker_registry.includes(\"ln-015\")) {\n throw new Error(\"ln-015 must remain standalone and outside default environment setup dispatch\");\n }\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.CONFIG]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.ASSESS]);\n\n // Fast-forward to PROVIDER_SELECTION (assess_summary required)\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.ASSESS, \"--payload\", \"{\\\"assess_summary\\\":{\\\"node\\\":true}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.PROVIDER_SELECTION]);\n\n // TEST 1: DISPATCH_PLAN blocked without provider_selection.chosen\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.PROVIDER_SELECTION]);\n const t1 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.DISPATCH_PLAN], { allowFailure: true });\n expect(\"DISPATCH_PLAN blocked without provider_selection\", t1, false);\n\n // Fix: record provider_selection\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.PROVIDER_SELECTION, \"--payload\", \"{\\\"provider_selection\\\":{\\\"chosen\\\":\\\"file\\\",\\\"available\\\":[\\\"file\\\"],\\\"reason\\\":\\\"only file mode available\\\",\\\"selected_by\\\":\\\"single_option\\\"}}\"]);\n\n // TEST 2: DISPATCH_PLAN allowed with provider_selection\n const t2 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.DISPATCH_PLAN]);\n expect(\"DISPATCH_PLAN allowed with provider_selection\", t2, true);\n\n // TEST 3: WORKER_EXECUTION blocked without dispatch_plan\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.DISPATCH_PLAN]);\n const t3 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.WORKER_EXECUTION], { allowFailure: true });\n expect(\"WORKER_EXECUTION blocked without dispatch_plan\", t3, false);\n\n // Fix\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.DISPATCH_PLAN, \"--payload\", \"{\\\"dispatch_plan\\\":{\\\"workers_to_run\\\":[\\\"ln-011\\\",\\\"ln-013\\\"]}}\"]);\n\n // TEST 4: WORKER_EXECUTION allowed\n const t4 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.WORKER_EXECUTION]);\n expect(\"WORKER_EXECUTION allowed with dispatch_plan\", t4, true);\n\n // TEST 5: VERIFY blocked with incomplete workers (1/2)\n run([\"record-worker\", P, projectRoot, I, ID, \"--payload\", workerSummary(\"ln-011\", started.run_id)]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.WORKER_EXECUTION]);\n const t5 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.VERIFY], { allowFailure: true });\n expect(\"VERIFY blocked with 1/2 workers\", t5, false);\n\n // Fix: record second worker\n run([\"record-worker\", P, projectRoot, I, ID, \"--payload\", workerSummary(\"ln-013\", started.run_id)]);\n\n // TEST 6: VERIFY allowed with all workers\n const t6 = run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.VERIFY]);\n expect(\"VERIFY allowed with 2/2 workers\", t6, true);\n\n // Fast-forward to WRITE_ENV_STATE (verification_summary required)\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.VERIFY, \"--payload\", \"{\\\"verification_summary\\\":{\\\"all_passed\\\":true}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.WRITE_ENV_STATE]);\n\n process.stdout.write(`\\nenvironment-setup-runtime guards: ${passed} passed, ${failed} failed\\n`);\n if (failed > 0) process.exit(1);\n} finally {\n rmSync(projectRoot, { recursive: true, force: true });\n}\n","content_type":"text/javascript","language":"javascript","size":5248,"content_sha256":"5785af4d67d418c8d1e400ad3564ae7124965f5a409d0c655a8eb1dafb52dd5e"},{"filename":"references/scripts/environment-setup-runtime/test/smoke.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/environment-setup-runtime/test/smoke.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createJsonCliRunner,\n createProjectRoot,\n writeJson,\n} from \"../../coordinator-runtime/test/cli-test-helpers.mjs\";\nimport {\n ENVIRONMENT_SETUP_FINAL_RESULTS,\n WORKER_SUMMARY_STATUSES,\n} from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"../lib/phases.mjs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst cliPath = join(__dirname, \"..\", \"cli.mjs\");\nconst projectRoot = createProjectRoot(\"environment-setup-runtime-\");\nconst run = createJsonCliRunner(cliPath, projectRoot);\n\nconst ID = \"targets-both\";\nconst P = \"--project-root\";\nconst I = \"--identifier\";\n\ntry {\n const manifestPath = join(projectRoot, \"manifest.json\");\n writeJson(manifestPath, {\n targets: [\"both\"],\n dry_run: false,\n plugins: [\"agile-workflow\", \"codebase-audit-suite\"],\n auto_install_providers: true,\n apply_ide_override: true,\n });\n\n const started = run([\"start\", P, projectRoot, I, ID, \"--manifest-file\", manifestPath]);\n if (!started.ok) {\n throw new Error(\"Failed to start environment setup runtime\");\n }\n if (started.manifest.plugins.join(\",\") !== \"agile-workflow,codebase-audit-suite\") {\n throw new Error(\"Environment setup manifest did not preserve plugin selection\");\n }\n if (started.manifest.auto_install_providers !== true || started.manifest.apply_ide_override !== true) {\n throw new Error(\"Environment setup manifest did not preserve pass-through flags\");\n }\n if (started.manifest.worker_registry.includes(\"ln-015\")) {\n throw new Error(\"ln-015 must remain standalone and outside default environment setup dispatch\");\n }\n\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.CONFIG]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.ASSESS]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.ASSESS, \"--payload\", \"{\\\"assess_summary\\\":{\\\"node\\\":true}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.PROVIDER_SELECTION]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.PROVIDER_SELECTION, \"--payload\", \"{\\\"provider_selection\\\":{\\\"chosen\\\":\\\"file\\\",\\\"available\\\":[\\\"linear\\\",\\\"github\\\",\\\"file\\\"],\\\"reason\\\":\\\"user choice\\\",\\\"selected_by\\\":\\\"user\\\"}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.DISPATCH_PLAN]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.DISPATCH_PLAN, \"--payload\", \"{\\\"dispatch_plan\\\":{\\\"workers_to_run\\\":[\\\"ln-011\\\",\\\"ln-013\\\"]}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.WORKER_EXECUTION]);\n run([\"record-worker\", P, projectRoot, I, ID, \"--payload\", JSON.stringify({ schema_version: \"1.0\", summary_kind: \"env-agent-install\", run_id: started.run_id, identifier: ID, producer_skill: \"ln-011\", produced_at: \"2026-03-26T00:00:00Z\", payload: { status: WORKER_SUMMARY_STATUSES.COMPLETED, targets: [\"codex\"] } })]);\n run([\"record-worker\", P, projectRoot, I, ID, \"--payload\", JSON.stringify({ schema_version: \"1.0\", summary_kind: \"env-marketplace-align\", run_id: started.run_id, identifier: ID, producer_skill: \"ln-013\", produced_at: \"2026-03-26T00:00:00Z\", payload: { status: WORKER_SUMMARY_STATUSES.COMPLETED, targets: [\"claude\"] } })]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.WORKER_EXECUTION]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.VERIFY]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.VERIFY, \"--payload\", \"{\\\"verification_summary\\\":{\\\"hooks\\\":\\\"ok\\\"}}\"]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.WRITE_ENV_STATE]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.WRITE_ENV_STATE, \"--payload\", JSON.stringify({ env_state_written: true, final_result: ENVIRONMENT_SETUP_FINAL_RESULTS.READY })]);\n run([\"advance\", P, projectRoot, I, ID, \"--to\", PHASES.SELF_CHECK]);\n run([\"checkpoint\", P, projectRoot, I, ID, \"--phase\", PHASES.SELF_CHECK, \"--payload\", JSON.stringify({ pass: true, final_result: ENVIRONMENT_SETUP_FINAL_RESULTS.READY })]);\n const completed = run([\"complete\", P, projectRoot, I, ID]);\n\n if (!completed.ok || completed.state.phase !== PHASES.DONE) {\n throw new Error(\"Environment setup runtime did not complete\");\n }\n if (completed.state.provider_selection?.chosen !== \"file\") {\n throw new Error(\"provider_selection.chosen was not persisted to final state\");\n }\n\n process.stdout.write(\"environment-setup-runtime smoke passed\\n\");\n} finally {\n rmSync(projectRoot, { recursive: true, force: true });\n}\n","content_type":"text/javascript","language":"javascript","size":4826,"content_sha256":"40ea44d6f9200eaffd59003f027aa81985bc6819a651bc17c6f67f9aaedd0cf9"},{"filename":"references/scripts/epic-planning-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/epic-planning-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n recordPlanSummary,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\nimport {\n advancePlanningRun,\n checkpointPlanningRun,\n completePlanningRun,\n loadPlanningStatusRun,\n outputInactiveRuntime,\n outputPlanningStatus,\n pausePlanningRun,\n resolvePlanningRunOrFail,\n} from \"../planning-runtime/lib/cli.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n identifier: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n return resolvePlanningRunOrFail({\n projectRoot,\n skill: \"ln-210\",\n runId: values[\"run-id\"],\n identifier: values.identifier || \"scope\",\n identifierFlag: \"identifier\",\n listActiveRuns,\n resolveRunId,\n loadRun,\n fail,\n });\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n if (phase === PHASES.DISCOVERY) {\n nextState.discovery_summary = payload.discovery_summary || payload;\n }\n if (phase === PHASES.RESEARCH) {\n nextState.research_summary = payload.research_summary || payload;\n }\n if (phase === PHASES.PLAN) {\n nextState.ideal_plan_summary = payload.ideal_plan_summary || payload;\n }\n if (phase === PHASES.MODE_DETECTION) {\n nextState.mode_detection = payload.mode_detection || payload;\n }\n if (phase === PHASES.FINALIZE) {\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values[\"manifest-file\"]) {\n fail(\"start requires --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n identifier: values.identifier || manifest.identifier || \"scope\",\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n const run = loadPlanningStatusRun({\n projectRoot,\n skill: \"ln-210\",\n runId: values[\"run-id\"],\n identifier: values.identifier || \"scope\",\n identifierFlag: \"identifier\",\n listActiveRuns,\n loadRun,\n loadActiveRun,\n output,\n });\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputPlanningStatus(projectRoot, run, runtimePaths, computeResumeAction, output);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n advancePlanningRun(projectRoot, runId, run, values.to, validateTransition, saveState, PHASES.DONE, output);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n checkpointPlanningRun(projectRoot, runId, run, values.phase, payload, checkpointPhase, saveState, applyCheckpointToState, fail, output);\n return;\n }\n\n if (command === \"set-decision\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordDecision(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-plan-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordPlanSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n pausePlanningRun(projectRoot, runId, payload, values.reason, pauseRun, setPendingDecision, fail, output);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n completePlanningRun(projectRoot, runId, run, validateTransition, completeRun, PHASES.DONE, fail, output);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-plan-summary, set-decision, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":5906,"content_sha256":"8781705aa6bd9955377a5b3a1b9b0cc76df509b27fdd53600c1e17091856c43b"},{"filename":"references/scripts/epic-planning-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/epic-planning-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n computePlanningBaseResumeAction,\n hasChoice,\n validatePlanningBaseTransition,\n} from \"../../planning-runtime/lib/guards.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.RESEARCH])],\n [PHASES.RESEARCH, new Set([PHASES.PLAN])],\n [PHASES.PLAN, new Set([PHASES.MODE_DETECTION])],\n [PHASES.MODE_DETECTION, new Set([PHASES.PREVIEW])],\n [PHASES.PREVIEW, new Set([PHASES.DELEGATE])],\n [PHASES.DELEGATE, new Set([PHASES.FINALIZE])],\n [PHASES.FINALIZE, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const base = validatePlanningBaseTransition(state, checkpoints, toPhase, ALLOWED_TRANSITIONS);\n if (!base.ok) {\n return base;\n }\n if (toPhase === PHASES.RESEARCH && !state.discovery_summary) {\n return { ok: false, error: \"Discovery summary missing\" };\n }\n if (toPhase === PHASES.PLAN && !state.research_summary) {\n return { ok: false, error: \"Research summary missing\" };\n }\n if (toPhase === PHASES.MODE_DETECTION && !state.ideal_plan_summary) {\n return { ok: false, error: \"Ideal epic plan missing\" };\n }\n if (toPhase === PHASES.DELEGATE && !manifest.auto_approve && !hasChoice(state.decisions, \"confirm_epic_preview\")) {\n return { ok: false, error: \"Preview confirmation decision missing\" };\n }\n if (toPhase === PHASES.SELF_CHECK && !state.epic_plan_summary) {\n return { ok: false, error: \"Epic plan coordinator summary missing\" };\n }\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n }\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.phase === PHASES.FINALIZE && !state.epic_plan_summary) {\n return \"Record epic-plan coordinator summary before self-check\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n return computePlanningBaseResumeAction(\n state,\n checkpoints,\n ALLOWED_TRANSITIONS,\n PHASES.PAUSED,\n PHASES.DONE,\n );\n}\n","content_type":"text/javascript","language":"javascript","size":2756,"content_sha256":"c5d01934929be8c916c695ed236a83b0a4497efd63c55a69312f301b4eabaa8c"},{"filename":"references/scripts/epic-planning-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/epic-planning-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n RESEARCH: \"PHASE_2_RESEARCH\",\n PLAN: \"PHASE_3_PLAN\",\n MODE_DETECTION: \"PHASE_4_MODE_DETECTION\",\n PREVIEW: \"PHASE_5_PREVIEW\",\n DELEGATE: \"PHASE_6_DELEGATE\",\n FINALIZE: \"PHASE_7_FINALIZE\",\n SELF_CHECK: \"PHASE_8_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":667,"content_sha256":"47d42d97c20eabe9a111567c880d2000b6639bd329baa8ffc7f66f7b15e122d9"},{"filename":"references/scripts/epic-planning-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/epic-planning-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport { epicPlanCoordinatorSummarySchema } from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport {\n createPlanningManifestSchema,\n createPlanningRuntimeStore,\n createPlanningState,\n} from \"../../planning-runtime/lib/store.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst epicStore = createPlanningRuntimeStore({\n baseRootParts: [\".hex-skills\", \"epic-planning\", \"runtime\"],\n manifestSchema: createPlanningManifestSchema(\"scope_identifier\"),\n normalizeManifest(manifestInput, projectRoot) {\n const scopeIdentifier = manifestInput.scope_identifier || manifestInput.identifier || \"scope\";\n return {\n skill: \"ln-210\",\n mode: manifestInput.mode || \"epic_planning\",\n identifier: manifestInput.identifier || scopeIdentifier,\n scope_identifier: scopeIdentifier,\n task_provider: manifestInput.task_provider || \"unknown\",\n auto_approve: manifestInput.auto_approve === true,\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return createPlanningState(manifest, runId, PHASES.CONFIG, {\n scope_identifier: manifest.scope_identifier,\n discovery_summary: null,\n research_summary: null,\n ideal_plan_summary: null,\n mode_detection: null,\n epic_plan_summary: null,\n });\n },\n pausedPhase: PHASES.PAUSED,\n resumablePhases: new Set(Object.values(PHASES).filter(p => p !== PHASES.PAUSED && p !== PHASES.DONE)),\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} = epicStore;\n\nexport function recordPlanSummary(projectRoot, runId, summary) {\n return epicStore.recordCoordinatorSummary(\n projectRoot,\n runId,\n summary,\n epicPlanCoordinatorSummarySchema,\n \"epic planning coordinator summary\",\n \"epic_plan_summary\",\n );\n}\n","content_type":"text/javascript","language":"javascript","size":2331,"content_sha256":"593ba09240b1a7cc4c7253b6bed4adb82598f1284ce2e71fe1028e8b719f42e1"},{"filename":"references/scripts/evaluation-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/evaluation-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { existsSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n fileExists,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n recordSummary,\n recordWorkerResult,\n registerAgent,\n resolveRunId,\n resolveTrackedPath,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport {\n computeResumeAction,\n validateTransition,\n} from \"./lib/guards.mjs\";\nimport { REVIEW_AGENT_STATUSES, REVIEW_RESOLVED_AGENT_STATUS_SET } from \"../coordinator-runtime/lib/runtime-constants.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n skill: { type: \"string\" },\n identifier: { type: \"string\" },\n \"run-id\": { type: \"string\" },\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"manifest-file\": { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n agent: { type: \"string\" },\n \"prompt-file\": { type: \"string\" },\n \"result-file\": { type: \"string\" },\n \"log-file\": { type: \"string\" },\n \"metadata-file\": { type: \"string\" },\n reason: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, values.skill, values[\"run-id\"], values.identifier);\n if (!runId) {\n const activeRuns = values.skill ? listActiveRuns(projectRoot, values.skill) : [];\n if (activeRuns.length > 1 && !values.identifier) {\n fail(\"Multiple active runs found. Pass --identifier or --run-id.\");\n }\n fail(\"No active run found. Pass --run-id, or --skill with --identifier.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction mergeObjectMap(current, incoming) {\n if (!incoming || typeof incoming !== \"object\") {\n return current;\n }\n return {\n ...(current || {}),\n ...incoming,\n };\n}\n\nfunction applyCheckpointToState(run, phase, payload) {\n const nextState = {\n ...run.state,\n phase_data: {\n ...(run.state.phase_data || {}),\n [phase]: payload || {},\n },\n };\n const policy = run.manifest.phase_policy || {};\n\n if (Array.isArray(payload.worker_plan)) {\n nextState.worker_plan = payload.worker_plan;\n }\n if (payload.child_run && typeof payload.child_run === \"object\") {\n const childKey = `${payload.child_run.worker}--${payload.child_run.identifier}`;\n nextState.child_runs = {\n ...(run.state.child_runs || {}),\n [childKey]: payload.child_run,\n };\n }\n if (payload.child_runs && typeof payload.child_runs === \"object\") {\n nextState.child_runs = mergeObjectMap(run.state.child_runs, payload.child_runs);\n }\n if (payload.inflight_worker && typeof payload.inflight_worker === \"object\") {\n const inflightKey = `${payload.inflight_worker.worker}--${payload.inflight_worker.identifier}`;\n nextState.inflight_workers = {\n ...(run.state.inflight_workers || {}),\n [inflightKey]: payload.inflight_worker,\n };\n }\n if (payload.inflight_workers && typeof payload.inflight_workers === \"object\") {\n nextState.inflight_workers = mergeObjectMap(run.state.inflight_workers, payload.inflight_workers);\n }\n if (payload.resolved_workers && Array.isArray(payload.resolved_workers)) {\n const inflight = { ...(nextState.inflight_workers || {}) };\n for (const workerKey of payload.resolved_workers) {\n delete inflight[workerKey];\n }\n nextState.inflight_workers = inflight;\n }\n if (payload.final_result) {\n nextState.final_result = payload.final_result;\n }\n if (payload.report_path) {\n nextState.report_path = payload.report_path;\n }\n if (payload.results_log_path) {\n nextState.results_log_path = payload.results_log_path;\n }\n if (payload.research_completed === true || Array.isArray(payload.research_sources) || Array.isArray(payload.research_artifacts)) {\n nextState.research_completed = true;\n }\n if (payload.background_agent_cleanup && typeof payload.background_agent_cleanup === \"object\") {\n nextState.background_agent_cleanup = mergeObjectMap(run.state.background_agent_cleanup, payload.background_agent_cleanup);\n }\n if (payload.refinement_cleanup && typeof payload.refinement_cleanup === \"object\") {\n nextState.refinement_cleanup = mergeObjectMap(run.state.refinement_cleanup, payload.refinement_cleanup);\n }\n if (typeof payload.cleanup_verified === \"boolean\") {\n nextState.cleanup_verified = payload.cleanup_verified;\n }\n if (phase === policy.aggregate_phase) {\n nextState.aggregation_summary = payload.aggregation_summary || payload.summary || payload;\n }\n if (phase === policy.report_phase) {\n nextState.report_written = payload.report_written === true || Boolean(payload.report_path || nextState.report_path);\n }\n if (phase === policy.results_log_phase) {\n nextState.results_log_appended = payload.results_log_appended === true || payload.appended === true || Boolean(payload.log_row);\n }\n if (phase === policy.cleanup_phase) {\n nextState.cleanup_verified = payload.cleanup_verified === true;\n }\n if (phase === policy.self_check_phase) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nfunction isProcessAlive(pid) {\n if (!pid) {\n return false;\n }\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction syncOneAgent(projectRoot, agentState) {\n const nextAgent = { ...agentState };\n const metadataPath = resolveTrackedPath(projectRoot, nextAgent.metadata_file);\n const resultPath = resolveTrackedPath(projectRoot, nextAgent.result_file);\n const metadata = metadataPath && existsSync(metadataPath) ? readJsonFile(metadataPath) : null;\n if (metadata) {\n nextAgent.pid = metadata.pid ?? nextAgent.pid ?? null;\n nextAgent.error = metadata.error ?? nextAgent.error ?? null;\n nextAgent.exit_code = metadata.exit_code ?? nextAgent.exit_code ?? null;\n nextAgent.finished_at = metadata.finished_at ?? nextAgent.finished_at ?? null;\n }\n if (resultPath && fileExists(resultPath)) {\n nextAgent.status = REVIEW_AGENT_STATUSES.RESULT_READY;\n } else if (metadata && (metadata.success === false || metadata.status === REVIEW_AGENT_STATUSES.FAILED)) {\n nextAgent.status = REVIEW_AGENT_STATUSES.FAILED;\n } else if (nextAgent.pid && !isProcessAlive(nextAgent.pid)) {\n nextAgent.status = REVIEW_AGENT_STATUSES.DEAD;\n } else if (!REVIEW_RESOLVED_AGENT_STATUS_SET.has(nextAgent.status)) {\n nextAgent.status = REVIEW_AGENT_STATUSES.LAUNCHED;\n }\n return nextAgent;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.skill || !values.identifier || !values[\"manifest-file\"]) {\n fail(\"start requires --skill, --identifier, and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n skill: values.skill,\n identifier: values.identifier,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && values.skill && !values.identifier) {\n const activeRuns = listActiveRuns(projectRoot, values.skill);\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active runs found. Pass --identifier or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : (values.skill ? loadActiveRun(projectRoot, values.skill, values.identifier) : null);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === \"DONE\" ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const result = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!result.ok) {\n fail(result.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: result.checkpoints[values.phase],\n });\n return;\n }\n\n if (command === \"record-worker-result\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorkerResult(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"register-agent\") {\n if (!values.agent) {\n fail(\"register-agent requires --agent\");\n }\n const { runId } = resolveRun(projectRoot);\n const result = registerAgent(projectRoot, runId, {\n name: values.agent,\n prompt_file: values[\"prompt-file\"] || null,\n result_file: values[\"result-file\"] || null,\n log_file: values[\"log-file\"] || null,\n metadata_file: values[\"metadata-file\"] || null,\n status: REVIEW_AGENT_STATUSES.LAUNCHED,\n });\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"sync-agent\") {\n const { runId, run } = resolveRun(projectRoot);\n const agentNames = values.agent ? [values.agent] : Object.keys(run.state.agents || {});\n if (agentNames.length === 0) {\n output({ ok: true, agents: {}, resolved: true });\n return;\n }\n const nextAgents = { ...run.state.agents };\n for (const agentName of agentNames) {\n if (!nextAgents[agentName]) {\n fail(`Agent not registered: ${agentName}`);\n }\n nextAgents[agentName] = syncOneAgent(projectRoot, nextAgents[agentName]);\n }\n const nextState = saveState(projectRoot, runId, { ...run.state, agents: nextAgents });\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n output({\n ok: true,\n agents: agentNames.reduce((acc, name) => {\n acc[name] = nextState.agents[name];\n return acc;\n }, {}),\n resolved: Object.values(nextState.agents).every(agent => REVIEW_RESOLVED_AGENT_STATUS_SET.has(agent.status)),\n });\n return;\n }\n\n if (command === \"pause\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = Object.keys(payload).length > 0\n ? setPendingDecision(projectRoot, runId, payload, values.reason || \"Decision required\")\n : pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"set-decision\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordDecision(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, \"DONE\");\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, checkpoint, record-worker-result, record-summary, register-agent, sync-agent, advance, pause, set-decision, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":14444,"content_sha256":"196a9e9785df6219fcfeca7ad0508e3890f4e02032f34b542a44b102362bf3f9"},{"filename":"references/scripts/evaluation-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/evaluation-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { REVIEW_RESOLVED_AGENT_STATUS_SET } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nfunction latestPayload(checkpoints, phase) {\n return checkpoints?.[phase]?.payload || {};\n}\n\nfunction configuredPhases(manifest) {\n return Array.isArray(manifest.phase_order) ? manifest.phase_order : [];\n}\n\nfunction nextConfiguredPhase(manifest, currentPhase) {\n const phases = configuredPhases(manifest);\n const index = phases.indexOf(currentPhase);\n if (index === -1) {\n return null;\n }\n if (index === phases.length - 1) {\n return \"DONE\";\n }\n return phases[index + 1];\n}\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction workerResultsCount(state) {\n return Object.keys(state.worker_results || {}).length;\n}\n\nfunction inflightWorkersCount(state) {\n return Object.keys(state.inflight_workers || {}).length;\n}\n\nfunction firstMissingWorker(state) {\n const workerPlan = Array.isArray(state.worker_plan) ? state.worker_plan : [];\n const workerResults = state.worker_results || {};\n return workerPlan.find(worker => {\n const workerKey = typeof worker === \"string\"\n ? worker\n : `${worker.worker}--${worker.identifier}`;\n return !workerResults[workerKey];\n }) || null;\n}\n\nfunction skippedCheckpoint(checkpoints, phase) {\n const payload = latestPayload(checkpoints, phase);\n return payload.skipped_by_mode === true || payload.skipped === true;\n}\n\nfunction allAgentsResolved(state, barrierAgents = []) {\n const agents = state.agents || {};\n const agentNames = barrierAgents.length > 0 ? barrierAgents : Object.keys(agents);\n return agentNames.every(agentName => {\n const agent = agents[agentName];\n if (!agent) {\n return false;\n }\n return REVIEW_RESOLVED_AGENT_STATUS_SET.has(agent.status);\n });\n}\n\nfunction pendingAgentBarrier(manifest, toPhase) {\n const barriers = manifest.phase_policy?.agent_resolve_before || [];\n return barriers.includes(toPhase);\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n if (state.phase === \"DONE\" || state.phase === \"PAUSED\") {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n\n const expectedNext = nextConfiguredPhase(manifest, state.phase);\n if (!expectedNext || expectedNext !== toPhase) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n\n const policy = manifest.phase_policy || {};\n const isDelegatePhase = (policy.delegate_phases || []).includes(state.phase);\n if (isDelegatePhase && Array.isArray(state.worker_plan) && state.worker_plan.length > 0\n && workerResultsCount(state) === 0 && !skippedCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Worker summaries missing for ${state.phase}` };\n }\n\n if (toPhase === policy.aggregate_phase) {\n if (Array.isArray(state.worker_plan) && state.worker_plan.length > 0 && workerResultsCount(state) \u003c state.worker_plan.length) {\n return { ok: false, error: `Not all planned workers produced summaries (${workerResultsCount(state)}/${state.worker_plan.length})` };\n }\n if (inflightWorkersCount(state) > 0) {\n return { ok: false, error: `Aggregate phase blocked by inflight workers (${inflightWorkersCount(state)})` };\n }\n }\n\n if (pendingAgentBarrier(manifest, toPhase) && !allAgentsResolved(state, manifest.expected_agents || [])) {\n return { ok: false, error: `Required agents are unresolved before ${toPhase}` };\n }\n\n if (state.phase === policy.aggregate_phase && !state.aggregation_summary) {\n return { ok: false, error: `Aggregation summary missing for ${state.phase}` };\n }\n\n if (state.phase === policy.report_phase && !state.report_written) {\n return { ok: false, error: `Report checkpoint missing for ${state.phase}` };\n }\n\n if (state.phase === policy.results_log_phase && !state.results_log_appended) {\n return { ok: false, error: `Results log checkpoint missing for ${state.phase}` };\n }\n\n if (state.phase === policy.cleanup_phase && !state.cleanup_verified) {\n return { ok: false, error: `Cleanup verification missing for ${state.phase}` };\n }\n\n if (toPhase === \"DONE\") {\n if (manifest.required_research !== false && !state.research_completed) {\n return { ok: false, error: \"Research evidence must be recorded before completion\" };\n }\n if (!state.cleanup_verified) {\n return { ok: false, error: \"Cleanup must be verified before completion\" };\n }\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.report_written) {\n return { ok: false, error: \"Public report must be written before completion\" };\n }\n if (policy.results_log_phase && !state.results_log_appended) {\n return { ok: false, error: \"Results log must be appended before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n if (!state.summary_recorded) {\n return { ok: false, error: \"Evaluation coordinator summary must be recorded before completion\" };\n }\n }\n\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === \"DONE\") {\n return \"Run complete\";\n }\n if (state.phase === \"PAUSED\") {\n if (state.pending_decision?.resume_to_phase) {\n return `Resolve pending decision and resume ${state.pending_decision.resume_to_phase}`;\n }\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n\n const policy = manifest.phase_policy || {};\n const isDelegatePhase = (policy.delegate_phases || []).includes(state.phase);\n if (isDelegatePhase && Array.isArray(state.worker_plan) && state.worker_plan.length > 0\n && workerResultsCount(state) === 0 && !skippedCheckpoint(checkpoints, state.phase)) {\n return `Record worker summaries before advancing from ${state.phase}`;\n }\n if (Array.isArray(state.worker_plan) && state.worker_plan.length > 0 && workerResultsCount(state) \u003c state.worker_plan.length) {\n const missingWorker = firstMissingWorker(state);\n const missingKey = typeof missingWorker === \"string\"\n ? missingWorker\n : `${missingWorker?.worker}--${missingWorker?.identifier}`;\n const childRun = missingKey ? state.child_runs?.[missingKey] : null;\n if (childRun?.run_id) {\n return `Record ${missingKey} summary from child run ${childRun.run_id} before advancing`;\n }\n return `Record remaining worker summaries (${workerResultsCount(state)}/${state.worker_plan.length}) before advancing`;\n }\n if (inflightWorkersCount(state) > 0) {\n return `Wait for inflight workers to resolve (${inflightWorkersCount(state)} remaining)`;\n }\n if (state.phase === policy.aggregate_phase && !state.aggregation_summary) {\n return `Checkpoint ${state.phase} with aggregation_summary`;\n }\n if (state.phase === policy.report_phase && !state.report_written) {\n return `Checkpoint ${state.phase} with report_written=true`;\n }\n if (state.phase === policy.results_log_phase && !state.results_log_appended) {\n return `Checkpoint ${state.phase} with results_log_appended=true`;\n }\n if (state.phase === policy.cleanup_phase && !state.cleanup_verified) {\n return `Checkpoint ${state.phase} with cleanup_verified=true after evidence review`;\n }\n if (state.phase === policy.self_check_phase && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${state.phase} with pass=true`;\n }\n if (manifest.required_research !== false && !state.research_completed) {\n return \"Record mandatory research evidence before final completion\";\n }\n if (pendingAgentBarrier(manifest, nextConfiguredPhase(manifest, state.phase)) && !allAgentsResolved(state, manifest.expected_agents || [])) {\n return \"Sync agents until every required agent is resolved\";\n }\n if (state.phase === policy.self_check_phase && !state.summary_recorded) {\n return \"Record evaluation coordinator summary before completion\";\n }\n\n const nextPhase = nextConfiguredPhase(manifest, state.phase);\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":9053,"content_sha256":"243d781651658f9acf3663c3d6fc587dc7438f31a1024afcc03f48f3af5bdc54"},{"filename":"references/scripts/evaluation-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/evaluation-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n fileExists,\n readJsonFile,\n resolveTrackedPath,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n buildRuntimeStateSchema,\n evaluationCoordinatorSummarySchema,\n pendingDecisionSchema,\n reviewAgentRecordSchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { writeRuntimeArtifactJson } from \"../../coordinator-runtime/lib/artifacts.mjs\";\nimport { REVIEW_AGENT_STATUSES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\n\nconst phasePolicySchema = {\n type: \"object\",\n additionalProperties: false,\n properties: {\n delegate_phases: {\n type: \"array\",\n items: { type: \"string\" },\n },\n aggregate_phase: { type: \"string\" },\n report_phase: { type: \"string\" },\n results_log_phase: { type: \"string\" },\n cleanup_phase: { type: \"string\" },\n self_check_phase: { type: \"string\" },\n agent_resolve_before: {\n type: \"array\",\n items: { type: \"string\" },\n },\n },\n};\n\nconst evaluationManifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"project_root\", \"phase_order\", \"report_path\", \"created_at\"],\n additionalProperties: false,\n properties: {\n skill: { type: \"string\", minLength: 1 },\n mode: { type: \"string\" },\n identifier: { type: \"string\", minLength: 1 },\n project_root: { type: \"string\", minLength: 1 },\n phase_order: {\n type: \"array\",\n minItems: 1,\n items: { type: \"string\", minLength: 1 },\n },\n phase_policy: phasePolicySchema,\n report_path: { type: \"string\", minLength: 1 },\n results_log_path: { type: \"string\" },\n expected_agents: {\n type: \"array\",\n items: { type: \"string\" },\n },\n required_research: { type: \"boolean\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst evaluationStateSchema = buildRuntimeStateSchema({\n phase_order: {\n type: \"array\",\n minItems: 1,\n items: { type: \"string\", minLength: 1 },\n },\n phase_data: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n worker_plan: {\n type: \"array\",\n },\n worker_results: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n child_runs: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n inflight_workers: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n agents: {\n type: \"object\",\n additionalProperties: reviewAgentRecordSchema,\n },\n background_agent_cleanup: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n refinement_cleanup: {\n type: \"object\",\n additionalProperties: { type: \"object\" },\n },\n cleanup_verified: { type: \"boolean\" },\n research_completed: { type: \"boolean\" },\n aggregation_summary: {\n type: [\"object\", \"null\"],\n },\n report_written: { type: \"boolean\" },\n report_path: { type: [\"string\", \"null\"] },\n results_log_appended: { type: \"boolean\" },\n results_log_path: { type: [\"string\", \"null\"] },\n self_check_passed: { type: \"boolean\" },\n summary_recorded: { type: \"boolean\" },\n summary_artifact_path: { type: [\"string\", \"null\"] },\n summary: { type: [\"object\", \"null\"] },\n}, [\n \"phase_order\",\n \"phase_data\",\n \"worker_plan\",\n \"worker_results\",\n \"child_runs\",\n \"inflight_workers\",\n \"agents\",\n \"background_agent_cleanup\",\n \"refinement_cleanup\",\n \"cleanup_verified\",\n \"research_completed\",\n \"aggregation_summary\",\n \"report_written\",\n \"report_path\",\n \"results_log_appended\",\n \"results_log_path\",\n \"self_check_passed\",\n \"summary_recorded\",\n \"summary_artifact_path\",\n \"summary\",\n]);\n\nfunction normalizePhaseOrder(phaseOrder) {\n const seen = new Set();\n return (phaseOrder || []).filter(phase => {\n if (!phase || seen.has(phase)) {\n return false;\n }\n seen.add(phase);\n return true;\n });\n}\n\nconst evaluationStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"evaluation\", \"runtime\"],\n manifestSchema: evaluationManifestSchema,\n stateSchema: evaluationStateSchema,\n normalizeManifest(manifestInput, projectRoot) {\n const phaseOrder = normalizePhaseOrder(manifestInput.phase_order);\n return {\n skill: manifestInput.skill,\n mode: manifestInput.mode || \"evaluation\",\n identifier: manifestInput.identifier,\n project_root: resolve(projectRoot || process.cwd()),\n phase_order: phaseOrder,\n phase_policy: manifestInput.phase_policy || {},\n report_path: manifestInput.report_path,\n results_log_path: manifestInput.results_log_path || \"docs/project/.evaluation/results_log.md\",\n expected_agents: manifestInput.expected_agents || [],\n required_research: manifestInput.required_research !== false,\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n phase: manifest.phase_order[0],\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n final_result: null,\n phase_order: manifest.phase_order,\n phase_data: {},\n worker_plan: [],\n worker_results: {},\n child_runs: {},\n inflight_workers: {},\n agents: {},\n background_agent_cleanup: {},\n refinement_cleanup: {},\n cleanup_verified: false,\n research_completed: manifest.required_research === false,\n aggregation_summary: null,\n report_written: false,\n report_path: manifest.report_path,\n results_log_appended: false,\n results_log_path: manifest.results_log_path || null,\n self_check_passed: false,\n summary_recorded: false,\n summary_artifact_path: null,\n summary: null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = evaluationStore;\n\nexport function setPendingDecision(projectRoot, runId, pendingDecision, reason = \"Decision required\") {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(pendingDecisionSchema, pendingDecision, \"pending decision\");\n if (!validation.ok) {\n return validation;\n }\n if (pendingDecision.resume_to_phase === \"PAUSED\" || pendingDecision.resume_to_phase === \"DONE\") {\n return { ok: false, error: `Invalid resume_to_phase: ${pendingDecision.resume_to_phase}` };\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n phase: \"PAUSED\",\n paused_reason: reason,\n pending_decision: pendingDecision,\n }), { eventType: \"RUN_PAUSED\" });\n}\n\nexport function recordDecision(projectRoot, runId, decision) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (!run.state.pending_decision) {\n return { ok: false, error: \"No pending decision recorded\" };\n }\n if (run.state.pending_decision.resume_to_phase === \"PAUSED\" || run.state.pending_decision.resume_to_phase === \"DONE\") {\n return { ok: false, error: `Invalid resume_to_phase: ${run.state.pending_decision.resume_to_phase}` };\n }\n const choices = run.state.pending_decision.choices || [];\n if (choices.length > 0 && !choices.includes(decision.selected_choice)) {\n return { ok: false, error: `Invalid selected_choice: ${decision.selected_choice}. Valid: ${choices.join(\", \")}` };\n }\n const nextDecision = {\n kind: run.state.pending_decision.kind,\n selected_choice: decision.selected_choice,\n answered_at: new Date().toISOString(),\n context: decision.context || {},\n };\n return updateState(projectRoot, runId, state => ({\n ...state,\n phase: state.pending_decision.resume_to_phase,\n paused_reason: null,\n pending_decision: null,\n decisions: [...(state.decisions || []), nextDecision],\n }));\n}\n\nexport function registerAgent(projectRoot, runId, agentRecord) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(reviewAgentRecordSchema, agentRecord, \"evaluation agent record\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n agents: {\n ...state.agents,\n [agentRecord.name]: {\n name: agentRecord.name,\n status: agentRecord.status || REVIEW_AGENT_STATUSES.LAUNCHED,\n prompt_file: agentRecord.prompt_file || null,\n result_file: agentRecord.result_file || null,\n log_file: agentRecord.log_file || null,\n metadata_file: agentRecord.metadata_file || null,\n pid: agentRecord.pid || null,\n session_id: agentRecord.session_id || null,\n started_at: agentRecord.started_at || null,\n finished_at: agentRecord.finished_at || null,\n exit_code: agentRecord.exit_code ?? null,\n error: agentRecord.error || null,\n },\n },\n }));\n}\n\nexport function recordWorkerResult(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const hasEnvelope = summary\n && typeof summary === \"object\"\n && typeof summary.schema_version === \"string\"\n && typeof summary.summary_kind === \"string\"\n && typeof summary.run_id === \"string\"\n && typeof summary.identifier === \"string\"\n && typeof summary.producer_skill === \"string\"\n && typeof summary.produced_at === \"string\"\n && summary.payload\n && typeof summary.payload === \"object\";\n if (!hasEnvelope) {\n return { ok: false, error: \"Worker summary must use the shared summary envelope\" };\n }\n const workerResultKey = `${summary.producer_skill}--${summary.identifier}`;\n return updateState(projectRoot, runId, state => {\n const nextInflightWorkers = { ...(state.inflight_workers || {}) };\n delete nextInflightWorkers[workerResultKey];\n return {\n ...state,\n worker_results: {\n ...state.worker_results,\n [workerResultKey]: summary,\n },\n inflight_workers: nextInflightWorkers,\n };\n });\n}\n\nexport function recordSummary(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `Evaluation coordinator summary run_id must match runtime run_id (${runId})` };\n }\n const validation = assertSchema(evaluationCoordinatorSummarySchema, summary, \"evaluation coordinator summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const artifactIdentifier = `${summary.producer_skill}--${summary.identifier}`;\n const artifactPath = writeRuntimeArtifactJson(projectRoot, runId, summary.summary_kind, artifactIdentifier, summary);\n return {\n ...state,\n summary_recorded: true,\n summary_artifact_path: artifactPath,\n summary: {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: artifactPath,\n },\n },\n };\n });\n}\n\nexport {\n fileExists,\n readJsonFile,\n resolveTrackedPath,\n};\n","content_type":"text/javascript","language":"javascript","size":12721,"content_sha256":"89d68be3cb6dd9d706837c2ef98e465b2e9b280498a7be6a5323faaf23137e71"},{"filename":"references/scripts/optimization-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/optimization-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordCycle,\n recordLoopHealth,\n recordSummary,\n recordWorkerResult,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport {\n computeResumeAction,\n validateTransition,\n} from \"./lib/guards.mjs\";\nimport {\n OPTIMIZATION_CHECKPOINT_STATUSES,\n OPTIMIZATION_GATE_VERDICTS,\n OPTIMIZATION_VALIDATION_VERDICTS,\n} from \"../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n slug: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n resolve: { type: \"boolean\", default: false },\n worker: { type: \"string\" },\n scope: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-810\", values[\"run-id\"], values.slug);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-810\");\n if (activeRuns.length > 1 && !values.slug) {\n fail(\"Multiple active ln-810 runs found. Pass --slug or --run-id.\");\n }\n fail(\"No active ln-810 run found. Pass --slug or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction markPhase(state, phase, status, extra = {}) {\n return {\n ...state.phases,\n [phase]: {\n ...(state.phases?.[phase] || {}),\n status,\n ts: new Date().toISOString(),\n ...extra,\n },\n };\n}\n\nfunction childRunKey(childRun) {\n const identifier = childRun?.identifier || childRun?.phase_context || childRun?.run_id || \"child\";\n return `${childRun?.worker || \"worker\"}--${identifier}`;\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = {\n ...state,\n phases: markPhase(state, phase, payload.phase_status || OPTIMIZATION_CHECKPOINT_STATUSES.COMPLETED),\n };\n\n if ([PHASES.PROFILE, PHASES.RESEARCH, PHASES.VALIDATE_PLAN, PHASES.EXECUTE].includes(phase)\n && payload.child_run && typeof payload.child_run === \"object\") {\n nextState.child_runs = {\n ...(nextState.child_runs || {}),\n [childRunKey(payload.child_run)]: payload.child_run,\n };\n }\n\n if (phase === PHASES.PARSE_INPUT) {\n nextState.target = payload.target || nextState.target;\n nextState.target_metric = payload.target_metric || nextState.target_metric;\n }\n\n if (phase === PHASES.WRONG_TOOL_GATE) {\n nextState.final_result = payload.gate_verdict === OPTIMIZATION_GATE_VERDICTS.BLOCK ? (payload.final_result || nextState.final_result) : nextState.final_result;\n nextState.stop_reason = payload.gate_verdict === OPTIMIZATION_GATE_VERDICTS.BLOCK ? (payload.stop_reason || nextState.stop_reason) : nextState.stop_reason;\n }\n\n if (phase === PHASES.SET_TARGET) {\n nextState.target_metric = payload.target_metric || nextState.target_metric;\n }\n\n if (phase === PHASES.WRITE_CONTEXT) {\n nextState.context_file = payload.context_file || nextState.context_file;\n }\n\n if (phase === PHASES.VALIDATE_PLAN && payload.validation_verdict === OPTIMIZATION_VALIDATION_VERDICTS.NO_GO) {\n nextState.paused_reason = payload.paused_reason || nextState.paused_reason;\n }\n\n if (phase === PHASES.CYCLE_BOUNDARY) {\n nextState.stop_reason = payload.stop_reason || nextState.stop_reason;\n nextState.final_result = payload.final_result || nextState.final_result;\n nextState.current_cycle = Number(payload.next_cycle || nextState.current_cycle);\n }\n\n if (phase === PHASES.REPORT) {\n nextState.final_result = payload.final_result || nextState.final_result;\n nextState.report_ready = payload.report_ready === true;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.slug || !values[\"manifest-file\"]) {\n fail(\"start requires --slug and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n slug: values.slug,\n identifier: values.slug,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.slug) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-810\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-810 runs found. Pass --slug or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-810\", values.slug);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n if (run.state.phase === PHASES.PAUSED && values.resolve) {\n const resumed = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n paused_reason: null,\n });\n if (resumed?.ok === false) {\n outputGuardFailure(output, resumed);\n }\n outputRuntimeState(output, run, resumed, { resumed_from: \"PAUSED\" });\n return;\n }\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-worker-result\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorkerResult(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-cycle\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordCycle(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-loop-health\") {\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const result = recordLoopHealth(projectRoot, runId, values.scope || `cycle_${run.state.current_cycle || 1}`, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const { runId } = resolveRun(projectRoot);\n const result = pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-worker-result, record-summary, record-cycle, record-loop-health, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":10435,"content_sha256":"cc82803448cabc9c7b8d59e8ebaf95443070d6b27094cc4e7dae253d413a0370"},{"filename":"references/scripts/optimization-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/optimization-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n OPTIMIZATION_CHECKPOINT_STATUSES,\n OPTIMIZATION_EXECUTION_ALLOWED_VERDICT_LIST,\n OPTIMIZATION_GATE_VERDICTS,\n OPTIMIZATION_GATE_VERDICT_LIST,\n OPTIMIZATION_VALIDATION_VERDICTS,\n} from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.PREFLIGHT, new Set([PHASES.PARSE_INPUT])],\n [PHASES.PARSE_INPUT, new Set([PHASES.PROFILE])],\n [PHASES.PROFILE, new Set([PHASES.WRONG_TOOL_GATE])],\n [PHASES.WRONG_TOOL_GATE, new Set([PHASES.RESEARCH, PHASES.AGGREGATE])],\n [PHASES.RESEARCH, new Set([PHASES.SET_TARGET, PHASES.AGGREGATE])],\n [PHASES.SET_TARGET, new Set([PHASES.WRITE_CONTEXT])],\n [PHASES.WRITE_CONTEXT, new Set([PHASES.VALIDATE_PLAN])],\n [PHASES.VALIDATE_PLAN, new Set([PHASES.EXECUTE])],\n [PHASES.EXECUTE, new Set([PHASES.CYCLE_BOUNDARY])],\n [PHASES.CYCLE_BOUNDARY, new Set([PHASES.PROFILE, PHASES.AGGREGATE])],\n [PHASES.AGGREGATE, new Set([PHASES.REPORT])],\n [PHASES.REPORT, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction latestPayload(checkpoints, phase) {\n return checkpoints?.[phase]?.payload || {};\n}\n\nfunction childRunFromCheckpoint(checkpoints, phase) {\n const childRun = latestPayload(checkpoints, phase).child_run;\n return childRun && typeof childRun === \"object\" ? childRun : null;\n}\n\nfunction workerResultKey(worker, identifier) {\n return `${worker}--${identifier}`;\n}\n\nfunction hasWorkerSummary(state, worker, identifier = null) {\n if (identifier) {\n return Boolean(state.worker_results?.[workerResultKey(worker, identifier)]);\n }\n return Object.values(state.worker_results || {}).some(summary => summary?.producer_skill === worker);\n}\n\nfunction childRunMessage(checkpoints, state, phase, worker, suffix) {\n const childRun = childRunFromCheckpoint(checkpoints, phase);\n if (!childRun?.run_id || childRun.worker !== worker) {\n return null;\n }\n return `Check child runtime ${childRun.run_id} for ${worker}${suffix}`;\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n\n if (toPhase === PHASES.RESEARCH) {\n const gateVerdict = latestPayload(checkpoints, PHASES.WRONG_TOOL_GATE).gate_verdict;\n if (!OPTIMIZATION_GATE_VERDICT_LIST.filter(value => value !== OPTIMIZATION_GATE_VERDICTS.BLOCK).includes(gateVerdict || \"\")) {\n return { ok: false, error: \"Wrong Tool Gate does not allow research\" };\n }\n }\n\n if (toPhase === PHASES.WRONG_TOOL_GATE) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.PROFILE);\n const childIdentifier = childRun?.worker === \"ln-811\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-811\", childIdentifier)) {\n return { ok: false, error: \"ln-811 summary missing\" };\n }\n }\n\n if (toPhase === PHASES.AGGREGATE) {\n if (state.phase === PHASES.WRONG_TOOL_GATE) {\n const gateVerdict = latestPayload(checkpoints, PHASES.WRONG_TOOL_GATE).gate_verdict;\n if (gateVerdict !== OPTIMIZATION_GATE_VERDICTS.BLOCK) {\n return { ok: false, error: \"Phase 3 can jump to aggregate only on BLOCK\" };\n }\n }\n if (state.phase === PHASES.RESEARCH) {\n const payload = latestPayload(checkpoints, PHASES.RESEARCH);\n if (Number(payload.hypotheses_count ?? 1) > 0) {\n return { ok: false, error: \"Phase 4 can jump to aggregate only when no hypotheses remain\" };\n }\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.RESEARCH);\n const childIdentifier = childRun?.worker === \"ln-812\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-812\", childIdentifier)) {\n return { ok: false, error: \"ln-812 summary missing\" };\n }\n }\n if (state.phase === PHASES.CYCLE_BOUNDARY && !state.stop_reason) {\n return { ok: false, error: \"Cycle boundary missing stop reason\" };\n }\n }\n\n if (toPhase === PHASES.SET_TARGET) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.RESEARCH);\n const childIdentifier = childRun?.worker === \"ln-812\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-812\", childIdentifier)) {\n return { ok: false, error: \"ln-812 summary missing\" };\n }\n }\n\n if (toPhase === PHASES.VALIDATE_PLAN && !state.context_file) {\n return { ok: false, error: \"Context file not recorded\" };\n }\n\n if (toPhase === PHASES.EXECUTE) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.VALIDATE_PLAN);\n const childIdentifier = childRun?.worker === \"ln-813\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-813\", childIdentifier)) {\n return { ok: false, error: \"ln-813 summary missing\" };\n }\n const verdict = latestPayload(checkpoints, PHASES.VALIDATE_PLAN).validation_verdict;\n if (!OPTIMIZATION_EXECUTION_ALLOWED_VERDICT_LIST.includes(verdict || \"\")) {\n return { ok: false, error: \"Validation verdict does not allow execution\" };\n }\n }\n\n if (toPhase === PHASES.CYCLE_BOUNDARY) {\n const payload = latestPayload(checkpoints, PHASES.EXECUTE);\n const skippedByMode = payload.status === OPTIMIZATION_CHECKPOINT_STATUSES.SKIPPED_BY_MODE && state.execution_mode === \"plan_only\";\n if (!skippedByMode) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.EXECUTE);\n const childIdentifier = childRun?.worker === \"ln-814\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-814\", childIdentifier)) {\n return { ok: false, error: \"ln-814 summary missing\" };\n }\n }\n }\n\n if (toPhase === PHASES.PROFILE && state.phase === PHASES.CYCLE_BOUNDARY && state.stop_reason) {\n return { ok: false, error: \"Stop reason recorded; cannot continue to another cycle\" };\n }\n\n if (toPhase === PHASES.DONE) {\n if (!state.report_ready) {\n return { ok: false, error: \"Final report checkpoint missing\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n if (!state.summary_recorded) {\n return { ok: false, error: \"Coordinator summary not recorded\" };\n }\n }\n\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.PROFILE) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.PROFILE);\n const childIdentifier = childRun?.worker === \"ln-811\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-811\", childIdentifier)) {\n return childRunMessage(checkpoints, state, PHASES.PROFILE, \"ln-811\", \" or record its worker summary before Wrong Tool Gate\")\n || \"Record ln-811 worker summary before Wrong Tool Gate\";\n }\n }\n if (state.phase === PHASES.RESEARCH) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.RESEARCH);\n const childIdentifier = childRun?.worker === \"ln-812\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-812\", childIdentifier)) {\n return childRunMessage(checkpoints, state, PHASES.RESEARCH, \"ln-812\", \" or record its worker summary before continuing research\")\n || \"Record ln-812 worker summary before continuing research\";\n }\n }\n if (state.phase === PHASES.WRITE_CONTEXT && !state.context_file) {\n return \"Write optimization context file and checkpoint PHASE_6_WRITE_CONTEXT\";\n }\n if (state.phase === PHASES.VALIDATE_PLAN) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.VALIDATE_PLAN);\n const childIdentifier = childRun?.worker === \"ln-813\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-813\", childIdentifier)) {\n return childRunMessage(checkpoints, state, PHASES.VALIDATE_PLAN, \"ln-813\", \" or record its worker summary before execution\")\n || \"Record ln-813 worker summary before execution\";\n }\n const verdict = latestPayload(checkpoints, PHASES.VALIDATE_PLAN).validation_verdict;\n if (verdict === OPTIMIZATION_VALIDATION_VERDICTS.NO_GO) {\n return \"Present NO_GO issues to the user, then resolve or pause\";\n }\n }\n if (state.phase === PHASES.EXECUTE && state.execution_mode === \"plan_only\") {\n return \"Checkpoint PHASE_8_EXECUTE as skipped_by_mode, then advance to PHASE_9_CYCLE_BOUNDARY\";\n }\n if (state.phase === PHASES.EXECUTE) {\n const childRun = childRunFromCheckpoint(checkpoints, PHASES.EXECUTE);\n const childIdentifier = childRun?.worker === \"ln-814\" ? childRun.identifier : null;\n if (!hasWorkerSummary(state, \"ln-814\", childIdentifier)) {\n return childRunMessage(checkpoints, state, PHASES.EXECUTE, \"ln-814\", \" or record its worker summary before cycle boundary\")\n || \"Record ln-814 worker summary before cycle boundary\";\n }\n }\n if (state.phase === PHASES.CYCLE_BOUNDARY) {\n if (state.stop_reason) {\n return \"Advance to PHASE_10_AGGREGATE\";\n }\n return `Advance to ${PHASES.PROFILE} for cycle ${Number(state.current_cycle || 1) + 1}`;\n }\n if (state.phase === PHASES.REPORT && !state.report_ready) {\n return \"Write final report checkpoint for PHASE_11_REPORT\";\n }\n if (state.phase === PHASES.REPORT && !state.summary_recorded) {\n return \"Record optimization coordinator summary before completion\";\n }\n\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":10831,"content_sha256":"1e6777b9cd79d140d0ea13074b200300a3b9c924a8d0f0a6167ce70274579e3d"},{"filename":"references/scripts/optimization-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/optimization-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n PREFLIGHT: \"PHASE_0_PREFLIGHT\",\n PARSE_INPUT: \"PHASE_1_PARSE_INPUT\",\n PROFILE: \"PHASE_2_PROFILE\",\n WRONG_TOOL_GATE: \"PHASE_3_WRONG_TOOL_GATE\",\n RESEARCH: \"PHASE_4_RESEARCH\",\n SET_TARGET: \"PHASE_5_SET_TARGET\",\n WRITE_CONTEXT: \"PHASE_6_WRITE_CONTEXT\",\n VALIDATE_PLAN: \"PHASE_7_VALIDATE_PLAN\",\n EXECUTE: \"PHASE_8_EXECUTE\",\n CYCLE_BOUNDARY: \"PHASE_9_CYCLE_BOUNDARY\",\n AGGREGATE: \"PHASE_10_AGGREGATE\",\n REPORT: \"PHASE_11_REPORT\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":818,"content_sha256":"3041ce9834196e34da55e49254afc4601d6903181dca4dde076091144b6c5ebc"},{"filename":"references/scripts/optimization-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/optimization-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n optimizationCycleSchema,\n optimizationCoordinatorSummarySchema,\n optimizationWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { writeRuntimeArtifactJson } from \"../../coordinator-runtime/lib/artifacts.mjs\";\nimport { updateLoopHealthMap } from \"../../coordinator-runtime/lib/loop-health.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst optimizationManifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"slug\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n slug: { type: \"string\" },\n target: { type: \"string\" },\n observed_metric: {},\n target_metric: {},\n execution_mode: { type: \"string\" },\n cycle_config: { type: \"object\" },\n project_root: { type: \"string\" },\n context_file: {},\n service_topology: {},\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst optimizationStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"optimization\", \"runtime\"],\n manifestSchema: optimizationManifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-810\",\n mode: manifestInput.mode || \"optimization\",\n identifier: manifestInput.slug || manifestInput.identifier,\n slug: manifestInput.slug || manifestInput.identifier,\n target: manifestInput.target,\n observed_metric: manifestInput.observed_metric || null,\n target_metric: manifestInput.target_metric || null,\n execution_mode: manifestInput.execution_mode || \"execute\",\n cycle_config: manifestInput.cycle_config || { max_cycles: 3, plateau_threshold: 5 },\n project_root: resolve(projectRoot || process.cwd()),\n context_file: manifestInput.context_file || null,\n service_topology: manifestInput.service_topology || null,\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n slug: manifest.slug,\n target: manifest.target,\n phase: PHASES.PREFLIGHT,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n execution_mode: manifest.execution_mode,\n cycle_config: manifest.cycle_config,\n current_cycle: 1,\n cycles: [],\n phases: {},\n worker_results: {},\n child_runs: {},\n loop_health: {\n cycles: {},\n },\n stop_reason: null,\n target_metric: manifest.target_metric,\n context_file: manifest.context_file,\n final_result: null,\n report_ready: false,\n summary_recorded: false,\n summary_artifact_path: null,\n summary: null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = optimizationStore;\n\nfunction childRunKey(childRun) {\n const identifier = childRun?.identifier || childRun?.phase_context || childRun?.run_id || \"child\";\n return `${childRun?.worker || \"worker\"}--${identifier}`;\n}\n\nfunction workerResultKey(summary) {\n return `${summary.producer_skill}--${summary.identifier}`;\n}\n\nexport function recordWorkerResult(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(optimizationWorkerSummarySchema, summary, \"optimization worker summary\");\n if (!validation.ok) {\n return validation;\n }\n if (summary?.run_id !== runId && !run.state.child_runs?.[childRunKey({\n worker: summary.producer_skill,\n identifier: summary.identifier,\n run_id: summary.run_id,\n })]) {\n return { ok: false, error: `Optimization worker summary must belong to runtime ${runId} or a recorded child run` };\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n worker_results: {\n ...state.worker_results,\n [workerResultKey(summary)]: summary,\n },\n }));\n}\n\nexport function recordSummary(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `Optimization coordinator summary run_id must match runtime run_id (${runId})` };\n }\n const validation = assertSchema(optimizationCoordinatorSummarySchema, summary, \"optimization coordinator summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const artifactIdentifier = `${summary.producer_skill}--${summary.identifier}`;\n const artifactPath = writeRuntimeArtifactJson(projectRoot, runId, summary.summary_kind, artifactIdentifier, summary);\n return {\n ...state,\n summary_recorded: true,\n summary_artifact_path: artifactPath,\n summary: {\n ...summary,\n payload: {\n ...summary.payload,\n summary_artifact_path: artifactPath,\n },\n },\n };\n });\n}\n\nexport function recordCycle(projectRoot, runId, cycleRecord) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const normalizedCycle = {\n ...cycleRecord,\n cycle: Number(cycleRecord.cycle || run.state.current_cycle || 1),\n recorded_at: cycleRecord.recorded_at || new Date().toISOString(),\n };\n const validation = assertSchema(optimizationCycleSchema, normalizedCycle, \"optimization cycle record\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const remaining = (state.cycles || []).filter(entry => entry.cycle !== normalizedCycle.cycle);\n const nextCurrentCycle = normalizedCycle.next_cycle || state.current_cycle;\n return {\n ...state,\n current_cycle: nextCurrentCycle,\n cycles: [...remaining, normalizedCycle].sort((left, right) => left.cycle - right.cycle),\n stop_reason: normalizedCycle.stop_reason || state.stop_reason,\n final_result: normalizedCycle.final_result || state.final_result,\n };\n });\n}\n\nexport function recordLoopHealth(projectRoot, runId, scopeId, signal) {\n let recordedEntry = null;\n let pauseRecommendation = null;\n const key = scopeId || \"cycle\";\n const result = updateState(projectRoot, runId, state => {\n const currentLoopHealth = state.loop_health || {};\n const updated = updateLoopHealthMap(currentLoopHealth.cycles || {}, key, signal);\n recordedEntry = updated.entry;\n pauseRecommendation = updated.pause;\n const pauseState = updated.pause.pause\n ? {\n phase: PHASES.PAUSED,\n paused_reason: `${key} loop health pause - ${updated.pause.reason}`,\n pending_decision: null,\n stop_reason: updated.pause.category || state.stop_reason,\n }\n : {};\n return {\n ...state,\n ...pauseState,\n loop_health: {\n cycles: updated.map,\n },\n };\n }, { eventType: \"LOOP_HEALTH_RECORDED\" });\n if (!result.ok) {\n return result;\n }\n return {\n ok: true,\n state: result.state,\n loop_health: recordedEntry,\n pause: pauseRecommendation,\n };\n}\n\nexport {\n readJsonFile,\n};\n","content_type":"text/javascript","language":"javascript","size":8536,"content_sha256":"43744db56f805a6f05faf7b78a6778af89eb0aec54e432295387426a0061204c"},{"filename":"references/scripts/planning-runtime/lib/cli.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/planning-runtime/lib/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n} from \"../../coordinator-runtime/lib/cli-helpers.mjs\";\n\nexport function resolvePlanningRunOrFail({\n projectRoot,\n skill,\n runId,\n identifier,\n identifierFlag,\n listActiveRuns,\n resolveRunId,\n loadRun,\n fail,\n}) {\n const resolvedRunId = resolveRunId(projectRoot, skill, runId, identifier);\n if (!resolvedRunId) {\n const activeRuns = listActiveRuns(projectRoot, skill);\n if (activeRuns.length > 1 && !identifier) {\n fail(`Multiple active ${skill} runs found. Pass --${identifierFlag} or --run-id.`);\n }\n fail(`No active ${skill} run found. Pass --${identifierFlag} or --run-id.`);\n }\n const run = loadRun(projectRoot, resolvedRunId);\n if (!run) {\n fail(`Run not found: ${resolvedRunId}`);\n }\n return { runId: resolvedRunId, run };\n}\n\nexport function loadPlanningStatusRun({\n projectRoot,\n skill,\n runId,\n identifier,\n identifierFlag,\n listActiveRuns,\n loadRun,\n loadActiveRun,\n output,\n}) {\n if (!runId && !identifier) {\n const activeRuns = listActiveRuns(projectRoot, skill);\n if (activeRuns.length > 1) {\n outputGuardFailure(output, { error: `Multiple active ${skill} runs found. Pass --${identifierFlag} or --run-id.` });\n }\n }\n return runId\n ? loadRun(projectRoot, runId)\n : loadActiveRun(projectRoot, skill, identifier);\n}\n\nexport function outputPlanningStatus(projectRoot, run, runtimePaths, computeResumeAction, output) {\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n}\n\nexport function advancePlanningRun(projectRoot, runId, run, toPhase, validateTransition, saveState, donePhase, output) {\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, toPhase);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: toPhase,\n complete: toPhase === donePhase ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n}\n\nexport function checkpointPlanningRun(projectRoot, runId, run, phase, payload, checkpointPhase, saveState, applyCheckpointToState, fail, output) {\n const checkpointed = checkpointPhase(projectRoot, runId, phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, phase, payload));\n if (nextState?.ok === false) {\n fail(nextState.error);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n}\n\nexport function pausePlanningRun(projectRoot, runId, payload, reason, pauseRun, setPendingDecision, fail, output) {\n const result = Object.keys(payload).length > 0\n ? setPendingDecision(projectRoot, runId, payload, reason || \"Decision required\")\n : pauseRun(projectRoot, runId, reason || \"Paused\");\n if (!result.ok) {\n fail(result.error);\n }\n output(result);\n}\n\nexport function completePlanningRun(projectRoot, runId, run, validateTransition, completeRun, donePhase, fail, output) {\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, donePhase);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n fail(result.error);\n }\n output(result);\n}\n\nexport {\n outputInactiveRuntime,\n};\n","content_type":"text/javascript","language":"javascript","size":3949,"content_sha256":"7907a68b38b2ae9386437250e432306e358d2016ac52447ea4c66b548716a9b5"},{"filename":"references/scripts/planning-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/planning-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nexport function hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nexport function hasChoice(decisions, choice) {\n return (decisions || []).some(entry => entry.selected_choice === choice);\n}\n\nexport function validatePlanningBaseTransition(state, checkpoints, toPhase, allowedTransitions) {\n const allowed = allowedTransitions.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n if (state.pending_decision) {\n return { ok: false, error: \"Pending decision must be resolved before advancing\" };\n }\n return { ok: true };\n}\n\nexport function computePlanningBaseResumeAction(state, checkpoints, allowedTransitions, pausedPhase, donePhase) {\n if (state.complete || state.phase === donePhase) {\n return \"Run complete\";\n }\n if (state.phase === pausedPhase) {\n if (state.pending_decision) {\n return `Resolve pending decision: ${state.pending_decision.kind}`;\n }\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n const nextPhase = Array.from(ALLOWED_OR_EMPTY(allowedTransitions, state.phase))[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n\nfunction ALLOWED_OR_EMPTY(allowedTransitions, phase) {\n return allowedTransitions.get(phase) || [];\n}\n","content_type":"text/javascript","language":"javascript","size":1818,"content_sha256":"87481a136e904989039af61968581cef93a67919f7b1b840c6c05d5eb32ff441"},{"filename":"references/scripts/planning-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/planning-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { createRuntimeStore, readJsonFile } from \"../../coordinator-runtime/lib/core.mjs\";\nimport { pendingDecisionSchema } from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { writeRuntimeArtifactJson } from \"../../coordinator-runtime/lib/artifacts.mjs\";\n\nconst BASE_MANIFEST_PROPERTIES = {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n task_provider: { type: \"string\" },\n auto_approve: { type: \"boolean\" },\n project_root: { type: \"string\" },\n created_at: { type: \"string\", format: \"date-time\" },\n};\n\nexport function createPlanningManifestSchema(identifierField) {\n return {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"project_root\", \"created_at\"],\n properties: {\n ...BASE_MANIFEST_PROPERTIES,\n [identifierField]: { type: \"string\" },\n },\n };\n}\n\nexport function createPlanningState(manifest, runId, phase, extraState = {}) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n phase,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n final_result: null,\n self_check_passed: false,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n ...extraState,\n };\n}\n\nexport function recordCoordinatorSummaryState({\n projectRoot,\n runId,\n summary,\n schema,\n label,\n stateKey,\n loadRun,\n updateState,\n artifactIdentifier,\n reduceState,\n}) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `${label} run_id must match runtime run_id (${runId})` };\n }\n const validation = assertSchema(schema, summary, label);\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const nextArtifactIdentifier = typeof artifactIdentifier === \"function\"\n ? artifactIdentifier(summary, state)\n : (artifactIdentifier || summary.identifier);\n const artifactPath = writeRuntimeArtifactJson(\n projectRoot,\n runId,\n summary.summary_kind,\n nextArtifactIdentifier,\n {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: summary.payload.artifact_path || null,\n },\n },\n );\n const reducedSummary = {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: artifactPath,\n },\n };\n const nextState = {\n ...state,\n [stateKey]: reducedSummary,\n };\n return typeof reduceState === \"function\"\n ? reduceState(nextState, reducedSummary, state)\n : nextState;\n });\n}\n\nexport function createPlanningRuntimeStore({\n baseRootParts,\n manifestSchema,\n normalizeManifest,\n defaultState,\n pausedPhase,\n resumablePhases,\n}) {\n const store = createRuntimeStore({\n baseRootParts,\n manifestSchema,\n normalizeManifest,\n defaultState,\n });\n\n function setPendingDecision(projectRoot, runId, pendingDecision, reason = \"Decision required\") {\n const run = store.loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(pendingDecisionSchema, pendingDecision, \"pending decision\");\n if (!validation.ok) {\n return validation;\n }\n if (resumablePhases && !resumablePhases.has(pendingDecision.resume_to_phase)) {\n return { ok: false, error: `Invalid resume_to_phase: ${pendingDecision.resume_to_phase}` };\n }\n return store.updateState(projectRoot, runId, state => ({\n ...state,\n phase: pausedPhase,\n paused_reason: reason,\n pending_decision: pendingDecision,\n }), { eventType: \"RUN_PAUSED\" });\n }\n\n function recordDecision(projectRoot, runId, decision) {\n const run = store.loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (!run.state.pending_decision) {\n return { ok: false, error: \"No pending decision recorded\" };\n }\n if (resumablePhases && !resumablePhases.has(run.state.pending_decision.resume_to_phase)) {\n return { ok: false, error: `Invalid resume_to_phase: ${run.state.pending_decision.resume_to_phase}` };\n }\n const choices = run.state.pending_decision.choices || [];\n if (choices.length > 0 && !choices.includes(decision.selected_choice)) {\n return { ok: false, error: `Invalid selected_choice: ${decision.selected_choice}. Valid: ${choices.join(\", \")}` };\n }\n const nextDecision = {\n kind: run.state.pending_decision.kind,\n selected_choice: decision.selected_choice,\n answered_at: new Date().toISOString(),\n context: decision.context || {},\n };\n return store.updateState(projectRoot, runId, state => ({\n ...state,\n phase: state.pending_decision.resume_to_phase,\n paused_reason: null,\n pending_decision: null,\n decisions: [...(state.decisions || []), nextDecision],\n }));\n }\n\n function recordSummary(projectRoot, runId, summary, schema, label, reducer) {\n const run = store.loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(schema, summary, label);\n if (!validation.ok) {\n return validation;\n }\n return store.updateState(projectRoot, runId, state => reducer(state, summary));\n }\n\n function recordCoordinatorSummary(projectRoot, runId, summary, schema, label, stateKey, options = {}) {\n return recordCoordinatorSummaryState({\n projectRoot,\n runId,\n summary,\n schema,\n label,\n stateKey,\n loadRun: store.loadRun,\n updateState: store.updateState,\n artifactIdentifier: options.artifactIdentifier,\n reduceState: options.reduceState,\n });\n }\n\n return {\n ...store,\n setPendingDecision,\n recordDecision,\n recordSummary,\n recordCoordinatorSummary,\n readJsonFile,\n };\n}\n","content_type":"text/javascript","language":"javascript","size":6938,"content_sha256":"faefae1ce85c346e39ce9d9708a624b03aed0ee518275e28748ae90acd8ea83a"},{"filename":"references/scripts/quality-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/quality-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordWorker,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputGuardFailure,\n outputInactiveRuntime,\n outputJson as output,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n story: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n resolve: { type: \"boolean\", default: false },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-510\", values[\"run-id\"], values.story);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-510\");\n if (activeRuns.length > 1 && !values.story) {\n fail(\"Multiple active ln-510 runs found. Pass --story or --run-id.\");\n }\n fail(\"No active ln-510 run found. Pass --story or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n if ([PHASES.CODE_QUALITY, PHASES.CLEANUP, PHASES.REGRESSION, PHASES.LOG_ANALYSIS].includes(phase)\n && payload.child_run?.worker) {\n nextState.child_runs = {\n ...(nextState.child_runs || {}),\n [payload.child_run.worker]: payload.child_run,\n };\n }\n if (phase === PHASES.FINALIZE) {\n nextState.quality_score = payload.quality_score ?? nextState.quality_score;\n nextState.quality_verdict = payload.quality_verdict || nextState.quality_verdict;\n nextState.aggregated_issues = payload.aggregated_issues || nextState.aggregated_issues;\n nextState.final_result = payload.final_result || payload.quality_verdict || nextState.final_result;\n }\n if (phase === PHASES.AGENT_REVIEW) {\n nextState.review_summary = payload.review_summary || payload;\n }\n if (phase === PHASES.CRITERIA) {\n nextState.criteria_summary = payload.criteria_summary || payload;\n }\n if (phase === PHASES.LINTERS) {\n nextState.linters_summary = payload.linters_summary || payload;\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.story || !values[\"manifest-file\"]) {\n fail(\"start requires --story and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n story_id: values.story,\n identifier: values.story,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.story) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-510\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-510 runs found. Pass --story or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-510\", values.story);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n if (run.state.phase === PHASES.PAUSED && values.resolve) {\n const resumed = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n paused_reason: null,\n });\n if (resumed?.ok === false) {\n outputGuardFailure(output, resumed);\n }\n outputRuntimeState(output, run, resumed, { resumed_from: \"PAUSED\" });\n return;\n }\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-worker\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorker(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const { runId } = resolveRun(projectRoot);\n const result = pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-worker, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":7803,"content_sha256":"c8bccac60cb1f89d48be06f1f19ce448edfd78fed985321387ec15ebd27e4f90"},{"filename":"references/scripts/quality-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/quality-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.CODE_QUALITY])],\n [PHASES.CODE_QUALITY, new Set([PHASES.CLEANUP])],\n [PHASES.CLEANUP, new Set([PHASES.AGENT_REVIEW])],\n [PHASES.AGENT_REVIEW, new Set([PHASES.CRITERIA])],\n [PHASES.CRITERIA, new Set([PHASES.LINTERS])],\n [PHASES.LINTERS, new Set([PHASES.REGRESSION])],\n [PHASES.REGRESSION, new Set([PHASES.LOG_ANALYSIS])],\n [PHASES.LOG_ANALYSIS, new Set([PHASES.FINALIZE])],\n [PHASES.FINALIZE, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction hasWorker(state, worker) {\n return Boolean(state.worker_results?.[worker]);\n}\n\nfunction childRunMessage(state, worker, suffix) {\n const childRun = state.child_runs?.[worker];\n if (!childRun?.run_id) {\n return null;\n }\n return `Check child runtime ${childRun.run_id} for ${worker}${suffix}`;\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n if (toPhase === PHASES.CLEANUP && !hasWorker(state, \"ln-511\")) {\n return { ok: false, error: \"ln-511 summary missing\" };\n }\n if (toPhase === PHASES.AGENT_REVIEW && !hasWorker(state, \"ln-512\")) {\n return { ok: false, error: \"ln-512 summary missing\" };\n }\n if (toPhase === PHASES.LOG_ANALYSIS && !hasWorker(state, \"ln-513\")) {\n return { ok: false, error: \"ln-513 summary missing\" };\n }\n if (toPhase === PHASES.FINALIZE && !hasWorker(state, \"ln-514\")) {\n return { ok: false, error: \"ln-514 summary missing\" };\n }\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n }\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.CODE_QUALITY && !hasWorker(state, \"ln-511\")) {\n return childRunMessage(state, \"ln-511\", \" or record its worker summary before cleanup\")\n || \"Record ln-511 worker summary before cleanup\";\n }\n if (state.phase === PHASES.CLEANUP && !hasWorker(state, \"ln-512\")) {\n return childRunMessage(state, \"ln-512\", \" or record its worker summary before agent review\")\n || \"Record ln-512 worker summary before agent review\";\n }\n if (state.phase === PHASES.REGRESSION && !hasWorker(state, \"ln-513\")) {\n return childRunMessage(state, \"ln-513\", \" or record its worker summary before log analysis\")\n || \"Record ln-513 worker summary before log analysis\";\n }\n if (state.phase === PHASES.LOG_ANALYSIS && !hasWorker(state, \"ln-514\")) {\n return childRunMessage(state, \"ln-514\", \" or record its worker summary before finalization\")\n || \"Record ln-514 worker summary before finalization\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":4324,"content_sha256":"000ee64b962965cce41c5334419068f9c23247241f14a948a41d07ac2229829b"},{"filename":"references/scripts/quality-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/quality-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n CODE_QUALITY: \"PHASE_2_CODE_QUALITY\",\n CLEANUP: \"PHASE_3_CLEANUP\",\n AGENT_REVIEW: \"PHASE_4_AGENT_REVIEW\",\n CRITERIA: \"PHASE_5_CRITERIA\",\n LINTERS: \"PHASE_6_LINTERS\",\n REGRESSION: \"PHASE_7_REGRESSION\",\n LOG_ANALYSIS: \"PHASE_8_LOG_ANALYSIS\",\n FINALIZE: \"PHASE_9_FINALIZE\",\n SELF_CHECK: \"PHASE_10_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":752,"content_sha256":"34c816ff0c7aa64e7e5066a8e5a510818a3c32699f2e19cfcec8857575fc27c8"},{"filename":"references/scripts/quality-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/quality-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n qualityWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst manifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"story_id\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n story_id: { type: \"string\" },\n fast_track: { type: \"boolean\" },\n project_root: { type: \"string\" },\n task_provider: { type: \"string\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst qualityStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"quality\", \"runtime\"],\n manifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-510\",\n mode: manifestInput.mode || \"quality_gate\",\n identifier: manifestInput.story_id || manifestInput.identifier,\n story_id: manifestInput.story_id || manifestInput.identifier,\n fast_track: manifestInput.fast_track === true,\n task_provider: manifestInput.task_provider || \"unknown\",\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n story_id: manifest.story_id,\n phase: PHASES.CONFIG,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n fast_track: manifest.fast_track,\n worker_results: {},\n child_runs: {},\n review_summary: null,\n criteria_summary: null,\n linters_summary: null,\n aggregated_issues: [],\n quality_score: null,\n quality_verdict: null,\n self_check_passed: false,\n final_result: null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = qualityStore;\n\nexport { readJsonFile };\n\nexport function recordWorker(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(qualityWorkerSummarySchema, summary, \"quality worker summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n worker_results: {\n ...state.worker_results,\n [summary.payload.worker]: summary,\n },\n }));\n}\n","content_type":"text/javascript","language":"javascript","size":3337,"content_sha256":"01a8c542c35faa576349b3faaa27808b91df61315cad1920c7d673c08e41dd63"},{"filename":"references/scripts/repo_review_suite.mjs","content":"#!/usr/bin/env node\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst scriptDir = dirname(fileURLToPath(import.meta.url));\nconst gitRoot = spawnSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n cwd: scriptDir,\n encoding: \"utf8\",\n shell: false,\n});\nconst repoRoot = gitRoot.status === 0 ? gitRoot.stdout.trim() : resolve(scriptDir, \"../../../../..\");\n\nfunction parseArgs(argv) {\n const args = {\n runtime: \"quick\",\n };\n\n for (let index = 0; index \u003c argv.length; index += 1) {\n const arg = argv[index];\n if (arg === \"--runtime\") {\n args.runtime = argv[index + 1];\n index += 1;\n } else if (arg.startsWith(\"--runtime=\")) {\n args.runtime = arg.slice(\"--runtime=\".length);\n } else if (arg === \"--skip-runtime\") {\n args.runtime = \"skip\";\n } else if (arg === \"--full-runtime\") {\n args.runtime = \"full\";\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n\n if (![\"quick\", \"full\", \"skip\"].includes(args.runtime)) {\n throw new Error(\"--runtime must be one of: quick, full, skip\");\n }\n return args;\n}\n\nfunction readText(path) {\n return readFileSync(join(repoRoot, path), \"utf8\");\n}\n\nfunction exists(path) {\n return existsSync(join(repoRoot, path));\n}\n\nfunction listDir(path) {\n const absolute = join(repoRoot, path);\n if (!existsSync(absolute)) return [];\n return readdirSync(absolute, { withFileTypes: true });\n}\n\nfunction walk(path, predicate = () => true) {\n const absolute = join(repoRoot, path);\n if (!existsSync(absolute)) return [];\n const files = [];\n const visit = (current) => {\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n const full = join(current, entry.name);\n const rel = relative(repoRoot, full).replaceAll(\"\\\\\", \"/\");\n if (entry.isDirectory()) {\n if (entry.name === \".git\" || entry.name === \"node_modules\") continue;\n if (/^plugins\\/[^/]+\\/shared(?:\\/|$)/.test(rel)) continue;\n visit(full);\n } else if (entry.isFile() && predicate(rel)) {\n files.push(rel);\n }\n }\n };\n if (statSync(absolute).isDirectory()) visit(absolute);\n return files;\n}\n\nfunction run(command, args, options = {}) {\n return spawnSync(command, args, {\n cwd: repoRoot,\n encoding: \"utf8\",\n shell: false,\n ...options,\n });\n}\n\nfunction add(results, id, check, result) {\n results.push({ id, check, result });\n}\n\nfunction grepCount(paths, regex, { exclude = () => false } = {}) {\n let count = 0;\n for (const path of paths) {\n if (exclude(path) || !exists(path)) continue;\n const text = readText(path);\n const matches = text.match(regex);\n count += matches ? matches.length : 0;\n }\n return count;\n}\n\nfunction skillDirs() {\n const dirs = [];\n for (const plugin of listDir(\"plugins\").filter((entry) => entry.isDirectory())) {\n const skillsRoot = `plugins/${plugin.name}/skills`;\n for (const entry of listDir(skillsRoot)) {\n if (entry.isDirectory() && /^ln-\\d+-/.test(entry.name) && exists(`${skillsRoot}/${entry.name}/SKILL.md`)) {\n dirs.push(`${skillsRoot}/${entry.name}`);\n }\n }\n }\n return dirs.sort();\n}\n\nfunction skillFiles() {\n return skillDirs().map((dir) => `${dir}/SKILL.md`);\n}\n\nfunction docsAndSkillFiles() {\n return [\n ...[\"AGENTS.md\", \"README.md\"].filter(exists),\n ...walk(\"docs\", (path) => /\\.(md|mdx|txt|html)$/.test(path)),\n ...walk(\"plugins\", (path) => /\\.(md|json|mjs|sh)$/.test(path)),\n ...walk(\".claude/commands\", (path) => path.endsWith(\".md\")),\n ];\n}\n\nfunction referencedSkillNames(paths) {\n const names = new Set();\n for (const path of paths) {\n if (!exists(path)) continue;\n for (const match of readText(path).matchAll(/ln-\\d+-[a-z-]+/g)) {\n names.add(match[0]);\n }\n }\n return [...names];\n}\n\nfunction marketplaceSkillPaths() {\n if (!exists(\".claude-plugin/marketplace.json\")) return [];\n const json = JSON.parse(readText(\".claude-plugin/marketplace.json\"));\n const paths = [];\n for (const plugin of json.plugins || []) {\n const source = typeof plugin.source === \"string\" ? plugin.source.replace(/^\\.\\//, \"\").replace(/\\/$/, \"\") : \"\";\n for (const skill of plugin.skills || []) {\n const skillPath = typeof skill === \"string\" ? skill : skill?.path;\n if (typeof skillPath === \"string\") {\n const normalized = skillPath.replace(/^\\.\\//, \"\");\n paths.push(source ? `${source}/${normalized}` : normalized);\n }\n }\n }\n return paths;\n}\n\nfunction checkMarketplaceCount(pluginName) {\n const result = run(process.execPath, [\"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/check_marketplace.mjs\", pluginName]);\n return Number(String(result.stdout || \"\").trim());\n}\n\nfunction runQuickRuntimeSuite() {\n const quickTests = [\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/coordinator-runtime/test/platform-regression.mjs\",\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/coordinator-runtime/test/consistency-scan.mjs\",\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/story-planning-runtime/test/smoke.mjs\",\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/task-planning-runtime/test/smoke.mjs\",\n \"plugins/agile-workflow/skills/ln-1000-pipeline-orchestrator/scripts/test/smoke.mjs\",\n \"plugins/agile-workflow/skills/ln-1000-pipeline-orchestrator/scripts/test/isolation.mjs\",\n ];\n const failures = [];\n for (const test of quickTests) {\n const result = run(process.execPath, [test], { timeout: 45000 });\n if (result.status !== 0) {\n failures.push({\n file: test,\n status: result.status,\n detail: (result.stderr || result.stdout || \"quick runtime test failed\").split(\"\\n\").slice(-10).join(\"\\n\"),\n });\n }\n }\n return {\n ok: failures.length === 0,\n total: quickTests.length,\n failed: failures.length,\n mode: \"quick\",\n failures,\n };\n}\n\nfunction runFullRuntimeSuite() {\n const result = run(process.execPath, [\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/run_runtime_suite.mjs\",\n \"--json\",\n \"--concurrency\",\n \"3\",\n \"--timeout-ms\",\n \"120000\",\n ], { timeout: 600000 });\n if (result.status !== 0) {\n return { ok: false, total: 0, failed: \"unknown\", detail: result.stderr || result.stdout || \"runtime suite failed\" };\n }\n return { ...JSON.parse(result.stdout), mode: \"full\" };\n}\n\nfunction main() {\n const args = parseArgs(process.argv.slice(2));\n const results = [];\n const skills = skillDirs();\n const skillMd = skillFiles();\n const activeFiles = docsAndSkillFiles();\n\n const marketplacePaths = marketplaceSkillPaths();\n const r1Missing = marketplacePaths.filter((path) => !exists(path));\n add(results, \"R1\", \"Marketplace paths\", r1Missing.length === 0 ? \"PASS\" : `FAIL (${r1Missing.length} missing dirs)`);\n\n const rootDocs = [\"README.md\", \"AGENTS.md\", \".claude-plugin/marketplace.json\"].filter(exists);\n let r2Fails = 0;\n for (const skill of referencedSkillNames(rootDocs)) {\n if (!skills.some((dir) => basename(dir).startsWith(skill))) r2Fails += 1;\n }\n add(results, \"R2\", \"Root docs stale names\", r2Fails === 0 ? \"PASS\" : `FAIL (${r2Fails} stale refs)`);\n\n const actualCount = skills.length;\n const badge = exists(\"README.md\") ? readText(\"README.md\").match(/skills-(\\d+)/)?.[1] : null;\n const r3Fails = (badge && Number(badge) !== actualCount ? 1 : 0) + (marketplacePaths.length !== actualCount ? 1 : 0);\n add(results, \"R3\", \"Skill count accuracy\", r3Fails === 0 ? `PASS (${actualCount} skills)` : `FAIL (badge/marketplace mismatch, actual=${actualCount})`);\n\n const marketplaceSet = new Set(marketplacePaths);\n const r4Fails = skills.filter((dir) => !marketplaceSet.has(dir)).length;\n add(results, \"R4\", \"Plugin completeness\", r4Fails === 0 ? \"PASS\" : `FAIL (${r4Fails} orphan skills)`);\n\n let r5Warns = 0;\n const downstreamFiles = skillMd.filter((path) => /^plugins\\/[^/]+\\/skills\\/ln-[2345]/.test(path));\n for (const creator of skillMd.filter((path) => /^plugins\\/[^/]+\\/skills\\/ln-11[1-5]-/.test(path))) {\n const outputs = [...new Set([...readText(creator).matchAll(/`([a-zA-Z_]+\\.md)`/g)]\n .map((match) => match[1])\n .filter((name) => !/(SKILL|README|CLAUDE|AGENTS|_template)/.test(name)))]\n .sort()\n .slice(0, 5);\n for (const output of outputs) {\n const found = downstreamFiles.some((path) => readText(path).includes(output));\n if (!found) r5Warns += 1;\n }\n }\n add(results, \"R5\", \"Pipeline data-flow\", r5Warns === 0 ? \"PASS\" : `WARN (${r5Warns} possibly orphan outputs)`);\n\n const unsupportedExcludes = (path) => path.includes(\"CHANGELOG.md\")\n || path.includes(\"/unsupported/\")\n || path.includes(\"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/\")\n || path === \".claude/commands/review-skills.md\";\n const unsupportedPlatformPattern = new RegExp([\"Agent \" + \"Teams\", \"Team\" + \"Create\", \"Teammate\" + \"Idle\"].join(\"|\"), \"g\");\n const r6Fails = grepCount(activeFiles, unsupportedPlatformPattern, { exclude: unsupportedExcludes });\n add(results, \"R6\", \"Unsupported platform API references\", r6Fails === 0 ? \"PASS\" : `FAIL (${r6Fails} active refs)`);\n\n const r7Fails = grepCount(activeFiles, /tests\\/(e2e|integration|unit)/g, { exclude: (path) => path === \".claude/commands/review-skills.md\" });\n add(results, \"R7\", \"Automated test root consistency\", r7Fails === 0 ? \"PASS\" : `FAIL (${r7Fails} old test roots)`);\n\n let r8Fails = 0;\n for (const path of [\"plugins/documentation-pipeline/skills/ln-160-docs-skill-extractor/SKILL.md\", \"plugins/documentation-pipeline/skills/ln-161-skill-creator/SKILL.md\"]) {\n const text = exists(path) ? readText(path) : \"\";\n for (const required of [\"markdown_read_protocol\", \"docs_quality_contract\", \"procedural_extraction_rules\"]) {\n if (!text.includes(required)) r8Fails += 1;\n }\n }\n const creatorText = exists(\"plugins/documentation-pipeline/skills/ln-161-skill-creator/SKILL.md\") ? readText(\"plugins/documentation-pipeline/skills/ln-161-skill-creator/SKILL.md\") : \"\";\n if (/^\\*\\*Coordinator:\\*\\*/m.test(creatorText)) r8Fails += 1;\n if (/^\\*\\*Parent:\\*\\*/m.test(creatorText)) r8Fails += 1;\n add(results, \"R8\", \"Docs extraction family alignment\", r8Fails === 0 ? \"PASS\" : `FAIL (${r8Fails} drift issues)`);\n\n const siteChanged = run(\"git\", [\"diff\", \"--name-only\", \"HEAD\", \"--\", \"site/\"]).stdout.trim().length > 0;\n if (siteChanged) {\n let r9Fails = 0;\n for (const page of walk(\"site/plugins\", (path) => path.endsWith(\".html\"))) {\n const plugin = basename(page, \".html\");\n const siteSkills = (readText(page).match(/skill-id\">ln-\\d+/g) || []).length;\n const marketSkills = checkMarketplaceCount(plugin);\n if (siteSkills > 0 && siteSkills !== marketSkills) r9Fails += 1;\n }\n const auditorCount = skillMd.filter((path) => /^plugins\\/[^/]+\\/skills\\/ln-6/.test(path)).length;\n const siteAuditor = exists(\"site/index.html\") ? readText(\"site/index.html\").match(/(\\d+) parallel auditors/)?.[1] : null;\n if (siteAuditor && Number(siteAuditor) !== auditorCount) r9Fails += 1;\n add(results, \"R9\", \"Site fact-check\", r9Fails === 0 ? \"PASS\" : `FAIL (${r9Fails} mismatches)`);\n } else {\n add(results, \"R9\", \"Site fact-check\", \"SKIP (no site/ changes)\");\n }\n\n const r10Warns = grepCount(walk(\"site\", (path) => path.endsWith(\".html\")), /\\d+ (skills|auditors|parallel auditors)/g);\n add(results, \"R10\", \"Volatile numbers in site\", r10Warns === 0 ? \"PASS\" : `WARN (${r10Warns} found)`);\n\n const checksDoc = new Set([...readText(\"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/automated_checks.md\").matchAll(/Check (\\d+)/g)].map((match) => match[1]));\n const checksScript = new Set([...readText(\"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/run_checks.sh\").matchAll(/CHECK (\\d+)/g)].map((match) => match[1]));\n const missingChecks = [...checksDoc].filter((check) => !checksScript.has(check));\n add(results, \"R11\", \"Check sync (docs\u003c->script)\", missingChecks.length === 0 ? \"PASS\" : `FAIL (missing in script: ${missingChecks.join(\",\")})`);\n\n let r12Fails = 0;\n for (const path of skillMd) {\n const text = readText(path);\n const level = text.match(/\\*\\*Type:\\*\\*.*\\b(L[12])\\b/)?.[1];\n if (!level || /\\*\\*Type:\\*\\*.*worker/i.test(text) || text.includes(\"| None |\")) continue;\n const self = basename(dirname(path));\n const workerCount = new Set([...text.matchAll(/ln-\\d+-[a-z-]+/g)].map((match) => match[0]).filter((name) => name !== self)).size;\n if (workerCount === 0) continue;\n if (!text.includes(\"Skill(skill:\")) r12Fails += 1;\n if (!text.includes(\"Worker Invocation (MANDATORY)\")) r12Fails += 1;\n }\n add(results, \"R12\", \"Worker invocation (full-repo D8b)\", r12Fails === 0 ? \"PASS\" : `FAIL (${r12Fails} issues)`);\n\n let r13Fails = 0;\n for (const path of skillMd) {\n const text = readText(path);\n if (!/\\*\\*Type:\\*\\*.*L3/.test(text)) continue;\n const selfId = basename(dirname(path)).match(/ln-\\d+/)?.[0];\n const hits = text.split(/\\r?\\n/).filter((line) => /Called by|Invoked by ln-|Caller:|returning control to `ln-|for `ln-\\d+`|returned to coordinator|handing control back to `ln-/.test(line));\n if (hits.some((line) => !selfId || !line.includes(`for \\`${selfId}\\``))) r13Fails += 1;\n }\n add(results, \"R13\", \"Worker independence (no coordinator refs)\", r13Fails === 0 ? \"PASS\" : `FAIL (${r13Fails} worker contracts)`);\n\n const r14Fails = grepCount([...walk(\"plugins\"), ...[\"README.md\", \"AGENTS.md\"], ...walk(\"docs\"), ...walk(\"site\")], /\\.hex-skills\\/(story-execution\\/summary|story-gate\\/summary|optimization\\/\\{slug\\}\\/8(11|12|13|14)-)/g);\n add(results, \"R14\", \"Universal runtime artifacts\", r14Fails === 0 ? \"PASS\" : `FAIL (${r14Fails} coordinator-specific paths)`);\n\n let r15Fails = 0;\n for (const path of [\n \"plugins/setup-environment/skills/ln-011-agent-installer/SKILL.md\",\n \"plugins/setup-environment/skills/ln-012-mcp-configurator/SKILL.md\",\n \"plugins/setup-environment/skills/ln-013-config-syncer/SKILL.md\",\n \"plugins/setup-environment/skills/ln-014-agent-instructions-manager/SKILL.md\",\n \"plugins/agile-workflow/skills/ln-221-story-creator/SKILL.md\",\n \"plugins/agile-workflow/skills/ln-222-story-replanner/SKILL.md\",\n \"plugins/agile-workflow/skills/ln-301-task-creator/SKILL.md\",\n \"plugins/agile-workflow/skills/ln-302-task-replanner/SKILL.md\",\n ]) {\n if (!exists(path)) continue;\n const text = readText(path);\n if (!text.includes(\"summaryArtifactPath\")) r15Fails += 1;\n if (!/standalone/i.test(text)) r15Fails += 1;\n }\n add(results, \"R15\", \"Standalone-first worker contract\", r15Fails === 0 ? \"PASS\" : `FAIL (${r15Fails} missing contract markers)`);\n\n const r16Fails = grepCount([...walk(\"plugins\"), ...[\"README.md\", \"AGENTS.md\"], ...walk(\"docs\"), ...walk(\"site\")], /\\.hex-skills\\/runtime-artifacts\\/(?!runs\\/)/g, {\n exclude: (path) => path.startsWith(\"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/\") || path === \".claude/commands/review-skills.md\",\n });\n add(results, \"R16\", \"Run-scoped artifact paths\", r16Fails === 0 ? \"PASS\" : `FAIL (${r16Fails} non-run-scoped paths)`);\n\n if (args.runtime === \"skip\") {\n add(results, \"R17\", \"Runtime test suite\", \"SKIP (--runtime skip)\");\n } else {\n const runtime = args.runtime === \"full\" ? runFullRuntimeSuite() : runQuickRuntimeSuite();\n const label = args.runtime === \"full\" ? `Runtime test suite (${runtime.total} files)` : `Quick runtime smoke (${runtime.total} files)`;\n add(results, \"R17\", label, runtime.ok ? \"PASS\" : `FAIL (${runtime.failed}/${runtime.total} failed)`);\n }\n\n let r18Fails = 0;\n if (exists(\"references/runtime_status_catalog.md\") && exists(\"references/agent_review_workflow.md\")) {\n const catalog = new Set([...readText(\"references/runtime_status_catalog.md\").matchAll(/`(CONVERGED|CONVERGED_LOW_IMPACT|MAX_ITER|ERROR|SKIPPED)`/g)].map((match) => match[1]));\n const workflowLines = readText(\"references/agent_review_workflow.md\").split(/\\r?\\n/).filter((line) => line.includes(\"exit_reason:\"));\n const quotedReasons = workflowLines.at(-1)?.match(/\"([^\"]+)\"/)?.[1] || \"\";\n const schemaReasons = new Set(quotedReasons.split(\"|\").map((reason) => reason.trim()).filter((reason) => reason && reason !== \"SKIPPED\"));\n for (const reason of schemaReasons) if (!catalog.has(reason)) r18Fails += 1;\n add(results, \"R18\", \"Exit reason enum sync\", r18Fails === 0 ? \"PASS\" : `FAIL (${r18Fails} reasons in schema but not in catalog)`);\n } else {\n add(results, \"R18\", \"Exit reason enum sync\", \"SKIP\");\n }\n\n if (exists(\"references/scripts/review-runtime/cli.mjs\") && exists(\"references/review_runtime_contract.md\")) {\n const text = readText(\"references/scripts/review-runtime/cli.mjs\");\n const missing = [\"refinement_iterations\", \"refinement_exit_reason\", \"refinement_applied\"].filter((field) => !text.includes(field)).length;\n add(results, \"R19\", \"Checkpoint payload completeness\", missing === 0 ? \"PASS\" : `FAIL (${missing} missing Phase 6 fields in cli.mjs)`);\n } else {\n add(results, \"R19\", \"Checkpoint payload completeness\", \"SKIP\");\n }\n\n const missingGuardTests = [];\n for (const runtimeDir of listDir(\"references/scripts\").filter((entry) => entry.isDirectory() && entry.name.endsWith(\"-runtime\")).map((entry) => `references/scripts/${entry.name}`)) {\n if (!exists(`${runtimeDir}/test`) || !exists(`${runtimeDir}/lib/guards.mjs`)) continue;\n const runtimeName = basename(runtimeDir);\n if (/^(coordinator|planning|story-planning|task-planning)-runtime$/.test(runtimeName)) continue;\n const guards = readText(`${runtimeDir}/lib/guards.mjs`);\n if (/validateLinearWorkerTransition|validateCoordinatorTransition/.test(guards)) continue;\n if (!exists(`${runtimeDir}/test/guards.mjs`)) missingGuardTests.push(runtimeName);\n }\n add(results, \"R20\", \"Guard coverage tests\", missingGuardTests.length === 0 ? \"PASS\" : `FAIL (missing: ${missingGuardTests.join(\" \")})`);\n\n const r21Fails = [\n \"references/scripts/story-planning-runtime/lib/store.mjs\",\n \"references/scripts/task-planning-runtime/lib/store.mjs\",\n \"references/scripts/epic-planning-runtime/lib/store.mjs\",\n \"references/scripts/docs-pipeline-runtime/lib/store.mjs\",\n \"references/scripts/scope-decomposition-runtime/lib/store.mjs\",\n ].filter((path) => exists(path) && !readText(path).includes(\"resumablePhases\")).length;\n add(results, \"R21\", \"resumablePhases in planning stores\", r21Fails === 0 ? \"PASS\" : `FAIL (${r21Fails} stores missing)`);\n\n let r22Fails = 0;\n for (const guards of walk(\"references/scripts\", (path) => path.endsWith(\"-runtime/lib/guards.mjs\"))) {\n const text = readText(guards);\n if (!text.includes(\"DONE\")) continue;\n if (/validateLinearWorkerTransition|validateCoordinatorTransition/.test(text)) continue;\n if (!text.includes(\"final_result\")) r22Fails += 1;\n }\n add(results, \"R22\", \"final_result guard on DONE\", r22Fails === 0 ? \"PASS\" : `FAIL (${r22Fails} missing)`);\n\n const r23Fails = grepCount(activeFiles, /review-runtime|audit-runtime|audit-worker-runtime|review_runtime_contract|audit_runtime_contract|audit_worker_runtime_contract/g, {\n exclude: (path) => path.includes(\"CHANGELOG.md\")\n || path === \".claude/commands/review-skills.md\"\n || path === \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/repo_review_suite.mjs\",\n });\n add(results, \"R23\", \"No legacy review/audit runtimes\", r23Fails === 0 ? \"PASS\" : `FAIL (${r23Fails} active refs)`);\n\n let r24Fails = 0;\n if (exists(\"README.md\")) {\n const readmeMatches = readText(\"README.md\").split(/\\r?\\n/).filter((line) => /(^|[^A-Za-z0-9/])\\d+ skills/.test(line) && !line.includes(\"img.shields.io/badge/skills-\"));\n r24Fails += readmeMatches.length;\n }\n r24Fails += grepCount([\n \"AGENTS.md\",\n ...walk(\"docs\"),\n ...walk(\"plugins\"),\n ...walk(\".claude/commands\"),\n ], /(^|[^A-Za-z0-9/])\\d+ skills|skills-\\d+/g, {\n exclude: (path) => path === \".claude/commands/review-skills.md\",\n });\n add(results, \"R24\", \"No hardcoded skill counts\", r24Fails === 0 ? \"PASS\" : `FAIL (${r24Fails} count refs outside badge)`);\n\n const r25Fails = grepCount(skillMd, /MANDATORY READ (per|for|when)|MANDATORY READ: (?!Load )|\\*\\*MANDATORY READ:\\*\\* (?!Load )/g);\n add(results, \"R25\", \"Exact MANDATORY READ pattern\", r25Fails === 0 ? \"PASS\" : `FAIL (${r25Fails} nonstandard patterns)`);\n\n if (exists(\"mcp/check-output-contracts.mjs\")) {\n const result = run(process.execPath, [\"mcp/check-output-contracts.mjs\"]);\n add(results, \"R26\", \"MCP output contract checker\", result.status === 0 ? \"PASS\" : \"FAIL\");\n } else {\n add(results, \"R26\", \"MCP output contract checker\", \"SKIP\");\n }\n\n let r27Fails = 0;\n const navigationText = [\n \"AGENTS.md\",\n \"docs/README.md\",\n \"README.md\",\n \"docs/architecture/SKILL_ARCHITECTURE_GUIDE.md\",\n ].map((path) => exists(path) ? readText(path) : \"\").join(\"\\n\");\n if (!navigationText.includes(\"loop_health_contract.md\")) r27Fails += 1;\n if (!navigationText.includes(\"procedural_skill_sop_guide.md\")) r27Fails += 1;\n if (!/Loop Health/i.test(exists(\"docs/plugins/agile-workflow.md\") ? readText(\"docs/plugins/agile-workflow.md\") : \"\")) r27Fails += 1;\n for (const path of [\n \"plugins/agile-workflow/skills/ln-1000-pipeline-orchestrator/SKILL.md\",\n \"plugins/agile-workflow/skills/ln-400-story-executor/SKILL.md\",\n ]) {\n const text = exists(path) ? readText(path) : \"\";\n if (!text.includes(\"loop_health_contract.md\")) r27Fails += 1;\n if (!text.includes(\"record-loop-health\")) r27Fails += 1;\n }\n for (const path of [\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/coordinator-runtime/test/loop-health.mjs\",\n \"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/story-execution-runtime/test/loop-health.mjs\",\n \"plugins/agile-workflow/skills/ln-1000-pipeline-orchestrator/scripts/test/loop-health.mjs\",\n ]) {\n if (!exists(path)) r27Fails += 1;\n }\n add(results, \"R27\", \"Loop Health/SOP discoverability\", r27Fails === 0 ? \"PASS\" : `FAIL (${r27Fails} missing refs)`);\n\n process.stdout.write(\"\\n## Repo-Specific Review -- claude-code-skills\\n\\n\");\n process.stdout.write(\"| # | Check | Result |\\n\");\n process.stdout.write(\"|---|-------|--------|\\n\");\n for (const row of results) {\n process.stdout.write(`| ${row.id} | ${row.check} | ${row.result} |\\n`);\n }\n const failures = results.filter((row) => row.result.includes(\"FAIL\")).length;\n const warnings = results.filter((row) => row.result.includes(\"WARN\")).length;\n process.stdout.write(\"\\n\");\n if (failures > 0) {\n process.stdout.write(`Repo verdict: FAIL (${failures} failures, ${warnings} warnings)\\n`);\n } else if (warnings > 0) {\n process.stdout.write(`Repo verdict: PASS with WARNINGS (${warnings})\\n`);\n } else {\n process.stdout.write(\"Repo verdict: PASS\\n\");\n }\n process.exit(failures > 0 ? 1 : 0);\n}\n\nmain();\n","content_type":"text/javascript","language":"javascript","size":24468,"content_sha256":"04cf00b663e7efaf2daaab64e958a38df78f28c43d7e3b725a4f537e856adbe1"},{"filename":"references/scripts/run_checks.sh","content":"#!/usr/bin/env bash\n# Automated SKILL.md verification checks (ln-162-skill-reviewer Phase 2)\n# Usage: bash run_checks.sh \u003cbatched SKILL.md files...>\n# Example: bash run_checks.sh ln-010-*/SKILL.md ln-011-*/SKILL.md\n#\n# Exit code: 0 if all pass, 1 if any FAIL found\n# Batch policy:\n# - keep one invocation within one ln-NXX family when possible\n# - split coordinators and workers into separate invocations\n# - for large families, chunk into 5-10 files instead of one giant repo-wide run\n# Lessons learned (bugs fixed vs template version):\n# - grep -q returns exit code 1 on no match -> breaks && chains; use if/then\n# - grep -c returns exit code 1 when count=0 -> append || true\n# - passive ref grep needs || true to avoid false script failure\n# - MANDATORY READ paths outside plugins/*/skills/ (mcp/, docs/project/*) are runtime-only\n# and skipped by Check 5 (only references/, references/, ../ln-* are verified)\n# - pipe | while read creates subshell -> FAILS counter lost; use \u003c \u003c(...) instead\n\nset -uo pipefail\n\n# Resolve repo root. Prefer the caller's working tree (git) so the script works\n# even when invoked from a plugin cache against a different project tree.\n# Fallback: resolve relative to the script location for offline / non-git use.\nREPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || (cd \"$(dirname \"$0\")/../../..\" && pwd))\nSKILLS_ROOT=\"$REPO_ROOT/plugins\"\nSCOPE=\"$@\"\nFAILS=0\n\nif [ $# -eq 0 ]; then\n echo \"Usage: bash run_checks.sh \u003cSKILL.md files...>\"\n echo \"Example: bash run_checks.sh ln-*/SKILL.md\"\n exit 2\nfi\n\nif [ $# -gt 12 ]; then\n echo \"WARN: large scope ($# files). Split run_checks.sh into smaller batches by ln-NXX family or coordinator/worker group.\" >&2\nfi\n\nfail() { echo \"FAIL: $1\"; FAILS=$((FAILS + 1)); }\nwarn() { echo \"WARN: $1\"; }\n\n# ── CHECK 1: Frontmatter (D7) ──────────────────────────────────────\necho \"=== CHECK 1: Frontmatter (D7) ===\"\nfor f in $SCOPE; do\n head -5 \"$f\" | grep -q \"^---\" || fail \"no frontmatter: $f\"\n grep -q \"^name:\" \"$f\" || fail \"no name: $f\"\n grep -q \"^description:\" \"$f\" || fail \"no description: $f\"\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 2: Version/Date (D7) ─────────────────────────────────────\necho \"=== CHECK 2: Version/Date (D7) ===\"\nfor f in $SCOPE; do\n grep -q '\\*\\*Version:\\*\\*' \"$f\" || fail \"no version: $f\"\n grep -q '\\*\\*Last Updated:\\*\\*' \"$f\" || fail \"no date: $f\"\n if grep -q '\\*\\*Changes:\\*\\*' \"$f\"; then fail \"has Changes section: $f\"; fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 3: Size \u003c=800 (D8) ───────────────────────────────────────\necho \"=== CHECK 3: Size \u003c=800 (D8) ===\"\nfor f in $SCOPE; do\n lines=$(wc -l \u003c \"$f\")\n if [ \"$lines\" -gt 800 ]; then fail \"$lines lines (>800): $f\"; fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 4: Description \u003c=200 chars (D8) ──────────────────────────\necho \"=== CHECK 4: Description \u003c=200 chars (D8) ===\"\nfor f in $SCOPE; do\n desc=$(sed -n '/^description:/p' \"$f\" | sed 's/^description: *//' | tr -d '\"')\n len=${#desc}\n if [ \"$len\" -gt 200 ]; then fail \"description $len chars (>200): $f\"; fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 5: MANDATORY READ paths (D2) ─────────────────────────────\necho \"=== CHECK 5: MANDATORY READ paths (D2) ===\"\nfor f in $SCOPE; do\n dir=$(dirname \"$f\")\n while read -r path; do\n # Only verify paths resolvable within plugins/*/skills/ (references/, references/, ../ln-*)\n # Paths outside skills tree (mcp/, docs/project/) are runtime — skip\n if ! echo \"$path\" | grep -qE '^(references/|references/|\\.\\./ln-)'; then continue; fi\n if [ ! -f \"$dir/$path\" ] && [ ! -f \"$path\" ] && [ ! -f \"$SKILLS_ROOT/$path\" ]; then\n fail \"missing MANDATORY READ target: $path (from $f)\"\n fi\n done \u003c \u003c(grep \"MANDATORY READ\" \"$f\" | tr '`' '\\n' | grep -E '\\.(md|json|txt|yaml|sh)

Paths: File paths ( , ) are relative to this skill directory. ln-162-skill-reviewer Type: L3 Worker (standalone-capable) Category: 1XX Documentation Pipeline Universal reviewer with two modes: - for - for - repo suite for this skills repository when / is requested or the current repo is Plan Mode behavior: Phases 1-4 and 6-7 are research. Run them fully in Plan Mode, write the report plus fix list into the plan, and apply edits only after approval. --- Mode Detection | Condition | Mode | Review Profile | |-----------|------|----------------| | files exist in CWD | SKILL | Full D1-D11 + M1-M6…

| grep -v '{' | sort -u)\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 6: Orphan references (D7) ────────────────────────────────\necho \"=== CHECK 6: Orphan references (D7) ===\"\nfor f in $SCOPE; do\n dir=$(dirname \"$f\")\n if [ -d \"$dir/references\" ]; then\n while read -r ref; do\n rel=${ref#\"$dir/\"}\n base=$(basename \"$ref\")\n [[ \"$base\" == .* ]] && continue\n case \"$rel\" in\n */dist/*|*/node_modules/*) continue ;;\n esac\n covered=0\n probe=\"$rel\"\n while [[ \"$probe\" == */* ]]; do\n if grep -Fq \"$probe/\" \"$f\"; then covered=1; break; fi\n probe=$(dirname \"$probe\")\n done\n [ \"$covered\" -eq 1 ] && continue\n grep -Fq \"$base\" \"$f\" || fail \"orphan reference: $ref (not in $f)\"\n done \u003c \u003c(find \"$dir/references\" -type f)\n fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 7: Passive file refs (D2) ────────────────────────────────\necho \"=== CHECK 7: Passive file refs (D2) ===\"\nfor f in $SCOPE; do\n result1=$(grep -nE '(^See |^Per |^Follows |See \\[).*\\.(md|txt|yaml)' \"$f\" | grep -v \"MANDATORY READ\" || true)\n result2=$(grep -nE '\\[[^\\]]*\\]\\([^)]*\\.(md|txt|yaml)\\)' \"$f\" | grep -vE '(MANDATORY READ|https?://)' || true)\n if [ -n \"$result1\" ]; then warn \"passive prose ref in $f:\"; echo \"$result1\"; fi\n if [ -n \"$result2\" ]; then warn \"passive markdown link in $f:\"; echo \"$result2\"; fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 8: DoD with checkboxes (D7) ──────────────────────────────\necho \"=== CHECK 8: DoD with checkboxes (D7) ===\"\nfor f in $SCOPE; do\n grep -q \"## Definition of Done\" \"$f\" || fail \"no Definition of Done: $f\"\n if grep -q \"## Definition of Done\" \"$f\"; then\n count=$(sed -n '/## Definition of Done/,/^---/p' \"$f\" | grep -c '^\\- \\[ \\]' || true)\n if [ \"$count\" -eq 0 ]; then fail \"DoD has no checkbox items (- [ ]): $f\"; fi\n fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 9: Meta-Analysis L1/L2 (D7) ──────────────────────────────\necho \"=== CHECK 9: Meta-Analysis L1/L2 (D7) ===\"\nfor f in $SCOPE; do\n level=$(grep '\\*\\*Type:\\*\\*' \"$f\" | grep -oE 'L[012]' | head -1 || true)\n # Meta-Analysis: orchestrators and coordinators only (not Workers)\n if [ -n \"$level\" ] && ! grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qi 'worker'; then\n grep -q \"Meta-Analysis\" \"$f\" || fail \"L1/L2 skill missing Meta-Analysis: $f\"\n grep -q \"meta_analysis_protocol\" \"$f\" || fail \"L1/L2 skill missing meta_analysis_protocol ref: $f\"\n fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 10: Publishing skills (D7) ───────────────────────────────\necho \"=== CHECK 10: Publishing skills (D7) ===\"\nfor f in $SCOPE; do\n if grep -qE '(gh api graphql.*mutation|gh issue comment)' \"$f\"; then\n grep -qi \"fact.check\" \"$f\" || fail \"publishing skill missing Fact-Check: $f\"\n grep -q \"humanizer_checklist\" \"$f\" || fail \"publishing skill missing humanizer_checklist ref: $f\"\n fi\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 11: Description trigger quality (D8, WARN) ─────────────\necho \"=== CHECK 11: Description trigger quality (D8, WARN) ===\"\n\nWARNS=0\nfor f in $SCOPE; do\n desc=$(sed -n '/^description:/p' \"$f\" | head -1 | sed 's/^description: *//' | tr -d '\"')\n if [ -n \"$desc\" ]; then\n if ! echo \"$desc\" | grep -qiE '(Use (this )?(skill )?(when|for|before|after)|Trigger when|Invoked when|should be used when|Not for )'; then\n warn \"description lacks trigger condition (WHEN): $f\"\n WARNS=$((WARNS + 1))\n fi\n fi\ndone\necho \"DONE ($WARNS warnings)\"\necho \"\"\n\n# ── CHECK 12: Execution proximity (D2b, WARN) ──────────────────────\necho \"=== CHECK 12: Execution proximity (D2b, WARN) ===\"\nWARNS=0\nfor f in $SCOPE; do\n while IFS= read -r match; do\n linenum=$(echo \"$match\" | cut -d: -f1)\n start=$((linenum > 5 ? linenum - 5 : 1))\n endline=$((linenum + 10))\n nearby=$(sed -n \"${start},${endline}p\" \"$f\")\n if ! echo \"$nearby\" | grep -qE -- '```|`node |`bash |--prompt-file|--output-file|--agent '; then\n warn \"imperative tool action at line $linenum without inline command template: $f\"\n WARNS=$((WARNS + 1))\n fi\n done \u003c \u003c(grep -nE '(Launch|Run|Execute) .*(agent_runner|--agent|background task|BOTH agents)' \"$f\" | grep -v 'health-check' || true)\ndone\necho \"DONE ($WARNS warnings)\"\necho \"\"\n\n# ── CHECK 13: Platform API compatibility ────────────────────────────\necho \"=== CHECK 13: Platform API compatibility ===\"\nfor f in $SCOPE; do\n grep -n 'Agent(resume:' \"$f\" && fail \"unsupported Agent(resume:) in $f — use SendMessage({to: agentId})\"\n grep -nE 'effort.*\"max\"|effort: max' \"$f\" && fail \"unsupported effort \\\"max\\\" in $f — use low/medium/high\"\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 17: Worker invocation enforcement (D8b) ───────────────\necho \"=== CHECK 17: Worker invocation enforcement (D8b) ===\"\nfor f in $SCOPE; do\n level=$(grep '\\*\\*Type:\\*\\*' \"$f\" | grep -oE 'L[12]' | head -1 || true)\n [ -z \"$level\" ] && continue\n # Worker invocation: orchestrators and coordinators only (not Workers)\n grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qi 'worker' && continue\n self=$(basename $(dirname \"$f\") | grep -oE 'ln-[0-9]+-[a-z-]+')\n worker_count=$(grep -oE 'ln-[0-9]+-[a-z-]+' \"$f\" | sort -u | while read w; do\n [ \"$w\" != \"$self\" ] && echo \"$w\"\n done | sort -u | wc -l)\n [ \"$worker_count\" -eq 0 ] && continue\n grep -qF '| None |' \"$f\" && continue\n skill_calls=$(grep -c 'Skill(skill:' \"$f\" || true)\n [ \"$skill_calls\" -eq 0 ] && fail \"$level skill delegates to $worker_count workers but has no Skill() invocation code blocks: $f\"\n if [ \"$skill_calls\" -gt 0 ] && ! grep -q '\\*\\*Host Skill Invocation:\\*\\*' \"$f\"; then\n fail \"$level skill has Skill() invocation code but no Host Skill Invocation bridge: $f\"\n fi\n grep -q 'Worker Invocation (MANDATORY)' \"$f\" || fail \"$level skill missing Worker Invocation (MANDATORY) section: $f\"\n grep -q 'TodoWrite format (mandatory)' \"$f\" || warn \"$level skill missing TodoWrite format section: $f\"\ndone\necho \"DONE\"\necho \"\"\n\n# ── CHECK 18: Type line presence (D7) ──────────────────────────────\necho \"=== CHECK 18: Type line presence (D7) ===\"\nfor f in $SCOPE; do\n grep -q '\\*\\*Type:\\*\\*' \"$f\" || fail \"no **Type:** line: $f\"\ndone\necho \"DONE\"\necho \"\"\n\n# CHECK 19: Worker independence (D8)\necho \"=== CHECK 19: Worker independence (D8) ===\"\nfor f in $SCOPE; do\n grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qi 'worker' || continue\n if grep -q '^\\*\\*Coordinator:\\*\\*' \"$f\"; then fail \"worker declares Coordinator: $f\"; fi\n if grep -q '^\\*\\*Parent:\\*\\*' \"$f\"; then fail \"worker declares Parent: $f\"; fi\n if grep -nE 'Invoked by ln-[0-9]+|called by ln-[0-9]+' \"$f\" >/dev/null; then fail \"worker declares caller coupling: $f\"; fi\ndone\necho \"DONE\"\necho \"\"\n\n# CHECK 20: Docs-model alignment for extraction skills (D4)\necho \"=== CHECK 20: Docs-model alignment for extraction skills (D4) ===\"\nfor f in $SCOPE; do\n case \"$f\" in\n *ln-160-*|*ln-161-*)\n grep -q 'markdown_read_protocol' \"$f\" || fail \"docs extraction skill missing markdown_read_protocol: $f\"\n grep -q 'docs_quality_contract' \"$f\" || fail \"docs extraction skill missing docs_quality_contract: $f\"\n grep -q 'procedural_extraction_rules' \"$f\" || fail \"docs extraction skill missing procedural_extraction_rules: $f\"\n ;;\n esac\ndone\necho \"DONE\"\necho \"\"\n\n# CHECK 21: Standalone summary workers (D8)\necho \"=== CHECK 21: Standalone summary workers (D8) ===\"\nfor f in $SCOPE; do\n case \"$f\" in\n *ln-011-*|*ln-012-*|*ln-013-*|*ln-014-*|*ln-221-*|*ln-222-*|*ln-301-*|*ln-302-*)\n grep -q 'summaryArtifactPath' \"$f\" || fail \"standalone summary worker missing summaryArtifactPath contract: $f\"\n grep -qi 'standalone' \"$f\" || fail \"standalone summary worker missing standalone wording: $f\"\n grep -nE 'Invoked by ln-|called by ln-|returning control to `ln-|handing control back to `ln-' \"$f\" >/dev/null && fail \"standalone summary worker has caller coupling: $f\"\n ;;\n esac\ndone\necho \"DONE\"\necho \"\"\n\n# CHECK 22: Run-scoped runtime artifact paths (D2)\necho \"=== CHECK 22: Run-scoped runtime artifact paths (D2) ===\"\nfor f in $SCOPE; do\n grep -nP '\\.hex-skills/runtime-artifacts/(?!runs/)' \"$f\" >/dev/null && fail \"non-run-scoped runtime artifact path: $f\"\ndone\necho \"DONE\"\necho \"\"\n\n# CHECK 23: SOP/TWI procedural executability (D2b, WARN)\necho \"=== CHECK 23: SOP/TWI procedural executability (D2b, WARN) ===\"\nWARNS=0\nfor f in $SCOPE; do\n grep '\\*\\*Type:\\*\\*' \"$f\" | grep -qiE 'orchestrator|coordinator|worker' || continue\n vague=$(grep -nEi '\\b(typically|periodically|regularly|as needed|when appropriate)\\b' \"$f\" || true)\n compound=$(grep -nE '^[0-9]+\\. .*\\b(and then|; then|, then)\\b' \"$f\" || true)\n if [ -n \"$vague\" ]; then warn \"vague procedural modal wording: $f\"; echo \"$vague\"; WARNS=$((WARNS + 1)); fi\n if [ -n \"$compound\" ]; then warn \"compound procedural step: $f\"; echo \"$compound\"; WARNS=$((WARNS + 1)); fi\n if grep -qiE '(Agent\\(|Skill\\(skill:|record-worker|checkpoint|advance --to|update .*status)' \"$f\"; then\n if ! grep -qiE 'Risk Checklist|Preflight|guard|Evidence|checkpoint|artifact' \"$f\"; then\n warn \"procedural skill may lack point-of-use checklist/evidence: $f\"\n WARNS=$((WARNS + 1))\n fi\n fi\ndone\necho \"DONE ($WARNS warnings)\"\necho \"\"\n\n# ── SUMMARY ─────────────────────────────────────────────────────────\necho \"================================\"\nif [ \"$FAILS\" -eq 0 ]; then\n echo \"ALL CHECKS PASSED\"\n exit 0\nelse\n echo \"TOTAL FAILURES: $FAILS\"\n exit 1\nfi\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":14085,"content_sha256":"f4dfec54f90aaf934fe70c1aae17a837006646332d800ad17223fc53cc9dd358"},{"filename":"references/scripts/run_runtime_suite.mjs","content":"#!/usr/bin/env node\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { readdirSync, statSync } from \"node:fs\";\nimport { availableParallelism } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst scriptDir = dirname(fileURLToPath(import.meta.url));\nconst gitRoot = spawnSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n cwd: scriptDir,\n encoding: \"utf8\",\n shell: false,\n});\nconst repoRoot = gitRoot.status === 0 ? gitRoot.stdout.trim() : resolve(scriptDir, \"../../../../..\");\n\nconst batches = [\n {\n name: \"docs+audit\",\n dirs: [\n \"references/scripts/docs-pipeline-runtime/test\",\n \"references/scripts/docs-quality/test\",\n \"references/scripts/docs-runtime/test\",\n ],\n },\n {\n name: \"planning+story\",\n dirs: [\n \"references/scripts/epic-planning-runtime/test\",\n \"references/scripts/planning-worker-runtime/test\",\n \"references/scripts/scope-decomposition-runtime/test\",\n \"references/scripts/story-execution-runtime/test\",\n \"references/scripts/story-gate-runtime/test\",\n \"references/scripts/story-planning-runtime/test\",\n \"references/scripts/task-plan-worker-runtime/test\",\n \"references/scripts/task-planning-runtime/test\",\n \"references/scripts/task-worker-runtime/test\",\n \"references/scripts/test-planning-runtime/test\",\n \"references/scripts/test-planning-worker-runtime/test\",\n ],\n },\n {\n name: \"env+quality+optimization\",\n dirs: [\n \"references/agents/test\",\n \"references/scripts/benchmark-worker-runtime/test\",\n \"references/scripts/coordinator-runtime/test\",\n \"references/scripts/dependency-runtime/test\",\n \"references/scripts/environment-setup-runtime/test\",\n \"references/scripts/environment-worker-runtime/test\",\n \"references/scripts/evaluation-runtime/test\",\n \"references/scripts/evaluation-worker-runtime/test\",\n \"references/scripts/modernization-runtime/test\",\n \"references/scripts/optimization-runtime/test\",\n \"references/scripts/quality-runtime/test\",\n \"references/scripts/quality-worker-runtime/test\",\n ],\n },\n {\n name: \"pipeline-orchestrator\",\n dirs: [\n \"plugins/agile-workflow/skills/ln-1000-pipeline-orchestrator/scripts/test\",\n ],\n },\n];\n\nfunction parseArgs(argv) {\n const args = {\n concurrency: Math.max(1, Math.min(4, availableParallelism?.() || 2)),\n timeoutMs: 120000,\n json: false,\n };\n\n for (let index = 0; index \u003c argv.length; index += 1) {\n const arg = argv[index];\n if (arg === \"--json\") {\n args.json = true;\n } else if (arg === \"--concurrency\") {\n args.concurrency = Number(argv[index + 1]);\n index += 1;\n } else if (arg === \"--timeout-ms\") {\n args.timeoutMs = Number(argv[index + 1]);\n index += 1;\n }\n }\n\n if (!Number.isInteger(args.concurrency) || args.concurrency \u003c 1) {\n throw new Error(\"--concurrency must be a positive integer\");\n }\n if (!Number.isInteger(args.timeoutMs) || args.timeoutMs \u003c 1000) {\n throw new Error(\"--timeout-ms must be an integer >= 1000\");\n }\n return args;\n}\n\nfunction listTests() {\n const tests = [];\n for (const batch of batches) {\n for (const relativeDir of batch.dirs) {\n const dir = join(repoRoot, relativeDir);\n try {\n if (!statSync(dir).isDirectory()) {\n continue;\n }\n } catch {\n continue;\n }\n\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith(\".mjs\") || entry.name.includes(\"helpers\")) {\n continue;\n }\n tests.push({\n batch: batch.name,\n file: join(dir, entry.name),\n label: `${relativeDir}/${entry.name}`,\n });\n }\n }\n }\n return tests;\n}\n\nfunction runTest(test, timeoutMs) {\n return new Promise((resolveTest) => {\n const startedAt = Date.now();\n const child = spawn(process.execPath, [test.file], {\n cwd: repoRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.on(\"close\", (code, signal) => {\n clearTimeout(timer);\n resolveTest({\n ...test,\n ok: code === 0 && !timedOut,\n code,\n signal,\n timedOut,\n durationMs: Date.now() - startedAt,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n });\n}\n\nasync function runAll(tests, { concurrency, timeoutMs }) {\n const queue = [...tests];\n const results = [];\n const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {\n while (queue.length > 0) {\n const next = queue.shift();\n results.push(await runTest(next, timeoutMs));\n }\n });\n await Promise.all(workers);\n return results;\n}\n\nfunction summarize(results) {\n const failures = results.filter((result) => !result.ok);\n const byBatch = new Map();\n for (const result of results) {\n const stats = byBatch.get(result.batch) || { total: 0, failed: 0, durationMs: 0 };\n stats.total += 1;\n stats.failed += result.ok ? 0 : 1;\n stats.durationMs += result.durationMs;\n byBatch.set(result.batch, stats);\n }\n\n return {\n ok: failures.length === 0,\n total: results.length,\n failed: failures.length,\n batches: Object.fromEntries(byBatch),\n failures: failures.map((failure) => ({\n batch: failure.batch,\n file: failure.label,\n timedOut: failure.timedOut,\n code: failure.code,\n signal: failure.signal,\n durationMs: failure.durationMs,\n stderrTail: failure.stderr.split(\"\\n\").slice(-20).join(\"\\n\"),\n stdoutTail: failure.stdout.split(\"\\n\").slice(-20).join(\"\\n\"),\n })),\n };\n}\n\nconst args = parseArgs(process.argv.slice(2));\nconst tests = listTests();\nconst results = await runAll(tests, args);\nconst summary = summarize(results);\n\nif (args.json) {\n process.stdout.write(`${JSON.stringify(summary, null, 2)}\\n`);\n} else {\n for (const [batch, stats] of Object.entries(summary.batches)) {\n const verdict = stats.failed === 0 ? \"PASS\" : \"FAIL\";\n process.stdout.write(`${verdict}: ${batch} (${stats.total - stats.failed}/${stats.total})\\n`);\n }\n for (const failure of summary.failures) {\n const reason = failure.timedOut ? `timed out after ${args.timeoutMs}ms` : `exit ${failure.code ?? failure.signal}`;\n process.stderr.write(`FAIL: ${failure.file} (${reason})\\n`);\n if (failure.stderrTail) {\n process.stderr.write(`${failure.stderrTail}\\n`);\n }\n }\n process.stdout.write(`Runtime suite ${summary.ok ? \"PASS\" : \"FAIL\"} (${summary.total - summary.failed}/${summary.total} files)\\n`);\n}\n\nprocess.exit(summary.ok ? 0 : 1);\n","content_type":"text/javascript","language":"javascript","size":7818,"content_sha256":"16ea3be1b77ac74959348626fe2801ea096e3927dd4a69641df3f1c08cb0ba2b"},{"filename":"references/scripts/scope-decomposition-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/scope-decomposition-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n EPIC_DECOMPOSITION: \"PHASE_2_EPIC_DECOMPOSITION\",\n STORY_LOOP: \"PHASE_3_STORY_LOOP\",\n PRIORITIZATION_LOOP: \"PHASE_4_PRIORITIZATION_LOOP\",\n FINALIZE: \"PHASE_5_FINALIZE\",\n SELF_CHECK: \"PHASE_6_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":649,"content_sha256":"6058ab7e442b9ff74289d416b2aa53c9fe4e4c5c13475bd1db92652989e2a63c"},{"filename":"references/scripts/scope-decomposition-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/scope-decomposition-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n epicPlanCoordinatorSummarySchema,\n scopeDecompositionSummarySchema,\n storyPlanCoordinatorSummarySchema,\n storyPrioritizationWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport {\n createPlanningManifestSchema,\n createPlanningRuntimeStore,\n createPlanningState,\n} from \"../../planning-runtime/lib/store.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst scopeStore = createPlanningRuntimeStore({\n baseRootParts: [\".hex-skills\", \"scope-decomposition\", \"runtime\"],\n manifestSchema: createPlanningManifestSchema(\"scope_identifier\"),\n normalizeManifest(manifestInput, projectRoot) {\n const scopeIdentifier = manifestInput.scope_identifier || manifestInput.identifier || \"scope\";\n return {\n skill: \"ln-200\",\n mode: manifestInput.mode || \"scope_decomposition\",\n identifier: manifestInput.identifier || scopeIdentifier,\n scope_identifier: scopeIdentifier,\n task_provider: manifestInput.task_provider || \"unknown\",\n auto_approve: manifestInput.auto_approve === true,\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return createPlanningState(manifest, runId, PHASES.CONFIG, {\n scope_identifier: manifest.scope_identifier,\n discovery_summary: null,\n epic_summary: null,\n story_summaries: {},\n prioritization_enabled: false,\n expected_prioritization_epics: [],\n prioritization_summaries: {},\n scope_summary: null,\n });\n },\n pausedPhase: PHASES.PAUSED,\n resumablePhases: new Set(Object.values(PHASES).filter(p => p !== PHASES.PAUSED && p !== PHASES.DONE)),\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} = scopeStore;\n\nexport function recordEpicSummary(projectRoot, runId, summary) {\n return scopeStore.recordSummary(\n projectRoot,\n runId,\n summary,\n epicPlanCoordinatorSummarySchema,\n \"epic planning summary\",\n (state, nextSummary) => ({\n ...state,\n epic_summary: nextSummary,\n }),\n );\n}\n\nexport function recordStorySummary(projectRoot, runId, summary) {\n return scopeStore.recordSummary(\n projectRoot,\n runId,\n summary,\n storyPlanCoordinatorSummarySchema,\n \"story planning summary\",\n (state, nextSummary) => ({\n ...state,\n story_summaries: {\n ...state.story_summaries,\n [nextSummary.payload.epic_id]: nextSummary,\n },\n }),\n );\n}\n\nexport function recordPrioritizationSummary(projectRoot, runId, summary) {\n return scopeStore.recordSummary(\n projectRoot,\n runId,\n summary,\n storyPrioritizationWorkerSummarySchema,\n \"story prioritization summary\",\n (state, nextSummary) => ({\n ...state,\n prioritization_summaries: {\n ...(state.prioritization_summaries || {}),\n [nextSummary.payload.epic_id]: nextSummary,\n },\n }),\n );\n}\n\nexport function recordScopeSummary(projectRoot, runId, summary) {\n return scopeStore.recordCoordinatorSummary(\n projectRoot,\n runId,\n summary,\n scopeDecompositionSummarySchema,\n \"scope decomposition summary\",\n \"scope_summary\",\n );\n}\n","content_type":"text/javascript","language":"javascript","size":3866,"content_sha256":"10a8d03c8e6464152990981e937af3d673b0d352b8852408a3ac1498ef7b5174"},{"filename":"references/scripts/story-execution-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/story-execution-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordGroup,\n recordLoopHealth,\n recordStageSummary,\n recordWorker,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport {\n computeResumeAction,\n validateTransition,\n} from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n story: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n resolve: { type: \"boolean\", default: false },\n \"task-id\": { type: \"string\" },\n worker: { type: \"string\" },\n result: { type: \"string\" },\n \"from-status\": { type: \"string\" },\n \"to-status\": { type: \"string\" },\n \"group-id\": { type: \"string\" },\n scope: { type: \"string\" },\n \"scope-id\": { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-400\", values[\"run-id\"], values.story);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-400\");\n if (activeRuns.length > 1 && !values.story) {\n fail(\"Multiple active ln-400 runs found. Pass --story or --run-id.\");\n }\n fail(\"No active ln-400 run found. Pass --story or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n\n if (phase === PHASES.WORKTREE_SETUP) {\n nextState.worktree_ready = payload.worktree_ready === true;\n nextState.worktree_dir = payload.worktree_dir || nextState.worktree_dir || null;\n nextState.branch = payload.branch || nextState.branch || null;\n }\n\n if (phase === PHASES.SELECT_WORK) {\n nextState.current_task_id = payload.current_task_id || null;\n nextState.current_group_id = payload.current_group_id || null;\n if (payload.processable_counts) {\n nextState.processable_counts = payload.processable_counts;\n }\n }\n\n if (phase === PHASES.VERIFY_STATUSES) {\n nextState.current_task_id = null;\n nextState.current_group_id = null;\n nextState.inflight_workers = payload.inflight_workers || {};\n if (payload.processable_counts) {\n nextState.processable_counts = payload.processable_counts;\n }\n }\n\n if (phase === PHASES.SCENARIO_VALIDATION) {\n nextState.scenario_pass = payload.scenario_pass === true;\n nextState.validation_mode = payload.validation_mode || null;\n nextState.rework_tasks = payload.rework_tasks || [];\n }\n\n if (phase === PHASES.STORY_TO_REVIEW) {\n nextState.story_transition_done = payload.story_transition_done === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.story || !values[\"manifest-file\"]) {\n fail(\"start requires --story and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n story_id: values.story,\n identifier: values.story,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.story) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-400\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-400 runs found. Pass --story or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-400\", values.story);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n if (run.state.phase === PHASES.PAUSED && values.resolve) {\n const resumed = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n paused_reason: null,\n });\n if (resumed?.ok === false) {\n outputGuardFailure(output, resumed);\n }\n outputRuntimeState(output, run, resumed, { resumed_from: \"PAUSED\" });\n return;\n }\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-worker\") {\n if (!values[\"task-id\"]) {\n fail(\"record-worker requires --task-id\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorker(projectRoot, runId, values[\"task-id\"], payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-group\") {\n if (!values[\"group-id\"]) {\n fail(\"record-group requires --group-id\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordGroup(projectRoot, runId, {\n ...payload,\n group_id: values[\"group-id\"],\n });\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-stage-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordStageSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-loop-health\") {\n if (!values.scope) {\n fail(\"record-loop-health requires --scope\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordLoopHealth(projectRoot, runId, values.scope, values[\"scope-id\"], payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const { runId } = resolveRun(projectRoot);\n const result = pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-worker, record-group, record-stage-summary, record-loop-health, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":9993,"content_sha256":"c8b45cedf3d517e4a3720aaafbd54b68f0c2db4a36d0627a826276fd1b46d034"},{"filename":"references/scripts/story-execution-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-execution-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TASK_BOARD_STATUSES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst TASK_REVIEW_WORKER = \"ln-402\";\nconst TASK_EXECUTION_WORKERS = Object.freeze([\"ln-401\", \"ln-403\", \"ln-404\"]);\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.WORKTREE_SETUP])],\n [PHASES.WORKTREE_SETUP, new Set([PHASES.SELECT_WORK])],\n [PHASES.SELECT_WORK, new Set([PHASES.TASK_EXECUTION, PHASES.GROUP_EXECUTION, PHASES.STORY_TO_REVIEW])],\n [PHASES.TASK_EXECUTION, new Set([PHASES.VERIFY_STATUSES])],\n [PHASES.GROUP_EXECUTION, new Set([PHASES.VERIFY_STATUSES])],\n [PHASES.VERIFY_STATUSES, new Set([PHASES.SELECT_WORK, PHASES.SCENARIO_VALIDATION])],\n [PHASES.SCENARIO_VALIDATION, new Set([PHASES.SELECT_WORK, PHASES.STORY_TO_REVIEW])],\n [PHASES.STORY_TO_REVIEW, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction hasProcessableWork(counts) {\n const next = counts || {};\n return Number(next.todo || 0) > 0\n || Number(next.to_review || 0) > 0\n || Number(next.to_rework || 0) > 0;\n}\n\nfunction hasInflightWorkers(state) {\n return Object.keys(state.inflight_workers || {}).length > 0;\n}\n\nfunction getTaskWorkerResults(state, taskId) {\n return state.worker_results_by_task?.[taskId] || {};\n}\n\nfunction getReviewSummary(state, taskId) {\n return getTaskWorkerResults(state, taskId)[TASK_REVIEW_WORKER] || null;\n}\n\nfunction hasReviewOutcome(state, taskId) {\n const reviewSummary = getReviewSummary(state, taskId);\n const toStatus = reviewSummary?.payload?.to_status;\n return toStatus === TASK_BOARD_STATUSES.DONE || toStatus === TASK_BOARD_STATUSES.TO_REWORK;\n}\n\nfunction hasExecutionSummary(state, taskId) {\n const taskWorkerResults = getTaskWorkerResults(state, taskId);\n return TASK_EXECUTION_WORKERS.some(worker => Boolean(taskWorkerResults[worker]));\n}\n\nfunction getProcessedTaskIds(state) {\n const processed = new Set([\n ...Object.keys(state.worker_results_by_task || {}),\n ...Object.keys(state.tasks || {}),\n ]);\n for (const group of Object.values(state.groups || {})) {\n for (const taskId of group.task_ids || []) {\n processed.add(taskId);\n }\n }\n return Array.from(processed);\n}\n\nfunction getMissingReviewTasks(state, taskIds) {\n return (taskIds || []).filter(taskId => !hasReviewOutcome(state, taskId));\n}\n\nfunction hasCompletedStage2Summary(state) {\n return state.stage_summary?.summary_kind === \"pipeline-stage\"\n && state.stage_summary?.payload?.stage === 2\n && state.stage_summary?.payload?.status === \"completed\";\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n\n if (toPhase === PHASES.SELECT_WORK && state.phase === PHASES.WORKTREE_SETUP && !state.worktree_ready) {\n return { ok: false, error: \"Worktree setup not checkpointed as ready\" };\n }\n\n if (toPhase === PHASES.TASK_EXECUTION && !state.current_task_id) {\n return { ok: false, error: \"No selected task recorded for task execution\" };\n }\n\n if (toPhase === PHASES.GROUP_EXECUTION && !state.current_group_id) {\n return { ok: false, error: \"No selected group recorded for group execution\" };\n }\n\n if (toPhase === PHASES.VERIFY_STATUSES && state.phase === PHASES.TASK_EXECUTION) {\n if (!state.current_task_id) {\n return { ok: false, error: \"No selected task recorded for status verification\" };\n }\n if (!hasReviewOutcome(state, state.current_task_id)) {\n return { ok: false, error: `ln-402 review summary missing for task ${state.current_task_id}` };\n }\n }\n\n if (toPhase === PHASES.VERIFY_STATUSES && state.phase === PHASES.GROUP_EXECUTION) {\n const groupTaskIds = state.groups?.[state.current_group_id]?.task_ids || [];\n const missingReviewTasks = getMissingReviewTasks(state, groupTaskIds);\n if (missingReviewTasks.length > 0) {\n return { ok: false, error: `ln-402 review summaries missing for group tasks: ${missingReviewTasks.join(\", \")}` };\n }\n }\n\n if (toPhase === PHASES.SCENARIO_VALIDATION) {\n if (hasProcessableWork(state.processable_counts)) {\n return { ok: false, error: \"Processable tasks remain; cannot start scenario validation\" };\n }\n if (hasInflightWorkers(state)) {\n return { ok: false, error: \"Parallel workers still in flight\" };\n }\n const missingReviewTasks = getMissingReviewTasks(state, getProcessedTaskIds(state));\n if (missingReviewTasks.length > 0) {\n return { ok: false, error: `Latest ln-402 summaries missing for tasks: ${missingReviewTasks.join(\", \")}` };\n }\n }\n\n if (toPhase === PHASES.STORY_TO_REVIEW) {\n if (hasProcessableWork(state.processable_counts)) {\n return { ok: false, error: \"Processable tasks remain; cannot move Story to To Review\" };\n }\n if (hasInflightWorkers(state)) {\n return { ok: false, error: \"Parallel workers still in flight\" };\n }\n if (state.phase === PHASES.SCENARIO_VALIDATION && !state.scenario_pass) {\n return { ok: false, error: \"Scenario validation must pass before Story To Review\" };\n }\n }\n\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.story_transition_done) {\n return { ok: false, error: \"Story transition to To Review not recorded\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n if (!hasCompletedStage2Summary(state)) {\n return { ok: false, error: \"Stage 2 coordinator artifact not recorded\" };\n }\n const missingReviewTasks = getMissingReviewTasks(state, getProcessedTaskIds(state));\n if (missingReviewTasks.length > 0) {\n return { ok: false, error: `Latest ln-402 summaries missing for tasks: ${missingReviewTasks.join(\", \")}` };\n }\n }\n\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.WORKTREE_SETUP && !state.worktree_ready) {\n return \"Finish worktree setup and checkpoint PHASE_2_WORKTREE_SETUP\";\n }\n if (state.phase === PHASES.SELECT_WORK) {\n if (hasProcessableWork(state.processable_counts)) {\n return \"Select the next task or parallel group and checkpoint PHASE_3_SELECT_WORK\";\n }\n return `Advance to ${PHASES.STORY_TO_REVIEW}`;\n }\n if (state.phase === PHASES.TASK_EXECUTION && state.current_task_id) {\n if (!hasReviewOutcome(state, state.current_task_id)) {\n if (hasExecutionSummary(state, state.current_task_id)) {\n return `Record ln-402 summary for task ${state.current_task_id} before status verification`;\n }\n return `Record worker summary for task ${state.current_task_id} before review`;\n }\n return `Checkpoint ${PHASES.TASK_EXECUTION} and advance to ${PHASES.VERIFY_STATUSES}`;\n }\n if (state.phase === PHASES.GROUP_EXECUTION && state.current_group_id) {\n const groupTaskIds = state.groups?.[state.current_group_id]?.task_ids || [];\n const missingReviewTasks = getMissingReviewTasks(state, groupTaskIds);\n if (missingReviewTasks.length > 0) {\n return `Record missing ln-402 summaries for group ${state.current_group_id} before status verification`;\n }\n return `Checkpoint ${PHASES.GROUP_EXECUTION} and advance to ${PHASES.VERIFY_STATUSES}`;\n }\n if (state.phase === PHASES.VERIFY_STATUSES) {\n const missingReviewTasks = getMissingReviewTasks(state, getProcessedTaskIds(state));\n if (missingReviewTasks.length > 0) {\n return `Record latest ln-402 summaries before status verification: ${missingReviewTasks.join(\", \")}`;\n }\n if (hasProcessableWork(state.processable_counts)) {\n return \"Re-read task statuses, checkpoint PHASE_6_VERIFY_STATUSES, then advance to PHASE_3_SELECT_WORK\";\n }\n return `Advance to ${PHASES.SCENARIO_VALIDATION}`;\n }\n if (state.phase === PHASES.SCENARIO_VALIDATION) {\n if (state.scenario_pass) {\n return `Advance to ${PHASES.STORY_TO_REVIEW}`;\n }\n if (state.scenario_pass === false) {\n return \"Scenario validation failed — advance to PHASE_3_SELECT_WORK for rework\";\n }\n return \"Run scenario validation and checkpoint PHASE_6B_SCENARIO_VALIDATION\";\n }\n if (state.phase === PHASES.STORY_TO_REVIEW && !state.story_transition_done) {\n return `Move Story to ${TASK_BOARD_STATUSES.TO_REVIEW} and checkpoint ${PHASES.STORY_TO_REVIEW}`;\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n if (!hasCompletedStage2Summary(state)) {\n return \"Record Stage 2 coordinator artifact before completion\";\n }\n return \"Fix self-check failures, then checkpoint PHASE_8_SELF_CHECK with pass=true\";\n }\n\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":10377,"content_sha256":"4a718f9972a8382ab40c863287db9f23d07d16817512121188dfb87e6c0c9408"},{"filename":"references/scripts/story-execution-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-execution-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n WORKTREE_SETUP: \"PHASE_2_WORKTREE_SETUP\",\n SELECT_WORK: \"PHASE_3_SELECT_WORK\",\n TASK_EXECUTION: \"PHASE_4_TASK_EXECUTION\",\n GROUP_EXECUTION: \"PHASE_5_GROUP_EXECUTION\",\n VERIFY_STATUSES: \"PHASE_6_VERIFY_STATUSES\",\n SCENARIO_VALIDATION: \"PHASE_6B_SCENARIO_VALIDATION\",\n STORY_TO_REVIEW: \"PHASE_7_STORY_TO_REVIEW\",\n SELF_CHECK: \"PHASE_8_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":796,"content_sha256":"0b86a7fafc7eecae9a919feb3d4d5ae07bc2fb29c218f34f0476b59c1694f936"},{"filename":"references/scripts/story-execution-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-execution-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n pipelineStageCoordinatorSummarySchema,\n storyGroupRecordSchema,\n taskStatusWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { writeRuntimeArtifactJson } from \"../../coordinator-runtime/lib/artifacts.mjs\";\nimport {\n STORY_EXECUTION_GROUP_STATUSES,\n TASK_BOARD_STATUSES,\n} from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { updateLoopHealthMap } from \"../../coordinator-runtime/lib/loop-health.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst TASK_REVIEW_WORKER = \"ln-402\";\nconst TASK_LEDGER_PRIORITY = Object.freeze([\n TASK_REVIEW_WORKER,\n \"ln-403\",\n \"ln-404\",\n \"ln-401\",\n]);\n\nconst executionManifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"story_id\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n story_id: { type: \"string\" },\n task_provider: { type: \"string\" },\n project_root: { type: \"string\" },\n worktree_dir: { type: \"string\" },\n branch: { type: \"string\" },\n execution_mode: { type: \"string\" },\n task_inventory_snapshot: { type: \"array\" },\n parallel_group_policy: { type: \"object\" },\n status_transition_policy: { type: \"object\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst executionStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"story-execution\", \"runtime\"],\n manifestSchema: executionManifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-400\",\n mode: manifestInput.mode || \"story_execution\",\n identifier: manifestInput.story_id || manifestInput.identifier,\n story_id: manifestInput.story_id || manifestInput.identifier,\n task_provider: manifestInput.task_provider || \"unknown\",\n project_root: resolve(projectRoot || process.cwd()),\n worktree_dir: manifestInput.worktree_dir || null,\n branch: manifestInput.branch || null,\n execution_mode: manifestInput.execution_mode || \"execute\",\n task_inventory_snapshot: manifestInput.task_inventory_snapshot || [],\n parallel_group_policy: manifestInput.parallel_group_policy || {},\n status_transition_policy: manifestInput.status_transition_policy || {},\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n story_id: manifest.story_id,\n phase: PHASES.CONFIG,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n current_task_id: null,\n current_group_id: null,\n processable_counts: {\n todo: 0,\n to_review: 0,\n to_rework: 0,\n },\n rework_counter_by_task: {},\n inflight_workers: {},\n worker_results_by_task: {},\n tasks: {},\n groups: {},\n worktree_ready: false,\n worktree_dir: manifest.worktree_dir,\n branch: manifest.branch,\n story_transition_done: false,\n stage_summary: null,\n loop_health: {\n tasks: {},\n groups: {},\n scenario: {},\n },\n self_check_passed: false,\n final_result: null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = executionStore;\n\nfunction loopHealthBucket(scope) {\n if (scope === \"task\") return \"tasks\";\n if (scope === \"group\") return \"groups\";\n if (scope === \"scenario\") return \"scenario\";\n return null;\n}\n\nfunction selectTaskLedgerSummary(workerResultsBySkill = {}) {\n for (const worker of TASK_LEDGER_PRIORITY) {\n if (workerResultsBySkill[worker]) {\n return workerResultsBySkill[worker];\n }\n }\n return null;\n}\n\nfunction buildTaskLedgerEntry(taskId, workerResultsBySkill = {}, existingEntry = null) {\n const selectedSummary = selectTaskLedgerSummary(workerResultsBySkill);\n if (!selectedSummary) {\n return existingEntry;\n }\n const payload = selectedSummary.payload || {};\n return {\n task_id: taskId,\n worker: payload.worker || selectedSummary.producer_skill || null,\n result: payload.result || null,\n from_status: payload.from_status || null,\n to_status: payload.to_status || null,\n tests_run: payload.tests_run || [],\n files_changed: payload.files_changed || [],\n issues: payload.issues || [],\n score: payload.score ?? null,\n comment_path: payload.comment_path || null,\n error: payload.error || null,\n completed_at: selectedSummary.produced_at || new Date().toISOString(),\n };\n}\n\nfunction isSameSummary(previousSummary, nextSummary) {\n return previousSummary?.producer_skill === nextSummary?.producer_skill\n && previousSummary?.produced_at === nextSummary?.produced_at\n && previousSummary?.payload?.to_status === nextSummary?.payload?.to_status;\n}\n\nfunction applyReviewOutcomeToCounters(nextCounters, taskId, previousSummary, summary) {\n if (!summary || summary.producer_skill !== TASK_REVIEW_WORKER) {\n return nextCounters;\n }\n if (isSameSummary(previousSummary, summary)) {\n return nextCounters;\n }\n const toStatus = summary.payload?.to_status;\n if (toStatus === TASK_BOARD_STATUSES.TO_REWORK) {\n return {\n ...nextCounters,\n [taskId]: Number(nextCounters[taskId] || 0) + 1,\n };\n }\n if (toStatus === TASK_BOARD_STATUSES.DONE) {\n return {\n ...nextCounters,\n [taskId]: 0,\n };\n }\n return nextCounters;\n}\n\nexport function recordWorker(projectRoot, runId, taskId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `Worker summary run_id must match runtime run_id (${runId})` };\n }\n if (summary?.identifier !== taskId) {\n return { ok: false, error: `Worker summary identifier must match task_id (${taskId})` };\n }\n const validation = assertSchema(taskStatusWorkerSummarySchema, summary, \"task-status worker summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const artifactPath = writeRuntimeArtifactJson(projectRoot, runId, summary.summary_kind, summary.identifier, summary);\n const nextSummary = {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: artifactPath,\n },\n };\n const previousTaskResults = state.worker_results_by_task?.[taskId] || {};\n const nextTaskResults = {\n ...previousTaskResults,\n [nextSummary.producer_skill]: nextSummary,\n };\n const nextCounters = applyReviewOutcomeToCounters(\n { ...state.rework_counter_by_task },\n taskId,\n previousTaskResults[TASK_REVIEW_WORKER] || null,\n nextSummary,\n );\n return {\n ...state,\n current_task_id: taskId,\n worker_results_by_task: {\n ...state.worker_results_by_task,\n [taskId]: nextTaskResults,\n },\n tasks: {\n ...state.tasks,\n [taskId]: buildTaskLedgerEntry(taskId, nextTaskResults, state.tasks?.[taskId] || null),\n },\n rework_counter_by_task: nextCounters,\n };\n });\n}\n\nexport function recordGroup(projectRoot, runId, groupRecord) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(storyGroupRecordSchema, groupRecord, \"story group record\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n current_group_id: groupRecord.group_id,\n inflight_workers: groupRecord.inflight_workers || {},\n groups: {\n ...state.groups,\n [groupRecord.group_id]: {\n group_id: groupRecord.group_id,\n task_ids: groupRecord.task_ids || [],\n status: groupRecord.status || STORY_EXECUTION_GROUP_STATUSES.COMPLETED,\n result: groupRecord.result || null,\n completed_at: groupRecord.completed_at || new Date().toISOString(),\n },\n },\n }));\n}\n\nexport function recordStageSummary(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `Stage summary run_id must match runtime run_id (${runId})` };\n }\n const validation = assertSchema(pipelineStageCoordinatorSummarySchema, summary, \"pipeline stage coordinator summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const artifactIdentifier = `${summary.identifier}-stage-${summary.payload.stage}`;\n const artifactPath = writeRuntimeArtifactJson(projectRoot, runId, summary.summary_kind, artifactIdentifier, summary);\n return {\n ...state,\n stage_summary: {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: artifactPath,\n },\n },\n };\n });\n}\n\nexport function recordLoopHealth(projectRoot, runId, scope, scopeId, signal) {\n const bucket = loopHealthBucket(scope);\n if (!bucket) {\n return { ok: false, error: \"Loop health scope must be task, group, or scenario\" };\n }\n const key = scope === \"scenario\" ? (scopeId || \"default\") : scopeId;\n if (!key) {\n return { ok: false, error: \"Loop health scope id is required\" };\n }\n\n let recordedEntry = null;\n let pauseRecommendation = null;\n const result = updateState(projectRoot, runId, state => {\n const currentLoopHealth = state.loop_health || {};\n const updated = updateLoopHealthMap(currentLoopHealth[bucket] || {}, key, signal);\n recordedEntry = updated.entry;\n pauseRecommendation = updated.pause;\n const pauseState = updated.pause.pause\n ? {\n phase: PHASES.PAUSED,\n paused_reason: `${scope}:${key} loop health pause - ${updated.pause.reason}`,\n pending_decision: null,\n }\n : {};\n return {\n ...state,\n ...pauseState,\n loop_health: {\n tasks: currentLoopHealth.tasks || {},\n groups: currentLoopHealth.groups || {},\n scenario: currentLoopHealth.scenario || {},\n [bucket]: updated.map,\n },\n };\n }, { eventType: \"LOOP_HEALTH_RECORDED\" });\n if (!result.ok) {\n return result;\n }\n return {\n ok: true,\n state: result.state,\n loop_health: recordedEntry,\n pause: pauseRecommendation,\n };\n}\n\nexport {\n readJsonFile,\n};\n","content_type":"text/javascript","language":"javascript","size":12170,"content_sha256":"40db68957c99911b1e962e69a0751c535f4ebcbfeab5fad1297332bd8c8848e9"},{"filename":"references/scripts/story-execution-runtime/test/loop-health.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/story-execution-runtime/test/loop-health.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createJsonCliRunner } from \"../../coordinator-runtime/test/cli-test-helpers.mjs\";\nimport { PHASES } from \"../lib/phases.mjs\";\n\nconst cliPath = join(fileURLToPath(new URL(\"..\", import.meta.url)), \"cli.mjs\");\nconst projectRoot = mkdtempSync(join(tmpdir(), \"story-loop-health-\"));\nconst run = createJsonCliRunner(cliPath, projectRoot);\n\nfunction assert(condition, message) {\n if (!condition) {\n throw new Error(message);\n }\n}\n\ntry {\n const manifestPath = join(projectRoot, \"manifest.json\");\n writeFileSync(manifestPath, JSON.stringify({\n task_provider: \"file\",\n worktree_dir: \".hex-skills/worktrees/story-PROJ-LOOP\",\n branch: \"feature/proj-loop-story\",\n }, null, 2));\n const started = run([\"start\", \"--project-root\", projectRoot, \"--story\", \"PROJ-LOOP\", \"--manifest-file\", manifestPath]);\n assert(started.ok === true, \"runtime should start\");\n\n let third = null;\n for (let i = 0; i \u003c 3; i += 1) {\n third = run([\n \"record-loop-health\",\n \"--project-root\", projectRoot,\n \"--story\", \"PROJ-LOOP\",\n \"--scope\", \"task\",\n \"--scope-id\", \"TASK-1\",\n \"--payload\", JSON.stringify({ error: \"ASSERT same task failed\", progress_detected: false }),\n ]);\n }\n assert(third.pause.pause === true, \"repeated same task failure should pause\");\n assert(third.state.phase === PHASES.PAUSED, \"runtime phase should be PAUSED\");\n\n const resumed = run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-LOOP\", \"--to\", PHASES.DISCOVERY, \"--resolve\"]);\n assert(resumed.ok === true, \"runtime should resume after explicit resolve\");\n const progressed = run([\n \"record-loop-health\",\n \"--project-root\", projectRoot,\n \"--story\", \"PROJ-LOOP\",\n \"--scope\", \"task\",\n \"--scope-id\", \"TASK-1\",\n \"--payload\", JSON.stringify({ error: \"ASSERT same task failed\", progress_detected: true }),\n ]);\n assert(progressed.loop_health.no_progress_count === 0, \"progress should reset no-progress counter\");\n assert(progressed.loop_health.same_error_count === 0, \"progress should reset same-error counter\");\n\n process.stdout.write(\"story execution loop-health tests passed\\n\");\n} finally {\n rmSync(projectRoot, { recursive: true, force: true });\n}\n","content_type":"text/javascript","language":"javascript","size":2649,"content_sha256":"764399aa1521618ea692d012952faf8003ba752d47dbb73677e8ec3f222aa96a"},{"filename":"references/scripts/story-gate-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/story-gate-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordQuality,\n recordStageSummary,\n recordTestStatus,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n outputGuardFailure,\n outputInactiveRuntime,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport {\n computeResumeAction,\n validateTransition,\n} from \"./lib/guards.mjs\";\nimport { STORY_GATE_FINALIZATION_STATUSES } from \"../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n story: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n resolve: { type: \"boolean\", default: false },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-500\", values[\"run-id\"], values.story);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-500\");\n if (activeRuns.length > 1 && !values.story) {\n fail(\"Multiple active ln-500 runs found. Pass --story or --run-id.\");\n }\n fail(\"No active ln-500 run found. Pass --story or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n\n if ([PHASES.QUALITY_CHECKS, PHASES.TEST_PLANNING].includes(phase)\n && payload.child_run?.worker) {\n nextState.child_runs = {\n ...(nextState.child_runs || {}),\n [payload.child_run.worker]: payload.child_run,\n };\n }\n\n if (phase === PHASES.FAST_TRACK) {\n nextState.fast_track = payload.fast_track === true;\n }\n\n if (phase === PHASES.QUALITY_CHECKS) {\n nextState.quality_summary = payload.quality_summary || nextState.quality_summary;\n nextState.quality_score = payload.quality_score ?? nextState.quality_score;\n }\n\n if (phase === PHASES.TEST_PLANNING) {\n nextState.test_planner_invoked = payload.test_planner_invoked === true || nextState.test_planner_invoked;\n nextState.test_task_id = payload.test_task_id || nextState.test_task_id;\n nextState.test_task_status = payload.test_task_status || nextState.test_task_status;\n }\n\n if (phase === PHASES.TEST_VERIFICATION) {\n nextState.test_task_status = payload.test_task_status || nextState.test_task_status;\n }\n\n if (phase === PHASES.VERDICT) {\n nextState.quality_score = payload.quality_score ?? nextState.quality_score;\n nextState.nfr_validation = payload.nfr_validation || nextState.nfr_validation;\n nextState.fix_tasks_created = payload.fix_tasks_created || nextState.fix_tasks_created;\n nextState.final_result = payload.final_result || payload.verdict || nextState.final_result;\n }\n\n if (phase === PHASES.FINALIZATION) {\n nextState.branch_finalized = payload.branch_finalized === true || payload.status === STORY_GATE_FINALIZATION_STATUSES.SKIPPED_BY_VERDICT;\n nextState.story_final_status = payload.story_final_status || nextState.story_final_status;\n }\n\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.story || !values[\"manifest-file\"]) {\n fail(\"start requires --story and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n story_id: values.story,\n identifier: values.story,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.story) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-500\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-500 runs found. Pass --story or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-500\", values.story);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n if (run.state.phase === PHASES.PAUSED && values.resolve) {\n const resumed = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n paused_reason: null,\n });\n if (resumed?.ok === false) {\n outputGuardFailure(output, resumed);\n }\n outputRuntimeState(output, run, resumed, { resumed_from: \"PAUSED\" });\n return;\n }\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-quality\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordQuality(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-test-status\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordTestStatus(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-stage-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordStageSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const { runId } = resolveRun(projectRoot);\n const result = pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-quality, record-test-status, record-stage-summary, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":9408,"content_sha256":"b48b2b0f0022f0cece2bc8ce0316edbf9d4f74aac25427cb3f433719e4fdbfb7"},{"filename":"references/scripts/story-gate-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-gate-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n STORY_GATE_COMPLETED_TEST_STATUS_LIST,\n STORY_GATE_PRE_VERIFICATION_ALLOWED_TEST_STATUS_LIST,\n STORY_GATE_VERDICT_LIST,\n} from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.FAST_TRACK])],\n [PHASES.FAST_TRACK, new Set([PHASES.QUALITY_CHECKS])],\n [PHASES.QUALITY_CHECKS, new Set([PHASES.TEST_PLANNING, PHASES.VERDICT])],\n [PHASES.TEST_PLANNING, new Set([PHASES.TEST_VERIFICATION])],\n [PHASES.TEST_VERIFICATION, new Set([PHASES.VERDICT])],\n [PHASES.VERDICT, new Set([PHASES.FINALIZATION])],\n [PHASES.FINALIZATION, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction childRunMessage(state, worker, suffix) {\n const childRun = state.child_runs?.[worker];\n if (!childRun?.run_id) {\n return null;\n }\n return `Check child runtime ${childRun.run_id} for ${worker}${suffix}`;\n}\n\nfunction verdictAllowsFinalization(verdict) {\n return STORY_GATE_VERDICT_LIST.includes(verdict);\n}\n\nfunction hasCompletedStage3Summary(state) {\n return state.stage_summary?.summary_kind === \"pipeline-stage\"\n && state.stage_summary?.payload?.stage === 3\n && state.stage_summary?.payload?.status === \"completed\";\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n\n if (toPhase === PHASES.TEST_PLANNING || toPhase === PHASES.VERDICT) {\n if (!state.quality_summary) {\n return { ok: false, error: \"Quality summary missing\" };\n }\n }\n\n if (toPhase === PHASES.TEST_VERIFICATION && !state.test_planner_invoked && !STORY_GATE_PRE_VERIFICATION_ALLOWED_TEST_STATUS_LIST.includes(state.test_task_status || \"\")) {\n return { ok: false, error: \"Test planner not recorded before test verification\" };\n }\n\n if (toPhase === PHASES.VERDICT && state.phase === PHASES.TEST_VERIFICATION && !STORY_GATE_COMPLETED_TEST_STATUS_LIST.includes(state.test_task_status || \"\")) {\n return { ok: false, error: \"Test verification not complete\" };\n }\n\n if (toPhase === PHASES.FINALIZATION && !verdictAllowsFinalization(state.final_result)) {\n return { ok: false, error: \"Final verdict not recorded\" };\n }\n\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.story_final_status) {\n return { ok: false, error: \"Final Story status not recorded\" };\n }\n if (!hasCompletedStage3Summary(state)) {\n return { ok: false, error: \"Stage 3 coordinator artifact not recorded\" };\n }\n }\n\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.QUALITY_CHECKS && !state.quality_summary) {\n return childRunMessage(state, \"ln-510\", \" or record its coordinator summary before test planning\")\n || \"Persist ln-510 summary, then checkpoint PHASE_3_QUALITY_CHECKS\";\n }\n if (state.phase === PHASES.TEST_PLANNING\n && !state.test_planner_invoked\n && !STORY_GATE_PRE_VERIFICATION_ALLOWED_TEST_STATUS_LIST.includes(state.test_task_status || \"\")) {\n return childRunMessage(state, \"ln-520\", \" or record its coordinator summary before test verification\")\n || \"Record ln-520 summary or reused terminal test state before test verification\";\n }\n if (state.phase === PHASES.TEST_VERIFICATION && !STORY_GATE_COMPLETED_TEST_STATUS_LIST.includes(state.test_task_status || \"\")) {\n return \"Wait for the test task to finish, then resume PHASE_5_TEST_VERIFICATION\";\n }\n if (state.phase === PHASES.VERDICT && !state.final_result) {\n return \"Calculate final verdict and checkpoint PHASE_6_VERDICT\";\n }\n if (state.phase === PHASES.FINALIZATION && !state.story_final_status) {\n return \"Record Story status/finalization result and checkpoint PHASE_7_FINALIZATION\";\n }\n if (state.phase === PHASES.SELF_CHECK && !hasCompletedStage3Summary(state)) {\n return \"Record the Stage 3 coordinator artifact before completion\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return \"Fix self-check failures, then checkpoint PHASE_8_SELF_CHECK with pass=true\";\n }\n\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":5578,"content_sha256":"45ed3b3173e9ead02d3893b1616053850738c8a7572835025db3d1f6a0acd420"},{"filename":"references/scripts/story-gate-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-gate-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n FAST_TRACK: \"PHASE_2_FAST_TRACK\",\n QUALITY_CHECKS: \"PHASE_3_QUALITY_CHECKS\",\n TEST_PLANNING: \"PHASE_4_TEST_PLANNING\",\n TEST_VERIFICATION: \"PHASE_5_TEST_VERIFICATION\",\n VERDICT: \"PHASE_6_VERDICT\",\n FINALIZATION: \"PHASE_7_FINALIZATION\",\n SELF_CHECK: \"PHASE_8_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":712,"content_sha256":"0cc16e2ed1eb3ca10789e0163dc62a2a4e89416469a727034727631956ecb990"},{"filename":"references/scripts/story-gate-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-gate-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n pipelineStageCoordinatorSummarySchema,\n qualitySummarySchema,\n testSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { writeRuntimeArtifactJson } from \"../../coordinator-runtime/lib/artifacts.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst gateManifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"story_id\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n story_id: { type: \"string\" },\n task_provider: { type: \"string\" },\n project_root: { type: \"string\" },\n worktree_dir: { type: \"string\" },\n branch: { type: \"string\" },\n fast_track_policy: { type: \"object\" },\n nfr_policy: { type: \"object\" },\n test_task_policy: { type: \"object\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst gateStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"story-gate\", \"runtime\"],\n manifestSchema: gateManifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-500\",\n mode: manifestInput.mode || \"story_gate\",\n identifier: manifestInput.story_id || manifestInput.identifier,\n story_id: manifestInput.story_id || manifestInput.identifier,\n task_provider: manifestInput.task_provider || \"unknown\",\n project_root: resolve(projectRoot || process.cwd()),\n worktree_dir: manifestInput.worktree_dir || null,\n branch: manifestInput.branch || null,\n fast_track_policy: manifestInput.fast_track_policy || {},\n nfr_policy: manifestInput.nfr_policy || {},\n test_task_policy: manifestInput.test_task_policy || {},\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n story_id: manifest.story_id,\n phase: PHASES.CONFIG,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n fast_track: false,\n quality_summary: null,\n child_runs: {},\n test_task_id: null,\n test_task_status: null,\n test_planner_invoked: false,\n quality_score: null,\n nfr_validation: {},\n fix_tasks_created: [],\n branch_finalized: false,\n story_final_status: null,\n stage_summary: null,\n self_check_passed: false,\n final_result: null,\n worktree_dir: manifest.worktree_dir,\n branch: manifest.branch,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = gateStore;\n\nexport function recordQuality(projectRoot, runId, qualitySummary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(qualitySummarySchema, qualitySummary, \"quality summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n quality_summary: qualitySummary,\n quality_score: qualitySummary.quality_score ?? state.quality_score,\n }));\n}\n\nexport function recordTestStatus(projectRoot, runId, testSummary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(testSummarySchema, testSummary, \"test summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n test_task_id: testSummary.test_task_id || state.test_task_id,\n test_task_status: testSummary.status || state.test_task_status,\n test_planner_invoked: state.test_planner_invoked || Boolean(testSummary.planner_invoked),\n }));\n}\n\nexport function recordStageSummary(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n if (summary?.run_id !== runId) {\n return { ok: false, error: `Stage summary run_id must match runtime run_id (${runId})` };\n }\n const validation = assertSchema(pipelineStageCoordinatorSummarySchema, summary, \"pipeline stage coordinator summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => {\n const artifactIdentifier = `${summary.identifier}-stage-${summary.payload.stage}`;\n const artifactPath = writeRuntimeArtifactJson(projectRoot, runId, summary.summary_kind, artifactIdentifier, summary);\n return {\n ...state,\n stage_summary: {\n ...summary,\n payload: {\n ...summary.payload,\n artifact_path: artifactPath,\n },\n },\n };\n });\n}\n\nexport {\n readJsonFile,\n};\n","content_type":"text/javascript","language":"javascript","size":5818,"content_sha256":"1e246fe2c2a8114e92184d2d72b3305ce3fec7616c28aea98e7dc1c5d428cda3"},{"filename":"references/scripts/story-planning-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/story-planning-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n recordEpic,\n recordPlanSummary,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\nimport {\n advancePlanningRun,\n checkpointPlanningRun,\n completePlanningRun,\n loadPlanningStatusRun,\n outputInactiveRuntime,\n outputPlanningStatus,\n pausePlanningRun,\n resolvePlanningRunOrFail,\n} from \"../planning-runtime/lib/cli.mjs\";\nimport { PLANNING_PROGRESS_STATUSES } from \"../coordinator-runtime/lib/runtime-constants.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n epic: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n return resolvePlanningRunOrFail({\n projectRoot,\n skill: \"ln-220\",\n runId: values[\"run-id\"],\n identifier: values.epic ? `epic-${values.epic}` : null,\n identifierFlag: \"epic\",\n listActiveRuns,\n resolveRunId,\n loadRun,\n fail,\n });\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n\n if (phase === PHASES.CONTEXT_ASSEMBLY) {\n nextState.context_ready = payload.context_ready === true;\n }\n if (phase === PHASES.RESEARCH) {\n nextState.research_status = payload.research_status || PLANNING_PROGRESS_STATUSES.COMPLETED;\n nextState.research_file = payload.research_file || nextState.research_file;\n }\n if (phase === PHASES.PLAN) {\n nextState.ideal_plan_summary = payload.ideal_plan_summary || payload.plan_summary || payload;\n }\n if (phase === PHASES.ROUTING) {\n nextState.routing_summary = payload.routing_summary || payload;\n }\n if (phase === PHASES.MODE_DETECTION) {\n nextState.epic_group_modes = payload.epic_group_modes || payload.group_modes || {};\n }\n if (phase === PHASES.FINALIZE) {\n nextState.final_result = payload.final_result || nextState.final_result;\n if (payload.template_compliance_passed === true) {\n nextState.template_compliance_passed = true;\n }\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.epic || !values[\"manifest-file\"]) {\n fail(\"start requires --epic and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n epic_id: values.epic,\n identifier: `epic-${values.epic}`,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n const run = loadPlanningStatusRun({\n projectRoot,\n skill: \"ln-220\",\n runId: values[\"run-id\"],\n identifier: values.epic ? `epic-${values.epic}` : null,\n identifierFlag: \"epic\",\n listActiveRuns,\n loadRun,\n loadActiveRun,\n output,\n });\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputPlanningStatus(projectRoot, run, runtimePaths, computeResumeAction, output);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n advancePlanningRun(projectRoot, runId, run, values.to, validateTransition, saveState, PHASES.DONE, output);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n checkpointPlanningRun(projectRoot, runId, run, values.phase, payload, checkpointPhase, saveState, applyCheckpointToState, fail, output);\n return;\n }\n\n if (command === \"record-epic\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordEpic(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"set-decision\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordDecision(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-plan-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordPlanSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n pausePlanningRun(projectRoot, runId, payload, values.reason, pauseRun, setPendingDecision, fail, output);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n completePlanningRun(projectRoot, runId, run, validateTransition, completeRun, PHASES.DONE, fail, output);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-epic, record-plan-summary, set-decision, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":6794,"content_sha256":"4e5170f849bbeb4de04acebc8733e40cbc211aada70a5c07d8a3d4e48e254d21"},{"filename":"references/scripts/story-planning-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-planning-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n computePlanningBaseResumeAction,\n hasChoice,\n validatePlanningBaseTransition,\n} from \"../../planning-runtime/lib/guards.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.CONTEXT_ASSEMBLY])],\n [PHASES.CONTEXT_ASSEMBLY, new Set([PHASES.RESEARCH])],\n [PHASES.RESEARCH, new Set([PHASES.PLAN])],\n [PHASES.PLAN, new Set([PHASES.ROUTING])],\n [PHASES.ROUTING, new Set([PHASES.MODE_DETECTION])],\n [PHASES.MODE_DETECTION, new Set([PHASES.DELEGATE])],\n [PHASES.DELEGATE, new Set([PHASES.FINALIZE])],\n [PHASES.FINALIZE, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const base = validatePlanningBaseTransition(state, checkpoints, toPhase, ALLOWED_TRANSITIONS);\n if (!base.ok) {\n return base;\n }\n if (toPhase === PHASES.RESEARCH && !state.context_ready) {\n return { ok: false, error: \"Context assembly not recorded\" };\n }\n if (toPhase === PHASES.PLAN && !state.research_status) {\n return { ok: false, error: \"Research result not recorded\" };\n }\n if (toPhase === PHASES.ROUTING && !state.ideal_plan_summary) {\n return { ok: false, error: \"Ideal plan summary missing\" };\n }\n if (toPhase === PHASES.MODE_DETECTION && !state.routing_summary) {\n return { ok: false, error: \"Routing summary missing\" };\n }\n if (toPhase === PHASES.DELEGATE) {\n if (Object.keys(state.epic_group_modes || {}).length === 0) {\n return { ok: false, error: \"Epic group modes missing\" };\n }\n if (!manifest.auto_approve && !hasChoice(state.decisions, \"confirm_preview\")) {\n return { ok: false, error: \"Preview confirmation decision missing\" };\n }\n }\n if (toPhase === PHASES.FINALIZE) {\n const expectedGroups = Object.keys(state.epic_group_modes || {}).length;\n const actualGroups = Object.keys(state.epic_results || {}).length;\n if (expectedGroups > 0 && actualGroups \u003c expectedGroups) {\n return { ok: false, error: \"Not all epic groups produced worker summaries\" };\n }\n }\n if (toPhase === PHASES.SELF_CHECK && !state.story_plan_summary) {\n return { ok: false, error: \"Story plan coordinator summary missing\" };\n }\n if (toPhase === PHASES.SELF_CHECK && !state.template_compliance_passed) {\n return { ok: false, error: \"Template compliance not verified. Fetch each created story via get_issue, run validateTemplateCompliance(description, 'story'), record template_compliance_passed in state.\" };\n }\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n }\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n const baseAction = computePlanningBaseResumeAction(\n state,\n checkpoints,\n ALLOWED_TRANSITIONS,\n PHASES.PAUSED,\n PHASES.DONE,\n );\n if (state.phase === PHASES.DELEGATE) {\n const expected = Object.keys(state.epic_group_modes || {}).length;\n const actual = Object.keys(state.epic_results || {}).length;\n if (expected > actual) {\n return \"Record remaining epic worker summaries before finalization\";\n }\n }\n if (state.phase === PHASES.FINALIZE && !state.story_plan_summary) {\n return \"Record story-plan coordinator summary before self-check\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n return baseAction;\n}\n","content_type":"text/javascript","language":"javascript","size":4101,"content_sha256":"4529a93433a4b3b9595b0d718b7ab38233ca0dd24ab60f998b06a1c4caa7e714"},{"filename":"references/scripts/story-planning-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-planning-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n CONTEXT_ASSEMBLY: \"PHASE_1_CONTEXT_ASSEMBLY\",\n RESEARCH: \"PHASE_2_RESEARCH\",\n PLAN: \"PHASE_3_PLAN\",\n ROUTING: \"PHASE_4_ROUTING\",\n MODE_DETECTION: \"PHASE_5_MODE_DETECTION\",\n DELEGATE: \"PHASE_6_DELEGATE\",\n FINALIZE: \"PHASE_7_FINALIZE\",\n SELF_CHECK: \"PHASE_8_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":682,"content_sha256":"cef984df6b57330a56946eabc92e132a40039fc382ff69fcfb780be82080c6e2"},{"filename":"references/scripts/story-planning-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/story-planning-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n storyPlanCoordinatorSummarySchema,\n storyPlanWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport {\n createPlanningManifestSchema,\n createPlanningRuntimeStore,\n createPlanningState,\n} from \"../../planning-runtime/lib/store.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst storyPlanningStore = createPlanningRuntimeStore({\n baseRootParts: [\".hex-skills\", \"story-planning\", \"runtime\"],\n manifestSchema: createPlanningManifestSchema(\"epic_id\"),\n normalizeManifest(manifestInput, projectRoot) {\n const epicId = manifestInput.epic_id || manifestInput.identifier;\n return {\n skill: \"ln-220\",\n mode: manifestInput.mode || \"story_planning\",\n identifier: manifestInput.identifier || `epic-${epicId}`,\n epic_id: epicId,\n task_provider: manifestInput.task_provider || \"unknown\",\n auto_approve: manifestInput.auto_approve === true,\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return createPlanningState(manifest, runId, PHASES.CONFIG, {\n epic_id: manifest.epic_id,\n context_ready: false,\n research_file: null,\n research_status: null,\n ideal_plan_summary: null,\n routing_summary: null,\n epic_group_modes: {},\n epic_results: {},\n story_plan_summary: null,\n });\n },\n pausedPhase: PHASES.PAUSED,\n resumablePhases: new Set(Object.values(PHASES).filter(p => p !== PHASES.PAUSED && p !== PHASES.DONE)),\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n updateState,\n} = storyPlanningStore;\n\nexport function recordEpic(projectRoot, runId, summary) {\n return storyPlanningStore.recordSummary(\n projectRoot,\n runId,\n summary,\n storyPlanWorkerSummarySchema,\n \"story plan worker summary\",\n (state, nextSummary) => ({\n ...state,\n epic_results: {\n ...state.epic_results,\n [nextSummary.payload.epic_id]: nextSummary,\n },\n }),\n );\n}\n\nexport function recordPlanSummary(projectRoot, runId, summary) {\n return storyPlanningStore.recordCoordinatorSummary(\n projectRoot,\n runId,\n summary,\n storyPlanCoordinatorSummarySchema,\n \"story planning coordinator summary\",\n \"story_plan_summary\",\n );\n}\n","content_type":"text/javascript","language":"javascript","size":2895,"content_sha256":"0a99a673e178f85876dbedef861fe3f3bf50767f0b9d3f7c07fb38bddcd79c9a"},{"filename":"references/scripts/story-planning-runtime/test/smoke.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/story-planning-runtime/test/smoke.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createJsonCliRunner,\n createProjectRoot,\n writeJson,\n} from \"../../coordinator-runtime/test/cli-test-helpers.mjs\";\nimport { PLANNING_PROGRESS_STATUSES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\nimport { PHASES } from \"../lib/phases.mjs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst cliPath = join(__dirname, \"..\", \"cli.mjs\");\nconst projectRoot = createProjectRoot(\"story-planning-runtime-\");\nconst run = createJsonCliRunner(cliPath, projectRoot);\n\ntry {\n const manifestPath = join(projectRoot, \"manifest.json\");\n writeJson(manifestPath, {\n task_provider: \"file\",\n auto_approve: false,\n });\n\n const started = run([\"start\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--manifest-file\", manifestPath]);\n if (!started.ok) {\n throw new Error(\"Failed to start story planning runtime\");\n }\n const parentRunId = started.run_id;\n\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.CONFIG]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.CONTEXT_ASSEMBLY]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.CONTEXT_ASSEMBLY, \"--payload\", \"{\\\"context_ready\\\":true}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.RESEARCH]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.RESEARCH, \"--payload\", JSON.stringify({ research_status: PLANNING_PROGRESS_STATUSES.COMPLETED, research_file: \"docs/research/rsh-007-auth.md\" })]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.PLAN]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", \"PHASE_3_PLAN\", \"--payload\", \"{\\\"ideal_plan_summary\\\":{\\\"stories_planned\\\":3}}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.ROUTING]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.ROUTING, \"--payload\", \"{\\\"routing_summary\\\":{\\\"groups\\\":[\\\"7\\\"]}}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.MODE_DETECTION]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.MODE_DETECTION, \"--payload\", \"{\\\"epic_group_modes\\\":{\\\"7\\\":\\\"CREATE\\\"}}\"]);\n run([\"pause\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--reason\", \"Preview confirmation\", \"--payload\", \"{\\\"kind\\\":\\\"preview_confirmation\\\",\\\"question\\\":\\\"Confirm preview?\\\",\\\"choices\\\":[\\\"confirm_preview\\\",\\\"cancel\\\"],\\\"default_choice\\\":\\\"confirm_preview\\\",\\\"context\\\":{\\\"epic_id\\\":\\\"7\\\"},\\\"resume_to_phase\\\":\\\"PHASE_6_DELEGATE\\\",\\\"blocking\\\":true}\"]);\n run([\"set-decision\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--payload\", \"{\\\"selected_choice\\\":\\\"confirm_preview\\\"}\"]);\n run([\"record-epic\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--payload\", \"{\\\"schema_version\\\":\\\"1.0\\\",\\\"summary_kind\\\":\\\"story-plan-worker\\\",\\\"run_id\\\":\\\"child-ln-221-epic-7\\\",\\\"identifier\\\":\\\"epic-7\\\",\\\"producer_skill\\\":\\\"ln-221\\\",\\\"produced_at\\\":\\\"2026-03-26T00:00:00Z\\\",\\\"payload\\\":{\\\"mode\\\":\\\"CREATE\\\",\\\"epic_id\\\":\\\"7\\\",\\\"stories_planned\\\":3,\\\"stories_created\\\":3,\\\"stories_updated\\\":0,\\\"stories_canceled\\\":0,\\\"story_urls\\\":[\\\"US001\\\",\\\"US002\\\",\\\"US003\\\"],\\\"warnings\\\":[],\\\"kanban_updated\\\":true,\\\"research_path_used\\\":\\\"docs/research/rsh-007-auth.md\\\"}}\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.DELEGATE]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.FINALIZE]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.FINALIZE, \"--payload\", \"{\\\"final_result\\\":\\\"CREATED\\\",\\\"template_compliance_passed\\\":true}\"]);\n run([\"record-plan-summary\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--payload\", JSON.stringify({\n schema_version: \"1.0.0\",\n summary_kind: \"story-plan\",\n run_id: parentRunId,\n identifier: \"epic-7\",\n producer_skill: \"ln-220\",\n produced_at: \"2026-04-08T00:00:00Z\",\n payload: {\n mode: \"CREATE\",\n epic_id: \"7\",\n stories_planned: 3,\n stories_created: 3,\n stories_updated: 0,\n stories_canceled: 0,\n story_urls: [\"US001\", \"US002\", \"US003\"],\n warnings: [],\n kanban_updated: true,\n research_path_used: \"docs/research/rsh-007-auth.md\",\n worker_runs_completed: 1,\n artifact_path: null,\n },\n })]);\n run([\"advance\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--to\", PHASES.SELF_CHECK]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--epic\", \"7\", \"--phase\", PHASES.SELF_CHECK, \"--payload\", \"{\\\"pass\\\":true,\\\"final_result\\\":\\\"CREATED\\\"}\"]);\n const completed = run([\"complete\", \"--project-root\", projectRoot, \"--epic\", \"7\"]);\n\n if (!completed.ok || completed.state.phase !== PHASES.DONE) {\n throw new Error(\"Story planning runtime did not complete\");\n }\n\n process.stdout.write(\"story-planning-runtime smoke passed\\n\");\n} finally {\n rmSync(projectRoot, { recursive: true, force: true });\n}\n","content_type":"text/javascript","language":"javascript","size":5488,"content_sha256":"a7c64c1ace44e0d4c51001517955599f96ec65dd69c9106f8dc1d0bf2d62e81d"},{"filename":"references/scripts/task-planning-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/task-planning-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n recordPlan,\n recordStageSummary,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputJson as output,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\nimport {\n advancePlanningRun,\n checkpointPlanningRun,\n completePlanningRun,\n loadPlanningStatusRun,\n outputInactiveRuntime,\n outputPlanningStatus,\n pausePlanningRun,\n resolvePlanningRunOrFail,\n} from \"../planning-runtime/lib/cli.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n story: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n },\n});\n\nfunction resolveRun(projectRoot) {\n return resolvePlanningRunOrFail({\n projectRoot,\n skill: \"ln-300\",\n runId: values[\"run-id\"],\n identifier: values.story ? `story-${values.story}` : null,\n identifierFlag: \"story\",\n listActiveRuns,\n resolveRunId,\n loadRun,\n fail,\n });\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n\n if (phase === PHASES.DISCOVERY) {\n nextState.discovery_ready = payload.discovery_ready === true;\n }\n if (phase === PHASES.DECOMPOSE) {\n nextState.ideal_plan_summary = payload.ideal_plan_summary || payload.plan_summary || payload;\n }\n if (phase === PHASES.READINESS_GATE) {\n nextState.readiness_score = Number(payload.readiness_score);\n nextState.readiness_findings = payload.readiness_findings || [];\n }\n if (phase === PHASES.MODE_DETECTION) {\n nextState.mode_detection = payload.mode_detection || payload.mode || null;\n }\n if (phase === PHASES.DELEGATE && payload.child_run && typeof payload.child_run === \"object\") {\n nextState.child_run = payload.child_run;\n }\n if (phase === PHASES.VERIFY) {\n nextState.verification_summary = payload.verification_summary || payload.summary || payload;\n nextState.final_result = payload.final_result || nextState.final_result;\n if (payload.template_compliance_passed === true) {\n nextState.template_compliance_passed = true;\n }\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.story || !values[\"manifest-file\"]) {\n fail(\"start requires --story and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n story_id: values.story,\n identifier: `story-${values.story}`,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n const run = loadPlanningStatusRun({\n projectRoot,\n skill: \"ln-300\",\n runId: values[\"run-id\"],\n identifier: values.story ? `story-${values.story}` : null,\n identifierFlag: \"story\",\n listActiveRuns,\n loadRun,\n loadActiveRun,\n output,\n });\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputPlanningStatus(projectRoot, run, runtimePaths, computeResumeAction, output);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n advancePlanningRun(projectRoot, runId, run, values.to, validateTransition, saveState, PHASES.DONE, output);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n checkpointPlanningRun(projectRoot, runId, run, values.phase, payload, checkpointPhase, saveState, applyCheckpointToState, fail, output);\n return;\n }\n\n if (command === \"record-plan\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordPlan(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"record-stage-summary\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordStageSummary(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"set-decision\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordDecision(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n pausePlanningRun(projectRoot, runId, payload, values.reason, pauseRun, setPendingDecision, fail, output);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n completePlanningRun(projectRoot, runId, run, validateTransition, completeRun, PHASES.DONE, fail, output);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-plan, record-stage-summary, set-decision, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":6812,"content_sha256":"52dfcc1fde2febdd1f51a041867dbc63417625f96c3d00e3e29bc9de65826e1b"},{"filename":"references/scripts/task-planning-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/task-planning-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport {\n computePlanningBaseResumeAction,\n hasChoice,\n validatePlanningBaseTransition,\n} from \"../../planning-runtime/lib/guards.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.DECOMPOSE])],\n [PHASES.DECOMPOSE, new Set([PHASES.READINESS_GATE])],\n [PHASES.READINESS_GATE, new Set([PHASES.MODE_DETECTION])],\n [PHASES.MODE_DETECTION, new Set([PHASES.DELEGATE])],\n [PHASES.DELEGATE, new Set([PHASES.VERIFY])],\n [PHASES.VERIFY, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const base = validatePlanningBaseTransition(state, checkpoints, toPhase, ALLOWED_TRANSITIONS);\n if (!base.ok) {\n return base;\n }\n if (toPhase === PHASES.DECOMPOSE && !state.discovery_ready) {\n return { ok: false, error: \"Discovery summary missing\" };\n }\n if (toPhase === PHASES.READINESS_GATE && !state.ideal_plan_summary) {\n return { ok: false, error: \"Ideal task plan summary missing\" };\n }\n if (toPhase === PHASES.MODE_DETECTION) {\n if (state.readiness_score == null) {\n return { ok: false, error: \"Readiness score missing\" };\n }\n if (state.readiness_score \u003c 4) {\n return { ok: false, error: \"Readiness gate blocked the plan\" };\n }\n if (state.readiness_score \u003c 6 && !hasChoice(state.decisions, \"continue_with_warnings\")) {\n return { ok: false, error: \"Readiness approval decision missing\" };\n }\n }\n if (toPhase === PHASES.DELEGATE && !state.mode_detection) {\n return { ok: false, error: \"Mode detection missing\" };\n }\n if (toPhase === PHASES.VERIFY && !state.plan_result) {\n return { ok: false, error: \"Worker summary missing\" };\n }\n if (toPhase === PHASES.SELF_CHECK && !state.verification_summary) {\n return { ok: false, error: \"Verification summary missing\" };\n }\n if (toPhase === PHASES.SELF_CHECK && !state.template_compliance_passed) {\n return { ok: false, error: \"Template compliance not verified. Fetch each created task via get_issue, run validateTemplateCompliance(description, 'task'), record template_compliance_passed in state.\" };\n }\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n }\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.phase === PHASES.READINESS_GATE && state.readiness_score != null && state.readiness_score \u003c 6) {\n return \"Record approval decision or improve the plan before mode detection\";\n }\n if (state.phase === PHASES.DELEGATE && !state.plan_result) {\n if (state.child_run?.run_id) {\n return `Check child runtime ${state.child_run.run_id} for ${state.child_run.worker || \"task-plan worker\"} or record task-planning worker summary before verification`;\n }\n return \"Record task-planning worker summary before verification\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n return computePlanningBaseResumeAction(\n state,\n checkpoints,\n ALLOWED_TRANSITIONS,\n PHASES.PAUSED,\n PHASES.DONE,\n );\n}\n","content_type":"text/javascript","language":"javascript","size":3858,"content_sha256":"b9830cc3e0c5ad5e013e0285747b46ea3777778ca177e8762c5d7134715ecde5"},{"filename":"references/scripts/task-planning-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/task-planning-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n DECOMPOSE: \"PHASE_2_DECOMPOSE\",\n READINESS_GATE: \"PHASE_3_READINESS_GATE\",\n MODE_DETECTION: \"PHASE_4_MODE_DETECTION\",\n DELEGATE: \"PHASE_5_DELEGATE\",\n VERIFY: \"PHASE_6_VERIFY\",\n SELF_CHECK: \"PHASE_7_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":653,"content_sha256":"57ecdf81db89530390453e97806cead7b284a61b43ada0797658367a92ed890f"},{"filename":"references/scripts/task-planning-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/task-planning-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n pipelineStageCoordinatorSummarySchema,\n taskPlanWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport {\n createPlanningManifestSchema,\n createPlanningRuntimeStore,\n createPlanningState,\n} from \"../../planning-runtime/lib/store.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst taskPlanningStore = createPlanningRuntimeStore({\n baseRootParts: [\".hex-skills\", \"task-planning\", \"runtime\"],\n manifestSchema: createPlanningManifestSchema(\"story_id\"),\n normalizeManifest(manifestInput, projectRoot) {\n const storyId = manifestInput.story_id || manifestInput.identifier;\n return {\n skill: \"ln-300\",\n mode: manifestInput.mode || \"task_planning\",\n identifier: manifestInput.identifier || `story-${storyId}`,\n story_id: storyId,\n task_provider: manifestInput.task_provider || \"unknown\",\n auto_approve: manifestInput.auto_approve === true,\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return createPlanningState(manifest, runId, PHASES.CONFIG, {\n story_id: manifest.story_id,\n discovery_ready: false,\n ideal_plan_summary: null,\n readiness_score: null,\n readiness_findings: [],\n mode_detection: null,\n plan_result: null,\n child_run: null,\n verification_summary: null,\n stage_summary: null,\n template_compliance_passed: false,\n });\n },\n pausedPhase: PHASES.PAUSED,\n resumablePhases: new Set(Object.values(PHASES).filter(p => p !== PHASES.PAUSED && p !== PHASES.DONE)),\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n readJsonFile,\n recordDecision,\n resolveRunId,\n runtimePaths,\n saveState,\n setPendingDecision,\n startRun,\n updateState,\n} = taskPlanningStore;\n\nexport function recordPlan(projectRoot, runId, summary) {\n return taskPlanningStore.recordSummary(\n projectRoot,\n runId,\n summary,\n taskPlanWorkerSummarySchema,\n \"task plan worker summary\",\n (state, nextSummary) => ({\n ...state,\n plan_result: nextSummary,\n }),\n );\n}\n\nexport function recordStageSummary(projectRoot, runId, summary) {\n return taskPlanningStore.recordCoordinatorSummary(\n projectRoot,\n runId,\n summary,\n pipelineStageCoordinatorSummarySchema,\n \"pipeline stage coordinator summary\",\n \"stage_summary\",\n {\n artifactIdentifier: nextSummary => `${nextSummary.identifier}-stage-${nextSummary.payload.stage}`,\n },\n );\n}\n","content_type":"text/javascript","language":"javascript","size":3008,"content_sha256":"3dabd0392a6c6165fe2bfe944ccaedaa96e3a254719bb9db84471a91de9d082f"},{"filename":"references/scripts/task-planning-runtime/test/smoke.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/task-planning-runtime/test/smoke.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createJsonCliRunner,\n createProjectRoot,\n writeJson,\n} from \"../../coordinator-runtime/test/cli-test-helpers.mjs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst cliPath = join(__dirname, \"..\", \"cli.mjs\");\nconst projectRoot = createProjectRoot(\"task-planning-runtime-\");\nconst run = createJsonCliRunner(cliPath, projectRoot);\n\ntry {\n const manifestPath = join(projectRoot, \"manifest.json\");\n writeJson(manifestPath, {\n task_provider: \"file\",\n auto_approve: true,\n });\n\n const started = run([\"start\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--manifest-file\", manifestPath]);\n if (!started.ok) {\n throw new Error(\"Failed to start task planning runtime\");\n }\n\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_0_CONFIG\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_1_DISCOVERY\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_1_DISCOVERY\", \"--payload\", \"{\\\"discovery_ready\\\":true}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_2_DECOMPOSE\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_2_DECOMPOSE\", \"--payload\", \"{\\\"ideal_plan_summary\\\":{\\\"tasks_planned\\\":3}}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_3_READINESS_GATE\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_3_READINESS_GATE\", \"--payload\", \"{\\\"readiness_score\\\":6,\\\"readiness_findings\\\":[]}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_4_MODE_DETECTION\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_4_MODE_DETECTION\", \"--payload\", \"{\\\"mode_detection\\\":\\\"CREATE\\\"}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_5_DELEGATE\"]);\n run([\"record-plan\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--payload\", \"{\\\"schema_version\\\":\\\"1.0\\\",\\\"summary_kind\\\":\\\"task-plan\\\",\\\"run_id\\\":\\\"run-1\\\",\\\"identifier\\\":\\\"story-proj-42\\\",\\\"producer_skill\\\":\\\"ln-301\\\",\\\"produced_at\\\":\\\"2026-03-26T00:00:00Z\\\",\\\"payload\\\":{\\\"mode\\\":\\\"CREATE\\\",\\\"story_id\\\":\\\"PROJ-42\\\",\\\"task_type\\\":\\\"implementation\\\",\\\"tasks_created\\\":3,\\\"tasks_updated\\\":0,\\\"tasks_canceled\\\":0,\\\"task_urls\\\":[\\\"TASK-1\\\",\\\"TASK-2\\\",\\\"TASK-3\\\"],\\\"dry_warnings_count\\\":1,\\\"warnings\\\":[],\\\"kanban_updated\\\":true}}\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_5_DELEGATE\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_6_VERIFY\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_6_VERIFY\", \"--payload\", \"{\\\"verification_summary\\\":{\\\"tasks_verified\\\":3},\\\"final_result\\\":\\\"PLAN_READY\\\",\\\"template_compliance_passed\\\":true}\"]);\n run([\"advance\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--to\", \"PHASE_7_SELF_CHECK\"]);\n run([\"checkpoint\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\", \"--phase\", \"PHASE_7_SELF_CHECK\", \"--payload\", \"{\\\"pass\\\":true,\\\"final_result\\\":\\\"PLAN_READY\\\"}\"]);\n const completed = run([\"complete\", \"--project-root\", projectRoot, \"--story\", \"PROJ-42\"]);\n\n if (!completed.ok || completed.state.phase !== \"DONE\") {\n throw new Error(\"Task planning runtime did not complete\");\n }\n\n process.stdout.write(\"task-planning-runtime smoke passed\\n\");\n} finally {\n rmSync(projectRoot, { recursive: true, force: true });\n}\n","content_type":"text/javascript","language":"javascript","size":3971,"content_sha256":"36b18e77fd7e4d1b35653441d86916bdf92a143d6accd8d5c4366a3f3b18460c"},{"filename":"references/scripts/test-planning-runtime/cli.mjs","content":"#!/usr/bin/env node\n// SOURCE-OF-TRUTH: shared/scripts/test-planning-runtime/cli.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { parseArgs } from \"node:util\";\nimport {\n checkpointPhase,\n completeRun,\n listActiveRuns,\n loadActiveRun,\n loadRun,\n pauseRun,\n readJsonFile,\n recordWorker,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n} from \"./lib/store.mjs\";\nimport {\n failJson as fail,\n failResult,\n outputGuardFailure,\n outputInactiveRuntime,\n outputJson as output,\n outputRuntimeState,\n outputRuntimeStatus,\n readManifestOrFail,\n readPayload,\n} from \"../coordinator-runtime/lib/cli-helpers.mjs\";\nimport { computeResumeAction, validateTransition } from \"./lib/guards.mjs\";\nimport { PHASES } from \"./lib/phases.mjs\";\n\nconst { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n \"project-root\": { type: \"string\", default: process.cwd() },\n \"run-id\": { type: \"string\" },\n story: { type: \"string\" },\n phase: { type: \"string\" },\n to: { type: \"string\" },\n payload: { type: \"string\" },\n \"payload-file\": { type: \"string\" },\n \"manifest-file\": { type: \"string\" },\n reason: { type: \"string\" },\n resolve: { type: \"boolean\", default: false },\n },\n});\n\nfunction resolveRun(projectRoot) {\n const runId = resolveRunId(projectRoot, \"ln-520\", values[\"run-id\"], values.story);\n if (!runId) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-520\");\n if (activeRuns.length > 1 && !values.story) {\n fail(\"Multiple active ln-520 runs found. Pass --story or --run-id.\");\n }\n fail(\"No active ln-520 run found. Pass --story or --run-id.\");\n }\n const run = loadRun(projectRoot, runId);\n if (!run) {\n fail(`Run not found: ${runId}`);\n }\n return { runId, run };\n}\n\nfunction applyCheckpointToState(state, phase, payload) {\n const nextState = { ...state };\n if ([PHASES.RESEARCH, PHASES.MANUAL_TESTING, PHASES.AUTO_TEST_PLANNING].includes(phase)\n && payload.child_run?.worker) {\n nextState.child_runs = {\n ...(nextState.child_runs || {}),\n [payload.child_run.worker]: payload.child_run,\n };\n }\n if (phase === PHASES.RESEARCH) {\n nextState.research_status = payload.research_status || nextState.research_status;\n }\n if (phase === PHASES.MANUAL_TESTING) {\n nextState.manual_status = payload.manual_status || nextState.manual_status;\n }\n if (phase === PHASES.FINALIZE) {\n nextState.test_task_id = payload.test_task_id || nextState.test_task_id;\n nextState.test_task_url = payload.test_task_url || nextState.test_task_url;\n nextState.coverage_summary = payload.coverage_summary || nextState.coverage_summary;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n if (phase === PHASES.SELF_CHECK) {\n nextState.self_check_passed = payload.pass === true;\n nextState.final_result = payload.final_result || nextState.final_result;\n }\n return nextState;\n}\n\nasync function main() {\n const command = positionals[0];\n const projectRoot = values[\"project-root\"];\n\n if (command === \"start\") {\n if (!values.story || !values[\"manifest-file\"]) {\n fail(\"start requires --story and --manifest-file\");\n }\n const manifest = readManifestOrFail(values, readJsonFile);\n const result = startRun(projectRoot, {\n ...manifest,\n story_id: values.story,\n identifier: values.story,\n });\n output(result);\n process.exit(result.ok ? 0 : 1);\n }\n\n if (command === \"status\") {\n if (!values[\"run-id\"] && !values.story) {\n const activeRuns = listActiveRuns(projectRoot, \"ln-520\");\n if (activeRuns.length > 1) {\n output({ ok: false, error: \"Multiple active ln-520 runs found. Pass --story or --run-id.\" });\n process.exit(1);\n }\n }\n const run = values[\"run-id\"]\n ? loadRun(projectRoot, values[\"run-id\"])\n : loadActiveRun(projectRoot, \"ln-520\", values.story);\n if (!run) {\n outputInactiveRuntime(output);\n return;\n }\n outputRuntimeStatus(output, projectRoot, run, runtimePaths, computeResumeAction);\n return;\n }\n\n if (command === \"advance\") {\n if (!values.to) {\n fail(\"advance requires --to\");\n }\n const { runId, run } = resolveRun(projectRoot);\n if (run.state.phase === PHASES.PAUSED && values.resolve) {\n const resumed = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n paused_reason: null,\n });\n if (resumed?.ok === false) {\n outputGuardFailure(output, resumed);\n }\n outputRuntimeState(output, run, resumed, { resumed_from: \"PAUSED\" });\n return;\n }\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, values.to);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const nextState = saveState(projectRoot, runId, {\n ...run.state,\n phase: values.to,\n complete: values.to === PHASES.DONE ? true : run.state.complete,\n paused_reason: null,\n });\n if (nextState?.ok === false) {\n outputGuardFailure(output, nextState);\n }\n outputRuntimeState(output, run, nextState);\n return;\n }\n\n if (command === \"checkpoint\") {\n if (!values.phase) {\n fail(\"checkpoint requires --phase\");\n }\n const payload = readPayload(values, readJsonFile);\n const { runId, run } = resolveRun(projectRoot);\n const checkpointed = checkpointPhase(projectRoot, runId, values.phase, payload);\n if (!checkpointed.ok) {\n fail(checkpointed.error);\n }\n const nextState = saveState(projectRoot, runId, applyCheckpointToState(run.state, values.phase, payload));\n if (nextState?.ok === false) {\n failResult(nextState);\n }\n outputRuntimeState(output, run, nextState, {\n checkpoint: checkpointed.checkpoints[values.phase],\n history_length: checkpointed.checkpoints._history.length,\n });\n return;\n }\n\n if (command === \"record-worker\") {\n const payload = readPayload(values, readJsonFile);\n const { runId } = resolveRun(projectRoot);\n const result = recordWorker(projectRoot, runId, payload);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"pause\") {\n const { runId } = resolveRun(projectRoot);\n const result = pauseRun(projectRoot, runId, values.reason || \"Paused\");\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n if (command === \"complete\") {\n const { runId, run } = resolveRun(projectRoot);\n const guard = validateTransition(run.manifest, run.state, run.checkpoints, PHASES.DONE);\n if (!guard.ok) {\n outputGuardFailure(output, guard);\n }\n const result = completeRun(projectRoot, runId);\n if (!result.ok) {\n failResult(result);\n }\n output(result);\n return;\n }\n\n fail(\"Unknown command. Use: start, status, advance, checkpoint, record-worker, pause, complete\");\n}\n\nmain().catch(error => fail(error.message));\n","content_type":"text/javascript","language":"javascript","size":7678,"content_sha256":"7a729327018df7a2c6ed863200c8bd35d2cb7f2ab49d35ae66277b4394a950e4"},{"filename":"references/scripts/test-planning-runtime/lib/guards.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/test-planning-runtime/lib/guards.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { PHASES } from \"./phases.mjs\";\n\nconst ALLOWED_TRANSITIONS = new Map([\n [PHASES.CONFIG, new Set([PHASES.DISCOVERY])],\n [PHASES.DISCOVERY, new Set([PHASES.RESEARCH])],\n [PHASES.RESEARCH, new Set([PHASES.MANUAL_TESTING])],\n [PHASES.MANUAL_TESTING, new Set([PHASES.AUTO_TEST_PLANNING])],\n [PHASES.AUTO_TEST_PLANNING, new Set([PHASES.FINALIZE])],\n [PHASES.FINALIZE, new Set([PHASES.SELF_CHECK])],\n [PHASES.SELF_CHECK, new Set([PHASES.DONE])],\n [PHASES.PAUSED, new Set([])],\n [PHASES.DONE, new Set([])],\n]);\n\nfunction hasCheckpoint(checkpoints, phase) {\n return Boolean(checkpoints?.[phase]);\n}\n\nfunction hasWorker(state, worker) {\n return Boolean(state.worker_results?.[worker]);\n}\n\nfunction childRunMessage(state, worker, suffix) {\n const childRun = state.child_runs?.[worker];\n if (!childRun?.run_id) {\n return null;\n }\n return `Check child runtime ${childRun.run_id} for ${worker}${suffix}`;\n}\n\nexport function validateTransition(manifest, state, checkpoints, toPhase) {\n const allowed = ALLOWED_TRANSITIONS.get(state.phase);\n if (!allowed || !allowed.has(toPhase)) {\n return { ok: false, error: `Invalid transition: ${state.phase} -> ${toPhase}` };\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return { ok: false, error: `Checkpoint missing for ${state.phase}` };\n }\n if (toPhase === PHASES.MANUAL_TESTING && !state.simplified && !hasWorker(state, \"ln-521\")) {\n return { ok: false, error: \"ln-521 summary missing\" };\n }\n if (toPhase === PHASES.AUTO_TEST_PLANNING && !state.simplified && !hasWorker(state, \"ln-522\")) {\n return { ok: false, error: \"ln-522 summary missing\" };\n }\n if (toPhase === PHASES.FINALIZE && !hasWorker(state, \"ln-523\")) {\n return { ok: false, error: \"ln-523 summary missing\" };\n }\n if (toPhase === PHASES.DONE) {\n if (!state.self_check_passed) {\n return { ok: false, error: \"Self-check must pass before completion\" };\n }\n if (!state.final_result) {\n return { ok: false, error: \"Final result not recorded\" };\n }\n }\n return { ok: true };\n}\n\nexport function computeResumeAction(manifest, state, checkpoints) {\n if (state.complete || state.phase === PHASES.DONE) {\n return \"Run complete\";\n }\n if (state.phase === PHASES.PAUSED) {\n return `Paused: ${state.paused_reason || \"manual intervention required\"}`;\n }\n if (!hasCheckpoint(checkpoints, state.phase)) {\n return `Complete ${state.phase} and write its checkpoint`;\n }\n if (state.phase === PHASES.RESEARCH && !state.simplified && !hasWorker(state, \"ln-521\")) {\n return childRunMessage(state, \"ln-521\", \" or record its worker summary before manual testing\")\n || \"Record ln-521 worker summary before manual testing\";\n }\n if (state.phase === PHASES.MANUAL_TESTING && !state.simplified && !hasWorker(state, \"ln-522\")) {\n return childRunMessage(state, \"ln-522\", \" or record its worker summary before auto-test planning\")\n || \"Record ln-522 worker summary before auto-test planning\";\n }\n if (state.phase === PHASES.AUTO_TEST_PLANNING && !hasWorker(state, \"ln-523\")) {\n return childRunMessage(state, \"ln-523\", \" or record its worker summary before finalization\")\n || \"Record ln-523 worker summary before finalization\";\n }\n if (state.phase === PHASES.SELF_CHECK && !state.self_check_passed) {\n return `Fix self-check failures, then checkpoint ${PHASES.SELF_CHECK} with pass=true`;\n }\n const nextPhase = Array.from(ALLOWED_TRANSITIONS.get(state.phase) || [])[0];\n return nextPhase ? `Advance to ${nextPhase}` : \"No automatic resume action available\";\n}\n","content_type":"text/javascript","language":"javascript","size":3873,"content_sha256":"6204646029b0f2dd3c09e1479e13494c74b0f4b6312dda518fb98f46146f31cc"},{"filename":"references/scripts/test-planning-runtime/lib/phases.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/test-planning-runtime/lib/phases.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { TERMINAL_RUNTIME_PHASES } from \"../../coordinator-runtime/lib/runtime-constants.mjs\";\n\nexport const PHASES = Object.freeze({\n CONFIG: \"PHASE_0_CONFIG\",\n DISCOVERY: \"PHASE_1_DISCOVERY\",\n RESEARCH: \"PHASE_2_RESEARCH\",\n MANUAL_TESTING: \"PHASE_3_MANUAL_TESTING\",\n AUTO_TEST_PLANNING: \"PHASE_4_AUTO_TEST_PLANNING\",\n FINALIZE: \"PHASE_5_FINALIZE\",\n SELF_CHECK: \"PHASE_6_SELF_CHECK\",\n PAUSED: TERMINAL_RUNTIME_PHASES.PAUSED,\n DONE: TERMINAL_RUNTIME_PHASES.DONE,\n});\n","content_type":"text/javascript","language":"javascript","size":629,"content_sha256":"bec851e02cc44b104061b8eb1b4c37c37a0ed944df9af0f695a6e958330f6c24"},{"filename":"references/scripts/test-planning-runtime/lib/store.mjs","content":"// SOURCE-OF-TRUTH: shared/scripts/test-planning-runtime/lib/store.mjs. Edit ONLY here; run `node tools/marketplace/shared.mjs sync`\n\nimport { resolve } from \"node:path\";\nimport {\n createRuntimeStore,\n readJsonFile,\n} from \"../../coordinator-runtime/lib/core.mjs\";\nimport {\n testPlanningWorkerSummarySchema,\n} from \"../../coordinator-runtime/lib/schemas.mjs\";\nimport { assertSchema } from \"../../coordinator-runtime/lib/validate.mjs\";\nimport { PHASES } from \"./phases.mjs\";\n\nconst manifestSchema = {\n type: \"object\",\n required: [\"skill\", \"identifier\", \"story_id\", \"project_root\", \"created_at\"],\n properties: {\n skill: { type: \"string\" },\n mode: { type: \"string\" },\n identifier: { type: \"string\" },\n story_id: { type: \"string\" },\n simplified: { type: \"boolean\" },\n project_root: { type: \"string\" },\n task_provider: { type: \"string\" },\n created_at: { type: \"string\", format: \"date-time\" },\n },\n};\n\nconst plannerStore = createRuntimeStore({\n baseRootParts: [\".hex-skills\", \"test-planning\", \"runtime\"],\n manifestSchema,\n normalizeManifest(manifestInput, projectRoot) {\n return {\n skill: \"ln-520\",\n mode: manifestInput.mode || \"test_planning\",\n identifier: manifestInput.story_id || manifestInput.identifier,\n story_id: manifestInput.story_id || manifestInput.identifier,\n simplified: manifestInput.simplified === true,\n task_provider: manifestInput.task_provider || \"unknown\",\n project_root: resolve(projectRoot || process.cwd()),\n created_at: new Date().toISOString(),\n };\n },\n defaultState(manifest, runId) {\n return {\n run_id: runId,\n skill: manifest.skill,\n mode: manifest.mode,\n identifier: manifest.identifier,\n story_id: manifest.story_id,\n phase: PHASES.CONFIG,\n complete: false,\n paused_reason: null,\n pending_decision: null,\n decisions: [],\n simplified: manifest.simplified,\n worker_results: {},\n child_runs: {},\n research_status: null,\n manual_status: null,\n test_task_id: null,\n test_task_url: null,\n coverage_summary: null,\n self_check_passed: false,\n final_result: null,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n };\n },\n});\n\nexport const {\n checkpointPhase,\n completeRun,\n loadActiveRun,\n listActiveRuns,\n loadRun,\n pauseRun,\n resolveRunId,\n runtimePaths,\n saveState,\n startRun,\n updateState,\n} = plannerStore;\n\nexport { readJsonFile };\n\nexport function recordWorker(projectRoot, runId, summary) {\n const run = loadRun(projectRoot, runId);\n if (!run) {\n return { ok: false, error: \"Run not found\" };\n }\n const validation = assertSchema(testPlanningWorkerSummarySchema, summary, \"test-planning worker summary\");\n if (!validation.ok) {\n return validation;\n }\n return updateState(projectRoot, runId, state => ({\n ...state,\n worker_results: {\n ...state.worker_results,\n [summary.payload.worker]: summary,\n },\n research_status: summary.payload.worker === \"ln-521\" ? summary.payload.status : state.research_status,\n manual_status: summary.payload.worker === \"ln-522\" ? summary.payload.status : state.manual_status,\n test_task_id: summary.payload.test_task_id || state.test_task_id,\n test_task_url: summary.payload.test_task_url || state.test_task_url,\n coverage_summary: summary.payload.coverage_summary || state.coverage_summary,\n }));\n}\n","content_type":"text/javascript","language":"javascript","size":3782,"content_sha256":"513a29e1d67f310bfec8f38220f17736717bd3471be545cf67cf54a7ef14e0d3"},{"filename":"references/skill_contract.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/skill_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Skill Contract\n\n\u003c!-- SCOPE: Canonical shared contract for SKILL.md files in this repository. Contains enforceable structure, delegation, and coupling rules. -->\n\nThis file is the runtime source of truth for `SKILL.md` requirements.\n\nUse it for:\n- creating new skills\n- reviewing or refactoring existing skills\n- enforcing rules in `ln-162-skill-reviewer`\n\nDo not rely on `docs/` meta files for runtime enforcement. Those files are maintainer references only.\n\n---\n\n## Goal\n\nEvery `SKILL.md` must be:\n- executable by an agent without guessing\n- small enough to stay context-efficient\n- explicit about delegation and boundaries\n- free of reverse coupling and stale instructions\n\n---\n\n## Required Structure\n\nEvery `SKILL.md` must include:\n- YAML frontmatter with `name` and `description`\n- `> **Paths:**` note after frontmatter if the file references local paths\n- `**Type:**` line as the canonical role marker for review and delegation logic\n- `## Definition of Done` with `- [ ]` checkboxes\n- `**Version:** X.Y.Z` and `**Last Updated:** YYYY-MM-DD` at the end\n\nForbidden:\n- `**Changes:**` sections\n- passive local file references such as `See`, `Per`, `Follows` instead of `**MANDATORY READ:** Load`\n\n`**Type:**` rules:\n- reviewers and coordinators use it to classify the skill as L1/L2/L3 and orchestrator/coordinator/worker\n- a missing `**Type:**` is a structural contract violation, not a style nit\n- reviewers may infer likely role only to improve diagnostics; inference does not replace the required field\n\nDescription rules:\n- keep under 200 characters\n- say WHAT the skill does and WHEN to use it\n- if `description:` contains `:`, wrap it in double quotes\n\n---\n\n## Path and Reference Rules\n\nPath resolution:\n- relative paths in `SKILL.md` are relative to the skills repo root\n- not relative to the target project\n\nReference rules:\n- file references that matter for execution must use `**MANDATORY READ:** Load ...`\n- do not rely on `@path` imports as the execution contract for `SKILL.md`; use explicit `**MANDATORY READ:** Load ...` for any file the agent must read before acting\n- group multiple `MANDATORY READ` targets into one block at the section start\n- move reusable logic to `references/`\n- keep skill-specific logic in the local `SKILL.md` or local `references/`\n\n---\n\n## Delegation Rules\n\n### L1 / L2 skills\n\nIf a skill delegates to workers, it must include all three:\n- explicit invocation code using `Skill(skill:` or `Agent(... Skill(skill: ...))`\n- `**Host Skill Invocation:**` bridge when `Skill(skill:` appears\n- `## Worker Invocation (MANDATORY)`\n- `TodoWrite format (mandatory):`\n\n`Skill(skill: \"...\", args: \"...\")` is mandatory delegation syntax, not an illustrative example:\n- Claude hosts call the `Skill` tool exactly as shown.\n- Codex hosts without a `Skill` tool must locate the named skill in available skills, read its `SKILL.md`, treat `args` as `$ARGUMENTS`, execute that skill workflow, then return to the caller with the worker result or artifact.\n- callers must not inline worker logic or mark delegated work complete without executing the target skill.\n\nDefaults:\n- prefer `Skill` when shared context matters\n- prefer `Agent` when isolation matters more than shared context\n- prefer L2 -> L3 delegation over L2 -> L2 delegation\n- L2 -> L2 is allowed only when domains are distinct, the graph stays acyclic, and the flow is justified\n- sequential orchestration is the default; parallel branches are allowed only when they are independent and do not share mutable state or ordering requirements\n\n### L3 workers\n\nWorkers must stay standalone-invocable.\n\nForbidden in worker contract text:\n- `**Coordinator:**`\n- `**Parent:**`\n- required caller declarations\n- peer-worker cross-references as part of the public contract\n\nWorkers may mention external skills only when describing accepted inputs or interoperable formats, not ownership hierarchy.\n\n---\n\n## Context Economy\n\nHard limits:\n- `SKILL.md` \u003c= 800 lines\n- frontmatter `description` \u003c= 200 characters\n\nRequired behavior:\n- route heavy detail into `references/`\n- keep workflow steps sequential and explicit\n- use tables for compact metadata\n- remove filler and duplicated prose\n- prefer active voice\n\nHeuristics, not hard law:\n- 3-4 major workflow steps is usually a healthy ceiling\n- if one skill keeps accumulating unrelated branches, split it\n\n---\n\n## Procedural Skill Rules\n\nFor procedural, orchestrating, or mutating skills:\n- critical checklists must be colocated at the point of risk, not only in final DoD\n- risky steps should state action, key point, why, evidence, exception, and automation/guard when the risk is not self-evident\n- executable preflight checks must appear before external agent/tool invocations when permissions, auth, or tool availability can block execution\n- retry loops must include objective progress evidence and a pause condition\n- final Definition of Done does not replace point-of-use risk checks\n\nUse `references/procedural_skill_sop_guide.md` for the detailed SOP/TWI writing model.\n\n---\n\n## Compliance Notes\n\nAdditional enforced rules:\n- no hardcoded aggregate counts outside allowed locations\n- no stale references to removed skills or files\n- no unsupported platform APIs in active skills\n- no contradictions between caller and callee contracts\n- MCP usage must match `references/mcp_applicability_matrix.md`\n- skills that edit code/config/scripts must make `hex-line` primary and name built-in tools as fallback only\n- skills that depend on semantic code reasoning must make `hex-graph` primary and name grep/read as fallback only\n- skills without code-file or semantic-code decisions must not cargo-cult `hex-graph` requirements\n\nSpecial cases:\n- Meta-analysis is an optional post-run diagnostic, not a default runtime requirement. Load `references/meta_analysis_protocol.md` only when requested or when debugging repeated skill failures.\n- publishing skills need their extra review requirements\n- domain-specific families may add stricter shared contracts on top of this base contract\n\n---\n\n## Relationship to Maintainer Docs\n\n`docs/architecture/SKILL_ARCHITECTURE_GUIDE.md` is a developer reference:\n- rationale\n- design heuristics\n- anti-patterns\n- examples\n\nIt is not the enforceable runtime contract for skills.\n\n---\n\n**Version:** 1.0.0\n**Last Updated:** 2026-03-26\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6431,"content_sha256":"e279e2e21e6d2a1554ebdf798c51a51ecf09319966bea94d860a8c1593a68f3c"},{"filename":"references/structural_review.md","content":"# Structural Review Dimensions (D1-D11)\n\n\u003c!-- DO NOT add here: Workflow phases -> ln-162-skill-reviewer SKILL.md -->\n\u003c!-- Contract source: references/skill_contract.md -->\n\nCheck ALL dimensions across ALL skills in scope. Phase 2 failures are pre-verified -- include directly.\n\n## D1: Flow Integrity\n- Every `ln-NNN` reference in workflow/worker tables points to existing `ln-NNN-*/SKILL.md`\n- No circular delegation loops (A -> B -> A)\n- Every worker invocation targets a real skill with compatible responsibility boundaries\n- No dead-end flows (delegation to worker with no output/return path)\n- Peer coordinators (L2 siblings under same L1) do not reference each other\n- Peer workers (L3 siblings under same L2) do not reference each other\n\n## D2: Cross-Reference Consistency\n- `MANDATORY READ` paths exist on disk (Glob each path)\n- `Reference Files` section paths exist on disk\n- L3 workers stay caller-agnostic: no `Coordinator`, `Parent`, or required caller declaration\n- Skill invocation names (`skill: \"ln-NNN-*\"`) match actual directory names\n- No passive file references (`See`, `Per`, `Follows` pointing to files) -- must be `**MANDATORY READ:** Load`\n- Multiple `**MANDATORY READ:**` in same section -> group into ONE block at section start\n- `> **Paths:**` note present after frontmatter if SKILL.md contains any file references\n\n## D2b: Execution Proximity\n\nImperative actions in workflow steps (Launch, Run, Execute, Call) that depend on specific tool syntax (CLI flags, API signatures, file format patterns) MUST include an **inline command template** at the point of use — not only in a MANDATORY READ reference.\n\n**Rationale:** Agents may skip MANDATORY READ and \"guess\" the syntax. Inline template prevents this while MANDATORY READ provides full documentation.\n\n**Check:** For each workflow step containing an imperative action + reference to a shared tool:\n- Step mentions `agent_runner`, `Skill(`, `Bash`, or external CLI → inline code block with exact command MUST be within 5 lines\n- Step says \"per {reference}\" for execution syntax → inline template or example required\n\n**Severity:** WARN (not FAIL) — advisory, but high-impact for correctness.\n\n## D3: Duplication\n- Same instructions/rules not repeated across multiple skills\n- Shared logic lives in `references/`, skill-specific in SKILL.md (SRP)\n- No copy-pasted blocks that should be a MANDATORY READ to a shared file\n\n## D4: Contradiction Detection\n- Thresholds (confidence, impact, scores) consistent across related skills\n- Status transitions consistent (who sets which status)\n- Rules about same concept do not conflict between caller and callee\n- Verdict names and categories match across prompt templates, workflows, SKILL.md files\n- MCP primary/fallback ordering is consistent with `references/mcp_applicability_matrix.md`\n\n## D5: Context Economy\n- No large inline blocks that could be conditional MANDATORY READs\n- Metadata in table format where possible\n- No verbose explanations where table/list suffices\n- No filler words: \"simply\", \"quickly\", \"easily\", \"on top of that\", \"in many cases\"\n- No AI vocabulary: \"Additionally\", \"Furthermore\", \"Moreover\", \"testament\", \"landscape\", \"showcasing\", \"leverage\", \"utilize\", \"foster\", \"streamline\", \"delve\", \"tapestry\", \"multifaceted\", \"serves as\", \"functions as\", \"stands as\". Use: \"also\", \"shows\", \"use\", \"help\", \"explore\", \"is\", \"has\"\n- Passive voice where active is clearer (\"File should be loaded\" -> \"Load file\")\n- Sentences over 25 words -- flag for splitting\n- Verbose phrases not applied from `references/concise_terms.md` (\"in order to\" -> \"to\", \"make sure that\" -> \"ensure\")\n- Every content block must enable a specific agent action or decision -- remove if agent behavior unchanged without it\n- Tables must add information beyond adjacent text -- no restating\n- 1:1 mapping tables (each row = one input -> one output, no conditions) -> convert to inline list\n- Tables echoing template section names/structure -> reference template, don't duplicate\n- **Tiebreaker re-read:** re-read the WHOLE skill end-to-end (not just changed sections). If same instruction can be expressed in fewer words without losing agent actionability -- compress. Apply `code_efficiency_criterion` tiebreaker to skill text: among equivalent formulations, choose shorter\n- **Post-fix holistic pass:** after Phase 5 fixes, re-scan entire SKILL.md for cross-section redundancies introduced by fixes -- merge duplicate rules, combine overlapping tables, deduplicate restated instructions. Category: SIMPLIFY\n\n## D6: Stale Artifacts\n- No references to removed/renamed skills or files\n- No outdated caller names (skill renamed but old name in callers)\n- No instructions about features that no longer exist\n- No placeholder/TODO markers left from previous edits\n\n## D7: Structural Compliance\n- YAML frontmatter has `name` and `description` fields\n- If `description` contains `:`, wrapped in double quotes\n- `**Version:** X.Y.Z` and `**Last Updated:** YYYY-MM-DD` present at end of file\n- No `**Changes:**` section exists\n- Files in `references/` are actually referenced from SKILL.md (no orphan reference files)\n- `## Definition of Done` section present (all skills -- L1, L2, L3) with items as checkboxes (`- [ ]`)\n- `## Meta-Analysis` phase present with `MANDATORY READ` to `references/meta_analysis_protocol.md` (L1 orchestrators and L2 coordinators only)\n- Publishing skills (contain `gh api graphql.*mutation` or `gh issue comment`) must have: a Fact-Check phase AND `MANDATORY READ` to `references/humanizer_checklist.md`\n- Skills that edit code/config/scripts must load `references/mcp_tool_preferences.md` and make `hex-line` primary\n- Skills that depend on semantic code reasoning must load `references/mcp_tool_preferences.md` plus `references/mcp_integration_patterns.md` and make `hex-graph` primary\n- Skills in non-code or non-semantic families must not cargo-cult `hex-graph` or `hex-line` requirements without a real workflow need\n- Wrong MCP namespaces (`mcp__hex_graph__...`) are FAIL, not WARN\n\n## D8: Architecture Conformance\n- SKILL.md \u003c= 800 lines total\n- Frontmatter `description` \u003c= 200 chars\n- Phase/step numbering sequential (1, 2, 3, 4 -- no gaps). Exception: 4a/4b for CREATE/REPLAN\n- Orchestrators (L1/L2) delegate work, not execute directly -- no detailed implementation logic\n- Workers (L3) execute, not decide workflow -- no routing/priority logic\n- Workers (L3) do not declare `Coordinator`, `Parent`, or peer-skill coupling in their public contract text\n- L2->L2 cross-category delegation follows forward-flow (0XX->1XX->...->6XX), except 0XX shared services\n- Coupling reduction in `shared/` files -- shared references describe patterns, NOT consumers. Forbidden in any form: `Used by`, `Skills using this:`, `For ln-NNN`, `via ln-NNN` suffixes, skill names in role descriptions, skill IDs in code examples. Use generic role names (`task executor`, `review worker`). Consumers reference shared via MANDATORY READ; reverse direction is never needed\n\n\n## D8b: Worker Invocation Enforcement (L1/L2 only)\n\nL1 orchestrators and L2 coordinators that delegate to workers MUST have all three:\n\n| Required Element | Pattern to Grep | Where |\n|-----------------|----------------|-------|\n| Explicit invocation code | `Skill(skill:` or `Agent(description:.*Skill(skill:` | Per-worker in workflow section |\n| Host invocation bridge | `**Host Skill Invocation:**` | Near Worker Invocation section |\n| Worker Invocation section | `## Worker Invocation (MANDATORY)` | Dedicated section |\n| TodoWrite tracking | `TodoWrite format (mandatory):` | Near Worker Invocation section |\n\n**Detection:** Skill is L1/L2 if `Type:` line contains `L1` or `L2`, or SKILL.md has a Worker Invocation table referencing other `ln-NNN` skills.\n\n**Check:** For each L1/L2 skill with worker references:\n1. Count distinct `ln-NNN` skills in worker/delegation tables\n2. Count `Skill(skill: \"ln-NNN` code blocks in workflow\n3. If worker count > invocation count → FAIL: workers described but not explicitly invoked\n4. If `Skill(skill:` appears but no `**Host Skill Invocation:**` bridge exists → FAIL\n5. If no `Worker Invocation (MANDATORY)` section → FAIL\n6. If no `TodoWrite format (mandatory)` → WARN\n\n**Why:** Without explicit `Skill()` code blocks and Codex fallback semantics, agents forget to invoke workers or treat `Skill()` as unknown syntax. This is a recurring failure pattern in coordinators.\n\n## D9: Pattern Compliance (conditional -- `ln-6*` audit skills only)\n- References `references/two_layer_detection.md` via MANDATORY READ\n- Scoring formula consistent: `penalty = (C*2.0) + (H*1.0) + (M*0.5) + (L*0.2)`\n- Report structure follows `references/templates/audit_worker_report_template.md`\n\n## D10: Cross-Skill Behavioral Contracts\n\nWhen a primary skill changes its behavioral contract (fast-track matrix, dispatch pattern, input/output format), verify ALL skills it delegates to or receives delegation from have compatible contracts.\n\n- **Dispatch consistency:** If skill A's Worker Invocation table says \"invoke ln-B via Skill tool\" -- verify ln-B is actually designed for inline invocation (not Agent-only). Read Worker Invocation tables in both skills\n- **Fast-track cascade:** If skill A has a fast-track matrix that skips/modifies sub-skill behavior -- verify each sub-skill's SKILL.md supports that modified behavior. Example: if ln-500 says \"ln-520 RUN simplified\" -- verify ln-520 has a `--simplified` input\n- **Input contract compatibility:** If skill A delegates to B with specific args -- verify B's Inputs table accepts those args. If B has prerequisites -- verify A's state satisfies them when calling B\n- **Status transition ownership:** If multiple skills can set the same kanban status -- verify exactly ONE is the designated writer (no conflicts, no gaps)\n\n## D11: Resource Lifecycle Integrity\n\nFor skills that manage shared resources (worktrees, branches, `.hex-skills/pipeline/` state, `.hex-skills/agent-review/` files):\n\n- **Creator-User-Cleaner chain:** Trace who creates, who uses, who cleans up each resource. Verify no gaps (resource created but never cleaned) or conflicts (cleanup while still in use)\n- **Inline vs Isolated execution:** If a skill may run both as Skill (inline) and as Agent (isolated), verify resource operations work in both modes. Example: `git worktree remove` fails if CWD is inside the worktree\n- **Checkpoint contract:** If a skill writes checkpoints -- verify the recovery consumer reads the same fields. If fields are added/removed -- verify both sides match\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":10550,"content_sha256":"cb288598686d88e7e720d4e00b19e3c9b192a825669ae1ed07b8b5171c2b67b8"},{"filename":"references/templates/audit_worker_report_template.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/templates/audit_worker_report_template.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Audit Worker Report Template\n\nMarkdown evidence envelope for audit workers. Coordinators consume JSON summaries first; this report supports the verdict.\n\n## Path\n\nWrite once under `.hex-skills/runtime-artifacts/runs/{run_id}/audit-report/` using a stable name such as `{worker-id}-{slug}.md` or `{worker-id}-{slug}-{domain}.md`.\n\n## Required Shape\n\n```markdown\n# {Category Name} Audit Report\n\n\u003c!-- AUDIT-META\nworker: ln-62X\ncategory: {Category Name}\ndomain: {domain_name|global}\nscan_path: {scan_path|.}\nscore: {X.X}\ntotal_issues: {N}\ncritical: {N}\nhigh: {N}\nmedium: {N}\nlow: {N}\nstatus: completed\n-->\n\n## Checks\n\n| ID | Check | Status | Details |\n|----|-------|--------|---------|\n| {check_id} | {name} | {passed|failed|warning|skipped} | {brief evidence} |\n\n## Findings\n\n| Severity | Location | Issue | Principle | Recommendation | Effort |\n|----------|----------|-------|-----------|----------------|--------|\n| HIGH | path/file.ts:42 | What is wrong | Rule | How to fix | M |\n```\n\n## Optional Machine Blocks\n\nAdd only when consumed by the worker or coordinator: `FINDINGS-EXTENDED`, `DATA-EXTENDED`, or extra informational score fields. The primary penalty-based `score` remains canonical.\n\n## Writing Rules\n\n- Build the full report before writing; never leave partial reports.\n- Sort findings by severity: CRITICAL, HIGH, MEDIUM, LOW.\n- Keep recommendations actionable and effort as `S`, `M`, or `L`.\n- Also write the JSON summary to the path required by `audit_worker_core_contract.md`.\n\n---\n**Version:** 2.0.0\n**Last Updated:** 2026-02-15\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1686,"content_sha256":"54dc1ab21118b6bc86944950682698a246fe7b83133496556d2152c02c0b813c"},{"filename":"references/two_layer_detection.md","content":"\u003c!-- SOURCE-OF-TRUTH: shared/references/two_layer_detection.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->\n\n# Two-Layer Detection\n\nAudit workers use two-layer detection to avoid noisy grep-only reports.\n\n## Layer 1: Candidate Scan\n\nFind possible issues with the cheapest reliable source:\n- text search for known signatures\n- project tools such as linters, type checks, dependency scanners, or audit commands\n- `hex-graph audit_workspace` for structural clone/duplication candidates when indexed and relevant\n\nLayer 1 output is only a candidate list. A candidate is not a finding until verified.\n\n## Layer 2: Context Verification\n\nFor each material candidate:\n1. Read enough surrounding code to understand scope, data flow, ownership, and lifecycle.\n2. Apply the worker's domain questions and false-positive filters.\n3. Classify as `confirmed`, `false_positive`, or `needs_context`.\n4. Report only confirmed findings, plus `needs_context` as low-severity notes when useful.\n\nLayer 2 is mandatory when the finding depends on scope, architecture, concurrency, lifecycle, cross-process behavior, or any pattern with high false-positive risk. It is optional for unambiguous tool findings that already include structured severity and location.\n\n## Finding Standard\n\nEvery reported issue needs:\n- precise location\n- why the issue is real in context\n- severity and effort\n- recommendation\n- evidence basis when consumed by a coordinator\n\n---\n**Version:** 1.0.0\n**Last Updated:** 2026-03-04\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1504,"content_sha256":"9ed77a11fb7478157fc684eb831721561c670e3e973b75fe4932651d77131c5c"}],"content_json":{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Paths:","type":"text","marks":[{"type":"strong"}]},{"text":" File paths (","type":"text"},{"text":"references/","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"../ln-*","type":"text","marks":[{"type":"code_inline"}]},{"text":") are relative to this skill directory.","type":"text"}]}]},{"type":"heading","attrs":{"level":1},"content":[{"text":"ln-162-skill-reviewer","type":"text"}]},{"type":"paragraph","content":[{"text":"Type:","type":"text","marks":[{"type":"strong"}]},{"text":" L3 Worker (standalone-capable) ","type":"text"},{"text":"Category:","type":"text","marks":[{"type":"strong"}]},{"text":" 1XX Documentation Pipeline","type":"text"}]},{"type":"paragraph","content":[{"text":"Universal reviewer with two modes:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SKILL","type":"text","marks":[{"type":"code_inline"}]},{"text":" for ","type":"text"},{"text":"ln-*/SKILL.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"COMMAND","type":"text","marks":[{"type":"code_inline"}]},{"text":" for ","type":"text"},{"text":".claude/commands/*.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"repo suite for this skills repository when ","type":"text"},{"text":"repo","type":"text","marks":[{"type":"code_inline"}]},{"text":" / ","type":"text"},{"text":"repo-checks","type":"text","marks":[{"type":"code_inline"}]},{"text":" is requested or the current repo is ","type":"text"},{"text":"claude-code-skills","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Plan Mode behavior:","type":"text","marks":[{"type":"strong"}]},{"text":" Phases 1-4 and 6-7 are research. Run them fully in Plan Mode, write the report plus fix list into the plan, and apply edits only after approval.","type":"text"}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Mode Detection","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Condition","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Mode","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Review Profile","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"ln-*/SKILL.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" files exist in CWD","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SKILL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Full D1-D11 + M1-M6","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":".claude/commands/*.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" files exist","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"COMMAND","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Structural + actionability","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Both exist","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SKILL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Override with ","type":"text"},{"text":"$ARGUMENTS=commands","type":"text","marks":[{"type":"code_inline"}]}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Input","type":"text"}]},{"type":"paragraph","content":[{"text":"$ARGUMENTS","type":"text","marks":[{"type":"code_inline"}]},{"text":" options:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"empty -> auto-detect mode and scope","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ln-400 ln-500","type":"text","marks":[{"type":"code_inline"}]},{"text":" -> SKILL mode, specific skills","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"repo","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"repo-checks","type":"text","marks":[{"type":"code_inline"}]},{"text":" -> run canonical repo-specific checks after universal review","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"commands","type":"text","marks":[{"type":"code_inline"}]},{"text":" -> COMMAND mode, all ","type":"text"},{"text":".claude/commands/*.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"deploy.md run-tests.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" -> COMMAND mode, specific files","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"When invoked by another skill, file paths may be passed directly.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"SKILL Mode","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Scope Detection","type":"text"}]},{"type":"paragraph","content":[{"text":"If ","type":"text"},{"text":"$ARGUMENTS","type":"text","marks":[{"type":"code_inline"}]},{"text":" is provided:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"treat each token as a skill directory prefix","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"glob ","type":"text"},{"text":"{prefix}*/SKILL.md","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"paragraph","content":[{"text":"If ","type":"text"},{"text":"$ARGUMENTS","type":"text","marks":[{"type":"code_inline"}]},{"text":" is empty:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"inspect git diff, staged files, and untracked files","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"collect primary skill dirs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"collect affected skills referencing changed shared files","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"collect dependency skills from worker tables and ","type":"text"},{"text":"Skill()","type":"text","marks":[{"type":"code_inline"}]},{"text":" invocations","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Report: ","type":"text"},{"text":"Scope: {N} primary, {M} affected, {K} dependency skills.","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: Automated Verification","type":"text"}]},{"type":"paragraph","content":[{"text":"Run:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Never pass a giant mixed scope in one invocation.\n# Split by `ln-NXX` family or by coordinator/worker group.\nbash references/scripts/run_checks.sh {batch_1 SKILL.md files}\nbash references/scripts/run_checks.sh {batch_2 SKILL.md files}","type":"text"}]},{"type":"paragraph","content":[{"text":"Batching rules:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"keep each invocation within one ","type":"text"},{"text":"ln-NXX","type":"text","marks":[{"type":"code_inline"}]},{"text":" family when possible","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"if scope mixes coordinators and workers, split them into separate invocations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"if one family is still large, chunk it into 5-10 files per invocation","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Automated failures are pre-verified. Record every one.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Structural Review","type":"text"}]},{"type":"paragraph","content":[{"text":"MANDATORY READ:","type":"text","marks":[{"type":"strong"}]},{"text":" Load ","type":"text"},{"text":"references/structural_review.md","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"references/skill_contract.md","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"references/procedural_skill_sop_guide.md","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"references/mcp_applicability_matrix.md","type":"text","marks":[{"type":"code_inline"}]},{"text":", and ","type":"text"},{"text":"references/mcp_tool_preferences.md","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"paragraph","content":[{"text":"Review every skill in scope across D1-D11.","type":"text"}]},{"type":"paragraph","content":[{"text":"Treat these as structural issues, not style nits:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"missing ","type":"text"},{"text":"**Type:**","type":"text","marks":[{"type":"code_inline"}]},{"text":" when role-sensitive checks depend on it","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"worker independence violations in L3 workers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"broken shared paths","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"stale root-doc assumptions — CLAUDE.md duplicating AGENTS.md content instead of using the ","type":"text"},{"text":"@AGENTS.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" import stub with a bounded harness delta","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"markdown-analysis skills missing ","type":"text"},{"text":"markdown_read_protocol.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"extraction or audit skills contradicting the shared docs-quality contract","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"skills contradicting the shared skill contract","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"skills that should make ","type":"text"},{"text":"hex-line","type":"text","marks":[{"type":"code_inline"}]},{"text":" primary but only describe built-in file tools","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"skills that should make ","type":"text"},{"text":"hex-graph","type":"text","marks":[{"type":"code_inline"}]},{"text":" primary but still describe grep/manual analysis as the default path","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"skills that add ","type":"text"},{"text":"hex-graph","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"hex-line","type":"text","marks":[{"type":"code_inline"}]},{"text":" with no real applicability per the shared matrix","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"wrong MCP namespaces such as ","type":"text"},{"text":"mcp__hex_graph__...","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"procedural skills with vague modal words, compound high-risk steps, missing point-of-use checklists, missing why for risky steps, missing executable preflight, or missing evidence","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 4: Intent Review","type":"text"}]},{"type":"paragraph","content":[{"text":"MANDATORY READ:","type":"text","marks":[{"type":"strong"}]},{"text":" Load ","type":"text"},{"text":"references/intent_review.md","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"paragraph","content":[{"text":"Apply M1-M6 to primary skills only. Read the git diff for each primary skill.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 5: Fix","type":"text"}]},{"type":"paragraph","content":[{"text":"Auto-fix deterministic issues:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"wrong paths","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"stale references","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"duplicated wording","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"worker-independence violations with exact removals","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"copied docs shell sections in command files","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Do not guess on ambiguous behavior.","type":"text"}]},{"type":"paragraph","content":[{"text":"After fixes, re-read each primary skill end-to-end and compress redundant wording without changing behavior.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 6: Report","type":"text"}]},{"type":"paragraph","content":[{"text":"Verdict rules:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"any structural violation not auto-fixed -> ","type":"text"},{"text":"FAIL","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"only advisory intent concerns remain -> ","type":"text"},{"text":"PASS with CONCERNS","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"zero findings -> ","type":"text"},{"text":"PASS","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"paragraph","content":[{"text":"Report format:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"## Skill Coherence Review -- {PASS|PASS with CONCERNS|FAIL}\n\n**Scope:** {reviewed skills}\n**Verdict:** {verdict}","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 7: Volatile Numbers Cleanup","type":"text"}]},{"type":"paragraph","content":[{"text":"Remove stale aggregate counts from SKILL.md files. Keep only local counts intrinsic to the reviewed file.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Repo Suite Mode","type":"text"}]},{"type":"paragraph","content":[{"text":"Use when running inside this repository or when ","type":"text"},{"text":"$ARGUMENTS","type":"text","marks":[{"type":"code_inline"}]},{"text":" includes ","type":"text"},{"text":"repo","type":"text","marks":[{"type":"code_inline"}]},{"text":" / ","type":"text"},{"text":"repo-checks","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Universal Review","type":"text"}]},{"type":"paragraph","content":[{"text":"Run the applicable SKILL or COMMAND mode first. Do not skip the universal review.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: Repo-Specific Checks","type":"text"}]},{"type":"paragraph","content":[{"text":"Run the canonical repo suite:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"node plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/repo_review_suite.mjs","type":"text"}]},{"type":"paragraph","content":[{"text":"Default repo suite runtime policy:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"default: ","type":"text"},{"text":"--runtime quick","type":"text","marks":[{"type":"code_inline"}]},{"text":" (implicit) runs bounded smoke coverage only","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"structure-only: ","type":"text"},{"text":"--runtime skip","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"release/CI: ","type":"text"},{"text":"--runtime full","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"node plugins/documentation-pipeline/skills/ln-162-skill-reviewer/references/scripts/repo_review_suite.mjs --runtime full","type":"text"}]},{"type":"paragraph","content":[{"text":"The suite owns R1-R27. Do not copy those checks into host-specific command files. Do not use the full runtime suite as the default interactive review gate; it is intentionally release-grade and can exceed normal review latency.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Combined Report","type":"text"}]},{"type":"paragraph","content":[{"text":"Merge the universal review verdict and repo suite verdict:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"| Source | Verdict | Details |\n|--------|---------|---------|\n| Universal review | {PASS|PASS with CONCERNS|FAIL} | {summary} |\n| Repo suite | {PASS|PASS with WARNINGS|FAIL} | {R1-R27 summary} |\n| Combined | {worst verdict} | |","type":"text"}]},{"type":"paragraph","content":[{"text":"List all FAIL and WARN items with file paths and fix descriptions.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"COMMAND Mode","type":"text"}]},{"type":"paragraph","content":[{"text":"MANDATORY READ:","type":"text","marks":[{"type":"strong"}]},{"text":" Load ","type":"text"},{"text":"references/command_review_criteria.md","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Scope Detection","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"explicit file paths -> review those files","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"commands","type":"text","marks":[{"type":"code_inline"}]},{"text":" -> glob ","type":"text"},{"text":".claude/commands/*.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"coordinator-supplied file list -> review those files","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: Review","type":"text"}]},{"type":"paragraph","content":[{"text":"For each command file:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"apply all command review criteria","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"verify source provenance","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"verify no copied docs shell sections remain","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Fix","type":"text"}]},{"type":"paragraph","content":[{"text":"Auto-fix where safe:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"missing frontmatter","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"missing ","type":"text"},{"text":"allowed-tools","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"description too long","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"missing ","type":"text"},{"text":"Last Updated","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"exact copied docs shell sections","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 4: Report","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"## Command Review -- {N} files\n\n| File | Verdict | Issues |\n|------|---------|--------|\n\nVerdicts: PASS / FIXED / WARN / FAIL\nPass rate: {X}%","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Rules","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automated checks are non-negotiable.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Read all scoped files before reporting.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Fix deterministic issues immediately.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Do not update versions or dates unless the user explicitly requests it.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"shared/","type":"text","marks":[{"type":"code_inline"}]},{"text":" changes affect all referencing skills.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Worker independence is mandatory for L3 workers:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"no ","type":"text"},{"text":"**Coordinator:**","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"no ","type":"text"},{"text":"**Parent:**","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"no required caller declaration","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Docs-model drift is a structural defect, not a preference.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Unsupported platform APIs are prohibited outside clearly marked historical references.","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reference Files","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/structural_review.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/intent_review.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/automated_checks.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/scripts/run_checks.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/scripts/run_runtime_suite.mjs","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/scripts/repo_review_suite.mjs","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/command_review_criteria.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/scripts/check_marketplace.mjs","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Definition of Done","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Scope detected","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Automated checks executed","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"D1-D11 reviewed across all scoped skills","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"M1-M6 evaluated for primary skills","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Fixable findings auto-fixed","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Post-fix holistic compaction completed","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Final verdict report generated","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Version:","type":"text","marks":[{"type":"strong"}]},{"text":" 1.0.0 ","type":"text"},{"text":"Last Updated:","type":"text","marks":[{"type":"strong"}]},{"text":" 2026-03-26","type":"text"}]}]},"metadata":{"date":"2026-06-05","name":"ln-162-skill-reviewer","author":"@skillopedia","source":{"stars":480,"repo_name":"claude-code-skills","origin_url":"https://github.com/levnikolaevich/claude-code-skills/blob/HEAD/plugins/documentation-pipeline/skills/ln-162-skill-reviewer/SKILL.md","repo_owner":"levnikolaevich","body_sha256":"c5ed49fbf6cd6d64d46c33dd5ef7ad4cfd18b6120a33fb3e95c7a95bf244ed39","cluster_key":"98967a086f38415ac7618737f114bbb3c0ff71c6b2462582b6583ae47c4a0d99","clean_bundle":{"format":"clean-skill-bundle-v1","source":"levnikolaevich/claude-code-skills/plugins/documentation-pipeline/skills/ln-162-skill-reviewer/SKILL.md","attachments":[{"id":"2048730f-1e2f-51ed-a6ed-c7f2c20c45ce","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2048730f-1e2f-51ed-a6ed-c7f2c20c45ce/attachment.md","path":"references/automated_checks.md","size":9139,"sha256":"36ad3bc7f2e51ab2efe4b98ca31e1e9245852c1b35f5fcdf17963fd8f5e62b2a","contentType":"text/markdown; charset=utf-8"},{"id":"b0c63cda-989f-5fe9-9f6f-fc95f3fa5396","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b0c63cda-989f-5fe9-9f6f-fc95f3fa5396/attachment.md","path":"references/clean_code_checklist.md","size":2379,"sha256":"55b91e1cf53fe3d97bb46fe0c9543ae422e898f1c1c1da1ec1a87d8d2c219cdb","contentType":"text/markdown; charset=utf-8"},{"id":"1e758dca-6bff-5f79-aa3e-8bc6f142e552","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1e758dca-6bff-5f79-aa3e-8bc6f142e552/attachment.md","path":"references/command_review_criteria.md","size":2394,"sha256":"e6191347c0608982362c3cd0914d7c944b105685e656d5b2406dc5db2cb21ff6","contentType":"text/markdown; charset=utf-8"},{"id":"f00f10d3-a6c2-51d9-8205-71183c53adf2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f00f10d3-a6c2-51d9-8205-71183c53adf2/attachment.md","path":"references/creation_quality_checklist.md","size":6700,"sha256":"cee1e4dbb27277503f662d4e6382399937b163e878b205cc3438a2a3e0dd94bf","contentType":"text/markdown; charset=utf-8"},{"id":"b1140455-fa33-5d91-8ccb-3ab224f5d8a6","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b1140455-fa33-5d91-8ccb-3ab224f5d8a6/attachment.md","path":"references/goal_articulation_gate.md","size":3608,"sha256":"b4d5ef0784baacf935a468e2e47c11b87eddb749375f890e9d0e95c986e06841","contentType":"text/markdown; charset=utf-8"},{"id":"e0124c49-bf8f-57d5-8ff6-ccad77a139e0","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/e0124c49-bf8f-57d5-8ff6-ccad77a139e0/attachment.md","path":"references/humanizer_checklist.md","size":4325,"sha256":"ff8b71a1dc664e6070b015a5b6d8c054abe4ceef6863e7e3312bdf1cf47ed639","contentType":"text/markdown; charset=utf-8"},{"id":"386f67e4-43ff-5b63-aa6f-4222cbb02126","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/386f67e4-43ff-5b63-aa6f-4222cbb02126/attachment.md","path":"references/intent_review.md","size":4346,"sha256":"3ad9d3bd6dcaae7cfcd37d7ba270b489fe711960447731525dbecf0eade11261","contentType":"text/markdown; charset=utf-8"},{"id":"1900ab12-3244-5288-bf6f-bed4d4e6771f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1900ab12-3244-5288-bf6f-bed4d4e6771f/attachment.md","path":"references/loop_health_contract.md","size":2462,"sha256":"ce2741dc3e881242fd0b88035ed7a66f9fbc9762e3231ef16b82e0e296c313e0","contentType":"text/markdown; charset=utf-8"},{"id":"722004c9-94df-52a8-8b23-ac13570e68fc","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/722004c9-94df-52a8-8b23-ac13570e68fc/attachment.md","path":"references/mcp_applicability_matrix.md","size":4405,"sha256":"0c5a4ee76119cd2842c0a40c336f80956bd64f9240158fd70a12895d11fbc51c","contentType":"text/markdown; charset=utf-8"},{"id":"0f47223d-5810-5a90-af9a-267b2afd7603","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/0f47223d-5810-5a90-af9a-267b2afd7603/attachment.md","path":"references/mcp_integration_patterns.md","size":1567,"sha256":"f0aff34db7d833bafdabe6080d55f0545046e07e1552778dafc8eb722f963659","contentType":"text/markdown; charset=utf-8"},{"id":"292cc22a-5f76-5d90-a881-3259cce2b038","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/292cc22a-5f76-5d90-a881-3259cce2b038/attachment.md","path":"references/mcp_tool_preferences.md","size":2338,"sha256":"578914a82f4825c50cee778ecdefd9346cd60f3a24f2f64d1df7f078dade1e3d","contentType":"text/markdown; charset=utf-8"},{"id":"f51f77eb-3fab-5663-a514-5dd0ee4d8f36","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f51f77eb-3fab-5663-a514-5dd0ee4d8f36/attachment.md","path":"references/meta_analysis_protocol.md","size":1509,"sha256":"b97ce62dc95b7fe171baef2fbc5f7cdb91626e1b2fee14a7850cd02c02f77b49","contentType":"text/markdown; charset=utf-8"},{"id":"162d75d6-2b60-542b-b784-f889b8930d8d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/162d75d6-2b60-542b-b784-f889b8930d8d/attachment.md","path":"references/procedural_skill_sop_guide.md","size":2934,"sha256":"b70e5a0d4a5bf75790f04fa3348b976d30fd86c4ef6eefa038c2c3a0df8d35fe","contentType":"text/markdown; charset=utf-8"},{"id":"8ce71d02-75ac-5358-b4f5-23a968bbddec","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8ce71d02-75ac-5358-b4f5-23a968bbddec/attachment.md","path":"references/researchgraph_mcp_usage.md","size":2981,"sha256":"128b6ff36dbe20a5d2337dba38862a6b4c0d7f85867c7c27f3c95589f8f66016","contentType":"text/markdown; charset=utf-8"},{"id":"cf1d0f88-1a91-584d-9660-ce23238f331b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cf1d0f88-1a91-584d-9660-ce23238f331b/attachment.mjs","path":"references/scripts/check_marketplace.mjs","size":491,"sha256":"623b0cb8034f6463248deb7c639bf01e457db87b8ac90d3a5e28ffc5c753f3f9","contentType":"text/javascript"},{"id":"f2f52c23-5806-55f2-a01e-448cf7d3e6a5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f2f52c23-5806-55f2-a01e-448cf7d3e6a5/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/artifacts.mjs","size":2463,"sha256":"b920166d0ad5bad12343c792a8b8f59abc88172d405c238290b8cf20f70a3898","contentType":"text/javascript"},{"id":"67374c39-9125-5650-9baf-dfa3253af9ad","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/67374c39-9125-5650-9baf-dfa3253af9ad/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/cli-helpers.mjs","size":3569,"sha256":"97c265d018bcc12185f997bf9398e818450678d5d34662ceb9e91a46bedb4ea5","contentType":"text/javascript"},{"id":"6e45765e-51ee-5f73-b171-6235cb749c00","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6e45765e-51ee-5f73-b171-6235cb749c00/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/core.mjs","size":19048,"sha256":"c98153f400f67794480805bfa08004a9011a6d0830848fcfb27d4407ec765bbd","contentType":"text/javascript"},{"id":"5439a188-9f54-5d5f-8ed7-1d6afdbc1ea1","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/5439a188-9f54-5d5f-8ed7-1d6afdbc1ea1/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/loop-health.mjs","size":7667,"sha256":"2455b79952b6bf708840ff0bb0406e374bbd51fb2a7c374b4588c25deb42af46","contentType":"text/javascript"},{"id":"04f175b5-604e-58f8-ae77-8472a3623eff","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/04f175b5-604e-58f8-ae77-8472a3623eff/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/runtime-constants.mjs","size":3880,"sha256":"66610a99e5fb0d9108e93f3a74cabd2614089911b354019035968f918478a37b","contentType":"text/javascript"},{"id":"6c65dd19-3d5b-599b-a7f4-1caf0536c82a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6c65dd19-3d5b-599b-a7f4-1caf0536c82a/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/schemas.mjs","size":38117,"sha256":"b41e4ceccb193d909d60a344e306fd08b587a9584c96c32dfd09b036c429bbc1","contentType":"text/javascript"},{"id":"d5fdcdec-53c7-5671-8233-fb7238556fb4","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/d5fdcdec-53c7-5671-8233-fb7238556fb4/attachment.mjs","path":"references/scripts/coordinator-runtime/lib/validate.mjs","size":4943,"sha256":"8aea4a181f03a1d22002563f844a973e5a71c45deb7fe6e668d37c5ea27b3196","contentType":"text/javascript"},{"id":"b4fc2117-7757-5897-a157-19fe1388998b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b4fc2117-7757-5897-a157-19fe1388998b/attachment.mjs","path":"references/scripts/coordinator-runtime/test/cli-test-helpers.mjs","size":1533,"sha256":"92043c0a046a64548210abc7c50b347a8e27a2eda715c1d7aed7dc2e0fed41d8","contentType":"text/javascript"},{"id":"017d33d5-8260-5ed7-8faa-dd1fc732e295","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/017d33d5-8260-5ed7-8faa-dd1fc732e295/attachment.mjs","path":"references/scripts/coordinator-runtime/test/consistency-scan.mjs","size":11847,"sha256":"cd64a5ff6a1c750c470c34edb04a587c1c8b84ca2c89c8336673ffc6a7f874a6","contentType":"text/javascript"},{"id":"bb4eedfd-884f-5106-a742-4fb748e7239d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bb4eedfd-884f-5106-a742-4fb748e7239d/attachment.mjs","path":"references/scripts/coordinator-runtime/test/loop-health.mjs","size":3347,"sha256":"6271efc6d67c87a17725cfe6f9cf2b698c2adac549d2b195de4dc06acc392187","contentType":"text/javascript"},{"id":"96c4c9d5-dba6-5e48-aa72-4df600e6bca5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/96c4c9d5-dba6-5e48-aa72-4df600e6bca5/attachment.mjs","path":"references/scripts/coordinator-runtime/test/platform-regression.mjs","size":10470,"sha256":"fbd029937817751483080fe2170b60c0093e86c10195cbb340310e0a68423384","contentType":"text/javascript"},{"id":"b819a9c4-e4c2-5464-9dd5-d8d94d405a5b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b819a9c4-e4c2-5464-9dd5-d8d94d405a5b/attachment.mjs","path":"references/scripts/docs-pipeline-runtime/lib/phases.mjs","size":615,"sha256":"3f817658715cbeea3abf1b5402181569de33c3ba5e11d7bff37088e26d8e48ec","contentType":"text/javascript"},{"id":"bc4f2cf5-916c-5fee-9ac4-75df2578d31c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bc4f2cf5-916c-5fee-9ac4-75df2578d31c/attachment.mjs","path":"references/scripts/docs-pipeline-runtime/lib/store.mjs","size":2431,"sha256":"083b4e37146a3f16f95c661f3768e977260e30144a2dc09e1cbc6499e076765d","contentType":"text/javascript"},{"id":"f7fa5f10-6dce-5045-a27c-10f67ac39072","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f7fa5f10-6dce-5045-a27c-10f67ac39072/attachment.mjs","path":"references/scripts/environment-setup-runtime/cli.mjs","size":8150,"sha256":"5fa89e8445e4a26197ddec16e6a86bd6a220f1ce5306b9b59f0f44ea8182b5fe","contentType":"text/javascript"},{"id":"c17ccda9-9f41-55e8-b038-efdabbfd5f5d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c17ccda9-9f41-55e8-b038-efdabbfd5f5d/attachment.mjs","path":"references/scripts/environment-setup-runtime/lib/guards.mjs","size":4450,"sha256":"53295615de28d93446ff342fd148a8beffa13b1709afe7d6421b1d7349c43404","contentType":"text/javascript"},{"id":"cb7f6832-0404-53d1-8b97-b6d0fd1e9f0a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cb7f6832-0404-53d1-8b97-b6d0fd1e9f0a/attachment.mjs","path":"references/scripts/environment-setup-runtime/lib/phases.mjs","size":686,"sha256":"2400c3a89bc6a3007f915ebd70e021ac42d6d294b95c9c7ce09402cd7eba18b3","contentType":"text/javascript"},{"id":"70d23bd8-b437-5052-901c-2844f4ecc65a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/70d23bd8-b437-5052-901c-2844f4ecc65a/attachment.mjs","path":"references/scripts/environment-setup-runtime/lib/store.mjs","size":6246,"sha256":"ba6a0b2203d10c72d8bf95fde4e695690b096613c558d59314ed89b04fb22eae","contentType":"text/javascript"},{"id":"02da7105-5170-53c1-8780-9b95f86abc6b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/02da7105-5170-53c1-8780-9b95f86abc6b/attachment.mjs","path":"references/scripts/environment-setup-runtime/test/guards.mjs","size":5248,"sha256":"5785af4d67d418c8d1e400ad3564ae7124965f5a409d0c655a8eb1dafb52dd5e","contentType":"text/javascript"},{"id":"6182ff64-33f6-56ae-996d-ac920aa67a42","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6182ff64-33f6-56ae-996d-ac920aa67a42/attachment.mjs","path":"references/scripts/environment-setup-runtime/test/smoke.mjs","size":4826,"sha256":"40ea44d6f9200eaffd59003f027aa81985bc6819a651bc17c6f67f9aaedd0cf9","contentType":"text/javascript"},{"id":"944484d3-f1fc-5f40-8fe9-1f6de0a6cd1d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/944484d3-f1fc-5f40-8fe9-1f6de0a6cd1d/attachment.mjs","path":"references/scripts/epic-planning-runtime/cli.mjs","size":5906,"sha256":"8781705aa6bd9955377a5b3a1b9b0cc76df509b27fdd53600c1e17091856c43b","contentType":"text/javascript"},{"id":"b48772c2-fe5a-5e2d-8d62-48f3b007bbb6","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b48772c2-fe5a-5e2d-8d62-48f3b007bbb6/attachment.mjs","path":"references/scripts/epic-planning-runtime/lib/guards.mjs","size":2756,"sha256":"c5d01934929be8c916c695ed236a83b0a4497efd63c55a69312f301b4eabaa8c","contentType":"text/javascript"},{"id":"12e5c924-96ac-5656-b85f-56a36146bfd3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/12e5c924-96ac-5656-b85f-56a36146bfd3/attachment.mjs","path":"references/scripts/epic-planning-runtime/lib/phases.mjs","size":667,"sha256":"47d42d97c20eabe9a111567c880d2000b6639bd329baa8ffc7f66f7b15e122d9","contentType":"text/javascript"},{"id":"b77c16af-87b0-50b4-afad-26ccc4ad5037","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b77c16af-87b0-50b4-afad-26ccc4ad5037/attachment.mjs","path":"references/scripts/epic-planning-runtime/lib/store.mjs","size":2331,"sha256":"593ba09240b1a7cc4c7253b6bed4adb82598f1284ce2e71fe1028e8b719f42e1","contentType":"text/javascript"},{"id":"f79bd510-1f41-515c-a95a-264128842b14","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f79bd510-1f41-515c-a95a-264128842b14/attachment.mjs","path":"references/scripts/evaluation-runtime/cli.mjs","size":14444,"sha256":"196a9e9785df6219fcfeca7ad0508e3890f4e02032f34b542a44b102362bf3f9","contentType":"text/javascript"},{"id":"6e7e6aa6-204c-567a-af1f-9889a5d47984","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6e7e6aa6-204c-567a-af1f-9889a5d47984/attachment.mjs","path":"references/scripts/evaluation-runtime/lib/guards.mjs","size":9053,"sha256":"243d781651658f9acf3663c3d6fc587dc7438f31a1024afcc03f48f3af5bdc54","contentType":"text/javascript"},{"id":"20704e4f-bb20-505e-a844-0811d7d393fb","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/20704e4f-bb20-505e-a844-0811d7d393fb/attachment.mjs","path":"references/scripts/evaluation-runtime/lib/store.mjs","size":12721,"sha256":"89d68be3cb6dd9d706837c2ef98e465b2e9b280498a7be6a5323faaf23137e71","contentType":"text/javascript"},{"id":"f895baaa-aea8-5378-8bb0-54439f02a0d8","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f895baaa-aea8-5378-8bb0-54439f02a0d8/attachment.mjs","path":"references/scripts/optimization-runtime/cli.mjs","size":10435,"sha256":"cc82803448cabc9c7b8d59e8ebaf95443070d6b27094cc4e7dae253d413a0370","contentType":"text/javascript"},{"id":"30f75f50-b1ad-5a08-91db-897c359bcdae","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/30f75f50-b1ad-5a08-91db-897c359bcdae/attachment.mjs","path":"references/scripts/optimization-runtime/lib/guards.mjs","size":10831,"sha256":"1e6777b9cd79d140d0ea13074b200300a3b9c924a8d0f0a6167ce70274579e3d","contentType":"text/javascript"},{"id":"915c7d40-50ea-5ed0-8a4c-cb410c72c708","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/915c7d40-50ea-5ed0-8a4c-cb410c72c708/attachment.mjs","path":"references/scripts/optimization-runtime/lib/phases.mjs","size":818,"sha256":"3041ce9834196e34da55e49254afc4601d6903181dca4dde076091144b6c5ebc","contentType":"text/javascript"},{"id":"4160f941-70b7-5d8a-b6d2-d42fb65447ec","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4160f941-70b7-5d8a-b6d2-d42fb65447ec/attachment.mjs","path":"references/scripts/optimization-runtime/lib/store.mjs","size":8536,"sha256":"43744db56f805a6f05faf7b78a6778af89eb0aec54e432295387426a0061204c","contentType":"text/javascript"},{"id":"28de3983-f171-5b03-a088-71c9d4e6e79f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/28de3983-f171-5b03-a088-71c9d4e6e79f/attachment.mjs","path":"references/scripts/planning-runtime/lib/cli.mjs","size":3949,"sha256":"7907a68b38b2ae9386437250e432306e358d2016ac52447ea4c66b548716a9b5","contentType":"text/javascript"},{"id":"b3b0face-5453-5c48-ae2f-bdeab3db7abf","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b3b0face-5453-5c48-ae2f-bdeab3db7abf/attachment.mjs","path":"references/scripts/planning-runtime/lib/guards.mjs","size":1818,"sha256":"87481a136e904989039af61968581cef93a67919f7b1b840c6c05d5eb32ff441","contentType":"text/javascript"},{"id":"21af90e2-c049-576d-8625-03d184e8d1ac","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/21af90e2-c049-576d-8625-03d184e8d1ac/attachment.mjs","path":"references/scripts/planning-runtime/lib/store.mjs","size":6938,"sha256":"faefae1ce85c346e39ce9d9708a624b03aed0ee518275e28748ae90acd8ea83a","contentType":"text/javascript"},{"id":"cd030f8b-d82f-5509-8e97-66aeb488f90a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cd030f8b-d82f-5509-8e97-66aeb488f90a/attachment.mjs","path":"references/scripts/quality-runtime/cli.mjs","size":7803,"sha256":"c8bccac60cb1f89d48be06f1f19ce448edfd78fed985321387ec15ebd27e4f90","contentType":"text/javascript"},{"id":"8b9d9419-0b51-5d7c-942b-c42414c58bf9","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8b9d9419-0b51-5d7c-942b-c42414c58bf9/attachment.mjs","path":"references/scripts/quality-runtime/lib/guards.mjs","size":4324,"sha256":"000ee64b962965cce41c5334419068f9c23247241f14a948a41d07ac2229829b","contentType":"text/javascript"},{"id":"15250df8-3645-5a76-a97a-47e845bbb3fb","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/15250df8-3645-5a76-a97a-47e845bbb3fb/attachment.mjs","path":"references/scripts/quality-runtime/lib/phases.mjs","size":752,"sha256":"34c816ff0c7aa64e7e5066a8e5a510818a3c32699f2e19cfcec8857575fc27c8","contentType":"text/javascript"},{"id":"514ff53f-4ad6-5462-8507-93af59ed17cc","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/514ff53f-4ad6-5462-8507-93af59ed17cc/attachment.mjs","path":"references/scripts/quality-runtime/lib/store.mjs","size":3337,"sha256":"01a8c542c35faa576349b3faaa27808b91df61315cad1920c7d673c08e41dd63","contentType":"text/javascript"},{"id":"610ec2fe-efa5-5c12-a9b1-1a2f4ca34426","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/610ec2fe-efa5-5c12-a9b1-1a2f4ca34426/attachment.mjs","path":"references/scripts/repo_review_suite.mjs","size":24468,"sha256":"04cf00b663e7efaf2daaab64e958a38df78f28c43d7e3b725a4f537e856adbe1","contentType":"text/javascript"},{"id":"bf059aca-c1b0-590c-824f-3c01ee100994","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bf059aca-c1b0-590c-824f-3c01ee100994/attachment.sh","path":"references/scripts/run_checks.sh","size":14085,"sha256":"f4dfec54f90aaf934fe70c1aae17a837006646332d800ad17223fc53cc9dd358","contentType":"application/x-sh; charset=utf-8"},{"id":"32461cda-fd80-5bef-a4bd-1997d90f1bd3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/32461cda-fd80-5bef-a4bd-1997d90f1bd3/attachment.mjs","path":"references/scripts/run_runtime_suite.mjs","size":7818,"sha256":"16ea3be1b77ac74959348626fe2801ea096e3927dd4a69641df3f1c08cb0ba2b","contentType":"text/javascript"},{"id":"d1421898-62e4-58c1-a1f3-bfd32b532535","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/d1421898-62e4-58c1-a1f3-bfd32b532535/attachment.mjs","path":"references/scripts/scope-decomposition-runtime/lib/phases.mjs","size":649,"sha256":"6058ab7e442b9ff74289d416b2aa53c9fe4e4c5c13475bd1db92652989e2a63c","contentType":"text/javascript"},{"id":"383fbcff-9645-5b7f-b56a-9cf6074c9d3f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/383fbcff-9645-5b7f-b56a-9cf6074c9d3f/attachment.mjs","path":"references/scripts/scope-decomposition-runtime/lib/store.mjs","size":3866,"sha256":"10a8d03c8e6464152990981e937af3d673b0d352b8852408a3ac1498ef7b5174","contentType":"text/javascript"},{"id":"dab0a9be-6055-5e0a-98bb-adc1869e095c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/dab0a9be-6055-5e0a-98bb-adc1869e095c/attachment.mjs","path":"references/scripts/story-execution-runtime/cli.mjs","size":9993,"sha256":"c8b45cedf3d517e4a3720aaafbd54b68f0c2db4a36d0627a826276fd1b46d034","contentType":"text/javascript"},{"id":"3971bd66-26db-5ded-b5f4-8dfe4c15c714","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3971bd66-26db-5ded-b5f4-8dfe4c15c714/attachment.mjs","path":"references/scripts/story-execution-runtime/lib/guards.mjs","size":10377,"sha256":"4a718f9972a8382ab40c863287db9f23d07d16817512121188dfb87e6c0c9408","contentType":"text/javascript"},{"id":"20eddaa4-a2e4-5021-9949-4292bf4e7ac6","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/20eddaa4-a2e4-5021-9949-4292bf4e7ac6/attachment.mjs","path":"references/scripts/story-execution-runtime/lib/phases.mjs","size":796,"sha256":"0b86a7fafc7eecae9a919feb3d4d5ae07bc2fb29c218f34f0476b59c1694f936","contentType":"text/javascript"},{"id":"ff15957a-eaf0-5e9c-ae8f-5e78589fdc54","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ff15957a-eaf0-5e9c-ae8f-5e78589fdc54/attachment.mjs","path":"references/scripts/story-execution-runtime/lib/store.mjs","size":12170,"sha256":"40db68957c99911b1e962e69a0751c535f4ebcbfeab5fad1297332bd8c8848e9","contentType":"text/javascript"},{"id":"12048ae8-073c-5d26-9e51-0e1c475721c5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/12048ae8-073c-5d26-9e51-0e1c475721c5/attachment.mjs","path":"references/scripts/story-execution-runtime/test/loop-health.mjs","size":2649,"sha256":"764399aa1521618ea692d012952faf8003ba752d47dbb73677e8ec3f222aa96a","contentType":"text/javascript"},{"id":"300e17ea-cf77-5c93-85f0-d183702b0b9f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/300e17ea-cf77-5c93-85f0-d183702b0b9f/attachment.mjs","path":"references/scripts/story-gate-runtime/cli.mjs","size":9408,"sha256":"b48b2b0f0022f0cece2bc8ce0316edbf9d4f74aac25427cb3f433719e4fdbfb7","contentType":"text/javascript"},{"id":"1eca143c-1037-59ab-8df2-f774e0734a06","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1eca143c-1037-59ab-8df2-f774e0734a06/attachment.mjs","path":"references/scripts/story-gate-runtime/lib/guards.mjs","size":5578,"sha256":"45ed3b3173e9ead02d3893b1616053850738c8a7572835025db3d1f6a0acd420","contentType":"text/javascript"},{"id":"3a7b2ec2-c1b7-5a63-b482-f513ee871cbc","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3a7b2ec2-c1b7-5a63-b482-f513ee871cbc/attachment.mjs","path":"references/scripts/story-gate-runtime/lib/phases.mjs","size":712,"sha256":"0cc16e2ed1eb3ca10789e0163dc62a2a4e89416469a727034727631956ecb990","contentType":"text/javascript"},{"id":"2a81eb9b-11b5-5880-bcc0-4cea88420809","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2a81eb9b-11b5-5880-bcc0-4cea88420809/attachment.mjs","path":"references/scripts/story-gate-runtime/lib/store.mjs","size":5818,"sha256":"1e246fe2c2a8114e92184d2d72b3305ce3fec7616c28aea98e7dc1c5d428cda3","contentType":"text/javascript"},{"id":"133b915e-0a6c-57f0-9be0-9fb8f5671ec6","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/133b915e-0a6c-57f0-9be0-9fb8f5671ec6/attachment.mjs","path":"references/scripts/story-planning-runtime/cli.mjs","size":6794,"sha256":"4e5170f849bbeb4de04acebc8733e40cbc211aada70a5c07d8a3d4e48e254d21","contentType":"text/javascript"},{"id":"7ad4a33d-9dfe-54b0-8436-1beba2c2697a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/7ad4a33d-9dfe-54b0-8436-1beba2c2697a/attachment.mjs","path":"references/scripts/story-planning-runtime/lib/guards.mjs","size":4101,"sha256":"4529a93433a4b3b9595b0d718b7ab38233ca0dd24ab60f998b06a1c4caa7e714","contentType":"text/javascript"},{"id":"20b4c4b1-aa09-5d09-b5fa-79daa0569af8","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/20b4c4b1-aa09-5d09-b5fa-79daa0569af8/attachment.mjs","path":"references/scripts/story-planning-runtime/lib/phases.mjs","size":682,"sha256":"cef984df6b57330a56946eabc92e132a40039fc382ff69fcfb780be82080c6e2","contentType":"text/javascript"},{"id":"f066c857-6297-5cb2-b3c3-a9ccb8ecb7e7","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f066c857-6297-5cb2-b3c3-a9ccb8ecb7e7/attachment.mjs","path":"references/scripts/story-planning-runtime/lib/store.mjs","size":2895,"sha256":"0a99a673e178f85876dbedef861fe3f3bf50767f0b9d3f7c07fb38bddcd79c9a","contentType":"text/javascript"},{"id":"1d1f9636-92b9-596a-b6b0-46512882b642","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1d1f9636-92b9-596a-b6b0-46512882b642/attachment.mjs","path":"references/scripts/story-planning-runtime/test/smoke.mjs","size":5488,"sha256":"a7c64c1ace44e0d4c51001517955599f96ec65dd69c9106f8dc1d0bf2d62e81d","contentType":"text/javascript"},{"id":"ed2270ea-8a11-53e2-aac0-e6aa4c0c9913","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ed2270ea-8a11-53e2-aac0-e6aa4c0c9913/attachment.mjs","path":"references/scripts/task-planning-runtime/cli.mjs","size":6812,"sha256":"52dfcc1fde2febdd1f51a041867dbc63417625f96c3d00e3e29bc9de65826e1b","contentType":"text/javascript"},{"id":"2c2d32df-872f-5445-82a6-d500f6da7e8e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2c2d32df-872f-5445-82a6-d500f6da7e8e/attachment.mjs","path":"references/scripts/task-planning-runtime/lib/guards.mjs","size":3858,"sha256":"b9830cc3e0c5ad5e013e0285747b46ea3777778ca177e8762c5d7134715ecde5","contentType":"text/javascript"},{"id":"35703e78-a744-5bc4-98a6-f494de2b10b4","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/35703e78-a744-5bc4-98a6-f494de2b10b4/attachment.mjs","path":"references/scripts/task-planning-runtime/lib/phases.mjs","size":653,"sha256":"57ecdf81db89530390453e97806cead7b284a61b43ada0797658367a92ed890f","contentType":"text/javascript"},{"id":"a7d78dd2-affc-5c25-b2de-c7362ac92006","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/a7d78dd2-affc-5c25-b2de-c7362ac92006/attachment.mjs","path":"references/scripts/task-planning-runtime/lib/store.mjs","size":3008,"sha256":"3dabd0392a6c6165fe2bfe944ccaedaa96e3a254719bb9db84471a91de9d082f","contentType":"text/javascript"},{"id":"1c20b8c1-b000-5b95-a21f-8fc259c3b51b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1c20b8c1-b000-5b95-a21f-8fc259c3b51b/attachment.mjs","path":"references/scripts/task-planning-runtime/test/smoke.mjs","size":3971,"sha256":"36b18e77fd7e4d1b35653441d86916bdf92a143d6accd8d5c4366a3f3b18460c","contentType":"text/javascript"},{"id":"dba4e30e-8c58-53bb-a0e7-5b9b21a1f16f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/dba4e30e-8c58-53bb-a0e7-5b9b21a1f16f/attachment.mjs","path":"references/scripts/test-planning-runtime/cli.mjs","size":7678,"sha256":"7a729327018df7a2c6ed863200c8bd35d2cb7f2ab49d35ae66277b4394a950e4","contentType":"text/javascript"},{"id":"8477a25b-c2cf-5b43-b4c6-74f49180aa85","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8477a25b-c2cf-5b43-b4c6-74f49180aa85/attachment.mjs","path":"references/scripts/test-planning-runtime/lib/guards.mjs","size":3873,"sha256":"6204646029b0f2dd3c09e1479e13494c74b0f4b6312dda518fb98f46146f31cc","contentType":"text/javascript"},{"id":"c37189ee-8e26-5d03-bd07-9ec7b17b137e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c37189ee-8e26-5d03-bd07-9ec7b17b137e/attachment.mjs","path":"references/scripts/test-planning-runtime/lib/phases.mjs","size":629,"sha256":"bec851e02cc44b104061b8eb1b4c37c37a0ed944df9af0f695a6e958330f6c24","contentType":"text/javascript"},{"id":"19dac142-9acb-5bb4-b506-a0880b40e661","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/19dac142-9acb-5bb4-b506-a0880b40e661/attachment.mjs","path":"references/scripts/test-planning-runtime/lib/store.mjs","size":3782,"sha256":"513a29e1d67f310bfec8f38220f17736717bd3471be545cf67cf54a7ef14e0d3","contentType":"text/javascript"},{"id":"44fda338-d322-59be-8656-9f0f1efdac96","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/44fda338-d322-59be-8656-9f0f1efdac96/attachment.md","path":"references/skill_contract.md","size":6431,"sha256":"e279e2e21e6d2a1554ebdf798c51a51ecf09319966bea94d860a8c1593a68f3c","contentType":"text/markdown; charset=utf-8"},{"id":"9d5a0019-5a84-596b-ab59-193f5d4e6940","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/9d5a0019-5a84-596b-ab59-193f5d4e6940/attachment.md","path":"references/structural_review.md","size":10550,"sha256":"cb288598686d88e7e720d4e00b19e3c9b192a825669ae1ed07b8b5171c2b67b8","contentType":"text/markdown; charset=utf-8"},{"id":"c21b6eaf-6ee6-5a6e-994f-ae67c9f9fb86","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c21b6eaf-6ee6-5a6e-994f-ae67c9f9fb86/attachment.md","path":"references/templates/audit_worker_report_template.md","size":1686,"sha256":"54dc1ab21118b6bc86944950682698a246fe7b83133496556d2152c02c0b813c","contentType":"text/markdown; charset=utf-8"},{"id":"a5dc2ec9-ec19-5ba6-9813-33501ee0b1b3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/a5dc2ec9-ec19-5ba6-9813-33501ee0b1b3/attachment.md","path":"references/two_layer_detection.md","size":1504,"sha256":"9ed77a11fb7478157fc684eb831721561c670e3e973b75fe4932651d77131c5c","contentType":"text/markdown; charset=utf-8"}],"bundle_sha256":"5887a623e6c921ff941cba74b3173b4a6457831c5beca947f4a1dc0b7cf212ba","attachment_count":84,"text_attachments":84,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":"plugins/documentation-pipeline/skills/ln-162-skill-reviewer/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"software-engineering","category_label":"Engineering"},"exact_dupes_collapsed_into_this":0},"license":"MIT","version":"v1","category":"software-engineering","import_tag":"clean-skills-v1","description":"Reviews skills (D1-D11 + M1-M6 criteria) or .claude/commands for quality. Use when validating skill correctness before release."}},"renderedAt":1782981876387}

Paths: File paths ( , ) are relative to this skill directory. ln-162-skill-reviewer Type: L3 Worker (standalone-capable) Category: 1XX Documentation Pipeline Universal reviewer with two modes: - for - for - repo suite for this skills repository when / is requested or the current repo is Plan Mode behavior: Phases 1-4 and 6-7 are research. Run them fully in Plan Mode, write the report plus fix list into the plan, and apply edits only after approval. --- Mode Detection | Condition | Mode | Review Profile | |-----------|------|----------------| | files exist in CWD | SKILL | Full D1-D11 + M1-M6…